{"id":523,"date":"2021-02-03T21:16:29","date_gmt":"2021-02-03T21:16:29","guid":{"rendered":"https:\/\/badbit.vc\/?p=523"},"modified":"2021-02-05T08:28:14","modified_gmt":"2021-02-05T08:28:14","slug":"windowsapi-voodoo","status":"publish","type":"post","link":"https:\/\/badbit.vc\/index.php\/2021\/02\/03\/windowsapi-voodoo\/","title":{"rendered":"WindowsAPI voodoo"},"content":{"rendered":"\n<p>This will be a multi part series where I will be publishing my notes taken while diving into the mysterious world of WinAPI programming. When it comes to WinAPI, there&#8217;s no better reference than <a href=\"https:\/\/docs.microsoft.com\/en-us\/\">MSDN itself!<\/a> And also, there&#8217;s no escape to it. To fully comprehend the mystery, we will have to refer to it no matter what.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Part 1 &#8211; Enumerating processes on Windows<\/h2>\n\n\n\n<p>The goal of the resultant binary would be to enumerate all the processes running on a Windows machine. The result would be produced on stdout consisting of the following details for each running process:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Process ID<\/li><li>Handles<\/li><li>Threads<\/li><li>Process Name<\/li><li>SID<\/li><li>Account Name<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><em>Take aways:<\/em><\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li>Understanding of Tokens<\/li><li>Understanding of Token privileges<\/li><li>Enabling \/ Disabling privileges of a process<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><em>Some WinAPI specific terminology before we proceed:<\/em><\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li><strong><em>LPSTR<\/em><\/strong> &#8211; Long Pointer String<\/li><li><strong><em>LUID<\/em><\/strong> &#8211; Describes a local identifier<\/li><li><strong><em>_T<\/em><\/strong> &#8211; stands for \u201ctext\u201d. Used where UNICODE support is required<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><em>Some must-knows:<\/em><\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li>When a user logs-in, the LSA creates a <strong>token<\/strong> for a user. This token is given to every single process created for that user. The Token contains:<ul><li>User&#8217;s SID<\/li><li>Group SIDs<\/li><li>Privileges<\/li><\/ul><\/li><li>Based on the SID and what the user is permitted to do, the Token holds the respective privileges<\/li><li>Not all privileges are enabled by default<\/li><li>A process has the ability to enable\/disable available privileges<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<p><strong>The execution flow will be as follows:<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><code>WTSEnumerateProcess<\/code> &#8211; To enumerate all the running processes<\/li><li><code>ConvertSidToStringSid<\/code> &#8211; To convert the SID of the fetched process into string for displaying<\/li><li><code>LookupAccountSid<\/code> &#8211; To enumerate the domain name and the account name of the process owner<\/li><li><code>LookupPrivilegeValue<\/code> &#8211; To select &#8220;SeDebugPrivilege&#8221; as the privilege value to perform further opertions<\/li><li><code>OpenProcessToken<\/code> &#8211; To open a handle to the current process&#8217;s (<em>GetCurrentProcess()<\/em>) Token to manipulate the privileges<\/li><li><code>AdjustTokenPrivilege<\/code> &#8211; To add the &#8220;SeDebugPriv&#8221; to the process<\/li><li>Print the processes<\/li><\/ol>\n\n\n\n<p>A brief description of the APIs used to achieve the above goal:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. WTSEnumerateProcess<\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li>Retrieves information about the active processes on a specified Remote Desktop Session Host (RD Session Host) server.<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nBOOL WINAPI WTSEnumerateProcessesEx\n(\n_In_ HANDLE hServer,\n_Inout_ DWORD *pLevel,\n_In_ DWORD SessionID,\n_Out_ LPSTR *ppProcessInfo,  \n_Out_ DWORD *pCount\n);\n<\/pre><\/div>\n\n\n<p><a href=\"https:\/\/docs.microsoft.com\/en-us\/windows\/win32\/api\/wtsapi32\/nf-wtsapi32-wtsenumerateprocessesa\">Windows Docs &#8211; WTSEnumerateProcess<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2. ConvertSidToStgringSid<\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li>Since SID is a variable length structure, we need to convert it into a suitable string for displaying it on stdout<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nBOOL ConvertSidToStringSidA(\n  PSID  Sid,\n  LPSTR *StringSid\n);\n<\/pre><\/div>\n\n\n<p><a href=\"https:\/\/docs.microsoft.com\/en-us\/windows\/win32\/api\/sddl\/nf-sddl-convertsidtostringsida\">Windows Docs &#8211; ConvertSidToStgringSid<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3. LookUpAccountSid<\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li>API required to fetch the process owner&#8217;s \/ user&#8217;s domain and username<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nBOOL LookupAccountSidA(\n  LPCSTR        lpSystemName,\n  PSID          Sid,\n  LPSTR         Name,\n  LPDWORD       cchName,\n  LPSTR         ReferencedDomainName,\n  LPDWORD       cchReferencedDomainName,\n  PSID_NAME_USE peUse\n);\n<\/pre><\/div>\n\n\n<p><a href=\"https:\/\/docs.microsoft.com\/en-us\/windows\/win32\/api\/winbase\/nf-winbase-lookupaccountsida\">Windows Docs &#8211; LookupAccountSid<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">4. LookUpPrivilegeValue<\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li>Fix on the privilege we need to enable. SeDebugPriv in our case<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nBOOL LookupPrivilegeValueA(\n  LPCSTR lpSystemName,\n  LPCSTR lpName,\n  PLUID  lpLuid\n);\n<\/pre><\/div>\n\n\n<p><a href=\"https:\/\/docs.microsoft.com\/en-us\/windows\/win32\/api\/winbase\/nf-winbase-lookupprivilegevaluea\">Windows Docs &#8211; LookUpPrivilegeValue<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">5. OpenProcessToken<\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li>Opening the access token of the current process to modify it. This API requires a handle to the process. We can get the same by using GetCurrentProcess() which opens a pseudo-handle to our current process<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nBOOL OpenProcessToken(\n  HANDLE  ProcessHandle,\n  DWORD   DesiredAccess,\n  PHANDLE TokenHandle\n);\n<\/pre><\/div>\n\n\n<p><a href=\"https:\/\/docs.microsoft.com\/en-us\/windows\/win32\/api\/winbase\/nf-winbase-lookupaccountsida\">Windows Docs &#8211; OpenProcessToken<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">6. AdjustTokenPrivilege<\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li>Lastly, modifying the privileges with the desired privileges.<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nBOOL AdjustTokenPrivileges(\n  HANDLE            TokenHandle,\n  BOOL              DisableAllPrivileges,\n  PTOKEN_PRIVILEGES NewState,\n  DWORD             BufferLength,\n  PTOKEN_PRIVILEGES PreviousState,\n  PDWORD            ReturnLength\n);\n<\/pre><\/div>\n\n\n<p><a href=\"https:\/\/docs.microsoft.com\/en-us\/windows\/win32\/api\/winbase\/nf-winbase-lookupaccountsida\">Windows Docs &#8211; AdjustTokenPrivilege<\/a><\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<p><em>Alright, enough of the theory. Show me the damn code!<\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Header file for enabling the SeDebugPrivilege<\/h2>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n\/\/ **The following code enables the SeDebugPrivilege for the current process**\n\/\/ Source - PentesterAcademy&#039;s - Windows API Exploitation Recipes: Processes, Tokens and Memory RW series.\n#include &lt;TlHelp32.h&gt;\nBOOL enablePriv(void) {\n    \/\/Fetch privilege value for SeDebugPriv\n    \/\/ LookupPrivilegeValue\n    LUID    privLUID;\n    if (!LookupPrivilegeValue(\n        NULL,\n        _T(&quot;SeDebugPrivilege&quot;),\n        &amp;privLUID\n        ))\n    {\n        ErrorExit(TEXT(&quot;LookupPrivilegeValue()&quot;));\n    }\n    \/\/ Setting up Token Privileges\n    TOKEN_PRIVILEGES tp;\n    tp.PrivilegeCount = 1; \/\/ count of Privileges to be modified\n    tp.Privileges&#x5B;0].Luid = privLUID; \/\/ The LUID of the privilege to be modified \n    tp.Privileges&#x5B;0].Attributes = SE_PRIVILEGE_ENABLED; \/\/ enable this privilege\n    \/\/ Setting up parameters for OpenProcessToken API\n    HANDLE  currentProcessHandle = GetCurrentProcess();\n    HANDLE  processToken; \/\/ A pointer to a handle that identifies the newly opened access token when the function returns. Will be required for AdjustPriv API\n    \/\/ TOKEN_ADJUST_PRIVILEGES  Required to enable or disable the privileges in an access token.\n    if (!OpenProcessToken(currentProcessHandle, TOKEN_ADJUST_PRIVILEGES, &amp;processToken))\n    {\n        ErrorExit(TEXT(&quot;LookupPrivilegeValue()&quot;));\n    }\n    \/\/ Enabling privileges in the cureent processes&#039;s Token\n    if (!AdjustTokenPrivileges(processToken, FALSE, &amp;tp, 0, NULL, NULL))\n    {\n        ErrorExit(TEXT(&quot;AdjustTokenPrivileges&quot;));\n    }\n    return TRUE;\n}\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Main source to enumerate processes:<\/h2>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n\/\/ **The following code enumerates processes on the system. Tested on Windows 7\/10.**\n\/\/ Source - PentesterAcademy&#039;s - Windows API Exploitation Recipes: Processes, Tokens and Memory RW series.\n#include &lt;Windows.h&gt;\n#include &lt;tchar.h&gt;\n#include &lt;WtsApi32.h&gt;\n#include &lt;sddl.h&gt;\n#include &lt;iostream&gt;\n#include &quot;Header.h&quot;\n#include &quot;SeDebug.h&quot;\n#include &lt;strsafe.h&gt;\n#pragma comment(lib, &quot;wtsapi32&quot;)\n#pragma comment(lib, &quot;Advapi32&quot;)\n#define MAX_ACCOUNTNAME_LEN 1024\n#define MAX_DOMAINNAME_LEN 1024\nint main(void)\n{\n    \/\/ Enabling SeDebugPrivilege\n    enablePriv();\n    DWORD level = 1;\n    PWTS_PROCESS_INFO_EX processListing = NULL;\n    DWORD processCount = 0;\n    DWORD dw = GetLastError();\n    if (!WTSEnumerateProcessesEx(\n        WTS_CURRENT_SERVER_HANDLE,\n        &amp;level,\n        WTS_ANY_SESSION,\n        (LPTSTR*)&amp;processListing,\n        &amp;processCount))\n    {\n        ErrorExit(TEXT(&quot;WTSEnumerateProcessesEx&quot;));\n        \/\/std::cout &lt;&lt; &quot;Failed with error code: %d&quot; &lt;&lt; dw;\n    }\n    _tprintf(_T(&quot;Processes found: %d\\n\\n&quot;), processCount);\n    _tprintf(_T(&quot;#\\tPID\\tHandles\\tThreads\\tProcess Name\\tSID\\tAccount\\n\\n&quot;));\n    LPTSTR stringSID = NULL;\n    PWTS_PROCESS_INFO_EX originalPtr = processListing;\n    for (DWORD counter = 1; counter &lt;= processCount; counter++)\n    {\n        _tprintf(_T(&quot;%d\\t&quot;), counter);\n        _tprintf(_T(&quot;%d\\t&quot;), processListing-&gt;ProcessId);\n        _tprintf(_T(&quot;%d\\t&quot;), processListing-&gt;HandleCount);\n        _tprintf(_T(&quot;%d\\t&quot;), processListing-&gt;NumberOfThreads);\n        _tprintf(_T(&quot;%s\\t&quot;), processListing-&gt;pProcessName);\n        \/\/ Printing the SID and associated accounts\n        \/\/ MSDN - https:\/\/docs.microsoft.com\/en-us\/windows\/win32\/api\/sddl\/nf-sddl-convertsidtostringsida\n        if (!ConvertSidToStringSid(\n            processListing-&gt;pUserSid,\n            &amp;stringSID))\n        {\n            _tprintf(_T(&quot;-\\t&quot;));\n            \/\/ErrorExit(TEXT(&quot;ConvertSidToStringSid&quot;));\n            \/\/std::cout &lt;&lt; &quot;Failed with error code: %d&quot;, dw;\n        }\n        else\n        {\n            _tprintf(_T(&quot;%s\\t&quot;), stringSID);\n            LocalFree((HLOCAL)stringSID);\n        }\n        TCHAR accountName &#x5B;MAX_ACCOUNTNAME_LEN];\n        DWORD bufferLen = MAX_ACCOUNTNAME_LEN;\n        TCHAR domainName&#x5B;MAX_DOMAINNAME_LEN];\n        DWORD domainNameBufferLen = MAX_DOMAINNAME_LEN;\n        SID_NAME_USE peUse;\n        if (!LookupAccountSid(\n            NULL,\n            processListing-&gt;pUserSid,\n            accountName,\n            &amp;bufferLen,\n            domainName,\n            &amp;domainNameBufferLen,\n            &amp;peUse)\n            )\n        {\n            \/\/ErrorExit(TEXT(&quot;LookupAccountSid&quot;));\n            _tprintf(_T(&quot;\\n&quot;));\n        }\n        else\n        {\n            _tprintf(_T(&quot;%s\\\\%s\\n&quot;), domainName, accountName);\n        }\n        processListing++;\n    }\n    if (!WTSFreeMemoryEx(WTSTypeProcessInfoLevel1, originalPtr, processCount))\n    {\n        ErrorExit(TEXT(&quot;WTSFreeMemoryEx&quot;));\n        \/\/std::cout &lt;&lt; &quot;Failed with error code: %d&quot; &lt;&lt; dw;\n    }\n    processListing = NULL;\n    _tprintf(_T(&quot;\\n\\nDone! Press any key to exit. \\n&quot;));\n    getchar();\n    return 0;\n}\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Output<\/h2>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1011\" height=\"531\" src=\"https:\/\/badbit.vc\/wp-content\/uploads\/2021\/02\/processEnum_Output.jpg\" alt=\"\" class=\"wp-image-524\" srcset=\"https:\/\/badbit.vc\/wp-content\/uploads\/2021\/02\/processEnum_Output.jpg 1011w, https:\/\/badbit.vc\/wp-content\/uploads\/2021\/02\/processEnum_Output-300x158.jpg 300w, https:\/\/badbit.vc\/wp-content\/uploads\/2021\/02\/processEnum_Output-768x403.jpg 768w, https:\/\/badbit.vc\/wp-content\/uploads\/2021\/02\/processEnum_Output-850x446.jpg 850w\" sizes=\"auto, (max-width: 1011px) 100vw, 1011px\" \/><\/figure>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<p><\/p>\n\n\n\n<p>The above notes have been taken while following PentesterAcademy&#8217;s &#8211; Windows API Exploitation Recipes: Processes, Tokens and Memory RW <a href=\"https:\/\/www.pentesteracademy.com\/course?id=31\">series<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This will be a multi part series where I will be publishing my notes taken while diving into the mysterious world of WinAPI programming. When it comes to WinAPI, there&#8217;s no better reference than MSDN itself! And also, there&#8217;s no escape to it. To fully comprehend the mystery, we will have to refer to it&#8230;<\/p>\n","protected":false},"author":1,"featured_media":538,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[18],"tags":[25,23,20,21,22,19,24],"class_list":["post-523","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-windowsapi","tag-c","tag-privileges","tag-processenumeration","tag-sedebugprivilege","tag-tokens","tag-winapi","tag-windows-programming"],"_links":{"self":[{"href":"https:\/\/badbit.vc\/index.php\/wp-json\/wp\/v2\/posts\/523","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/badbit.vc\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/badbit.vc\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/badbit.vc\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/badbit.vc\/index.php\/wp-json\/wp\/v2\/comments?post=523"}],"version-history":[{"count":16,"href":"https:\/\/badbit.vc\/index.php\/wp-json\/wp\/v2\/posts\/523\/revisions"}],"predecessor-version":[{"id":546,"href":"https:\/\/badbit.vc\/index.php\/wp-json\/wp\/v2\/posts\/523\/revisions\/546"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/badbit.vc\/index.php\/wp-json\/wp\/v2\/media\/538"}],"wp:attachment":[{"href":"https:\/\/badbit.vc\/index.php\/wp-json\/wp\/v2\/media?parent=523"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/badbit.vc\/index.php\/wp-json\/wp\/v2\/categories?post=523"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/badbit.vc\/index.php\/wp-json\/wp\/v2\/tags?post=523"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}