<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jasem Al-Sadi on Medium]]></title>
        <description><![CDATA[Stories by Jasem Al-Sadi on Medium]]></description>
        <link>https://medium.com/@jasemalsadi?source=rss-e4a893265a86------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*GCIkTS9mUcj5NGS23fNSYA.jpeg</url>
            <title>Stories by Jasem Al-Sadi on Medium</title>
            <link>https://medium.com/@jasemalsadi?source=rss-e4a893265a86------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:43:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jasemalsadi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Intro to Windows Access Control — part 1]]></title>
            <link>https://medium.com/@jasemalsadi/intro-to-windows-access-control-part-1-ff4c20b918e7?source=rss-e4a893265a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff4c20b918e7</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[windows-internals]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[access-control]]></category>
            <dc:creator><![CDATA[Jasem Al-Sadi]]></dc:creator>
            <pubDate>Tue, 23 Mar 2021 02:47:35 GMT</pubDate>
            <atom:updated>2022-01-30T16:37:53.780Z</atom:updated>
            <content:encoded><![CDATA[<h3>Windows Access Control For pentesters — part 1</h3><p><strong>One of the critical area of windows that any Red team operator or penetration tester must knows and have strong foundation is Access Control in Windows. It’s almost the root cause of any Domain Attack path. In this series of article I will go through Internals of Access Control in part 1 and the abuses in part 2.</strong></p><p>Before we start understanding the concepts of Windows Access Control, let’s have a brief overview about the components of the main windows security :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*84DZGxIoEh1r-w3up-RUiA.png" /><figcaption>Windows Security Components — Windows internals book</figcaption></figure><ol><li><strong>WinLogon and LogonUI</strong>: Winlogon is responsible for interactive logon and logoff and monitoring Ctrl-Alt-Del presses. While LogonUI responsible for the UI of the login and custom credential providers. The reason for separation to prevent any buggy custom authentication mechanisms (e.g. Windows Hello authentication ) from crashing winlogon.</li><li><strong>Security Reference Monitor (SRM) : </strong>It’s Lives in the kernel and it’s checks if you really have the sufficient rights to access any windows object. For example, when you get access denied for accessing a file, it’s SRM who reject you 🌝 . It’s has to be the kernel, so no user mode code can manipulate it.</li><li><strong>SAM database:</strong> Stores the registry and local logins.</li><li><strong>Event Logger :</strong> a Service to log security events.</li><li><strong>LSA ISO:</strong> Lsass component incase you enabled Virtual Based security and credential guard to prevent dumping lsass memory.</li><li><strong>LSASS</strong>: You probably already know it, it’s the one who check if your authentication matches the stored one. It uses different components such <strong>AD</strong> if you login to the domain (kerberose dll). if you login locally, it will communicate Local Stored Policy (LSA) (using LSA server and MsV1_01.dll). Once the user authenticated successfully, it will create a token that will represent the security context of that user. Then, that token will be passed to WinLogon to create windows session and create other processes. Each created process will copy your token to perform operation on behalf you.</li></ol><p>So, in this article, I will discuss all the details of how windows allow/deny certain user from doing an operation based on the user token that is generated after successful authentication.</p><h3>Terminologies :</h3><ol><li><strong>Security Principal: </strong>Entity that the Window’s security system recognizes, for example , user , group , Hyper-v VM, service and app container.</li><li><strong>Security Identifier (SID): </strong>Data structure to identify security principles. Windows uses SID to refer to users/group rather than using text.</li><li><strong>Securable objects</strong> are operating system objects (files,pipes, processes, etc.) that can have a security descriptor.</li><li><strong>Security descriptors : </strong>It’s a security structure that determines who can do what with that object. It’s created when the object is created.</li><li><strong>Handle: </strong>When a caller requests access to an object (you try to read file ), It will try to obtain a reference (handle) to that object. The object manager in the kernel checks with the security system (<strong>SRM</strong>) if the caller can obtain a handle to the object.</li><li><strong>Privilege</strong> is a right granted to user/group to perform system wide operations. E.g.SeShutdownPrivilege. This can affect any application running because it’s system wide modification.</li><li><strong>Access rights</strong>: is a right to user/group to perform securable object scope. E.g. ability for admins to write in system32 folder object. Typically access rights are RWX plus some others.<br>In any conflicts, Privilege &gt; Access rights. For example, If I have seDebugPrivilege, I can modify any object in the system regardless of its access rights.</li><li><strong>Access Token:</strong> It’s the object to send it to the OS when requesting to access other objects. <strong>SRM</strong> will check if u have a sufficient rights. The structure of access the token as follow :</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*ufL6IgChEFMbryZeQ7TjhA.png" /></figure><p>And the below an example of an access token of user called Dane used by cmd.exe process :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrJ_1_wrZukXQPbreKR_2g.png" /></figure><h3>A look into Windows Security Descriptor</h3><p>When an object created, a security descriptor is created, it has the answer of who can access this object and right it can access :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*aIpbfvZomFMXcj7w4HXzkw.png" /></figure><pre>typedef struct _SECURITY_DESCRIPTOR {<br>  BYTE                        Revision;<br>  BYTE                        Sbz1;<br>  SECURITY_DESCRIPTOR_CONTROL Control;<br>  PSID                        Owner;<br>  PSID                        Group;<br>  PACL                        Sacl;<br>  PACL                        Dacl;<br>} SECURITY_DESCRIPTOR, *PISECURITY_DESCRIPTOR;</pre><p><strong>Object Owner Sid: </strong>When this object created, a security principal (user/group) created that object.</p><p><strong>Group Sid</strong>: The creator of the object can specify a primary group for the object, if not, it will inherit the group of the creator. Primary group used when login to posix system such as mac. It has nothing to do with the user group memberships.</p><p><strong>DACL</strong>: DACL is just a container for ACE. ACE specifies which users/group can access this object and what rights it has on this object.</p><p><strong>SACL</strong>: logging/audit for DACL when someone attempt to access.</p><p>Example of SACL from GUI :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJa_edXwCrFgjfW4Oyy9Ew.png" /></figure><h3>Determining Access</h3><p>When the principal tries to open handle to a certain object, the following mechanism is done by the object manager and SRM to check if you have the sufficient right to get a handle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJrNcwkJaoJN64VRhNE-CA.png" /><figcaption>A user trying to access a folder</figcaption></figure><p>So, the object manager will check the DACL of the object (folder) , then it found your SID in the list ACE with correct access. It will grant you.</p><p>Let’s have another example where two threads trying to access an object:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*gdf3CoPuHLitcU7RYiMg-g.png" /></figure><p>You can notice Thread A created by <strong>Andrew</strong> and Thread B created by <strong>Jane</strong>.</p><ul><li><strong>Why Thread A not allowed ? <br></strong>Because ACE 1 says access denied for Andrew Access token.</li><li><strong>But ACE 3 says that it’s allowed for anyone ? <br></strong>ACE 1 has more importance than ACE 3. So order it important.</li><li><strong>What if DACL is null (not empty) ? <br></strong>It means allow anyone to access this object at any rights.</li><li><strong>What about Anonymous Access rights ? </strong><br>By default, no rights, unless admin specify for them a right.</li><li><strong>What type of permissions we can get on an object ? It’s only RWX ? <br></strong>It’s called access rights ,there are many more than RWX, which are just bits :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qh-w2nvW0rM4fU5lJHxbxg.png" /><figcaption>Access Rights Bits</figcaption></figure><p>You can see the normal RWX rights are defined in bit 28–31.</p><p>Then, The standard access rights (16–23) can be from the predefined flags:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LxybENptg8b3BpKv3pF1qg.png" /></figure><p>Also, MS can let you define your own Object access rights (from 0–15 bit):</p><p><a href="https://docs.microsoft.com/en-us/windows/win32/sync/synchronization-object-security-and-access-rights">https://docs.microsoft.com/en-us/windows/win32/sync/synchronization-object-security-and-access-rights</a></p><p>Example of Object Specific Rights :</p><p><strong>Processes :<br></strong>• PROCESS_TERMINATE<br>• PROCESS_VM_READ<br>• PROCESS_VM_WRITE<br><strong>Registry Key<br></strong>• KEY_READ<br>• KEY_SET_VALUE<br>• KEY_ENUMERATE_SUB_KEYS</p><p>The bit 24 is to indicate if I have an access to SACL.</p><ul><li><strong>So, how an object modify/get it’s own security descriptor ?</strong></li></ul><p>Using the following windows API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*2NsxwPd1olJcGxEFfcwvQw.png" /></figure><h3>A look into Access Control Entity (ACE)</h3><p>ACE stored in Security Descriptor Definition Language (SDDL) format: <br><a href="https://docs.microsoft.com/en-us/windows/win32/secauthz/ace-strings">https://docs.microsoft.com/en-us/windows/win32/secauthz/ace-strings</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4vBll0hTw0HytdyxJN6DA.png" /><figcaption>ACE format</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xyOMOLtAulehwqVwwjlMGQ.png" /><figcaption>ACE Simplified format</figcaption></figure><p><strong>ace_type</strong>: ACCESS allowed or denied. <br><strong>ace_flags</strong> : A combination of flags for ACE inheritance and child objects :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VpKytzxb4_BfD0gSzFDCpw.png" /><figcaption>Example of ACE flag</figcaption></figure><p><strong>rights</strong>: Like Read, write, write DACL , .. Etc. <br><strong>object_guid and inherit_object_gui</strong>d: I don’t understand it well. <br><strong>Account_sid</strong>: is the SID of the trustee/user.<br>An example of actual raw ACE :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-k-RNcBC4ttl8-kp6SA3YA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*bKRZCOeMzfnE1amrKGbtVQ.png" /></figure><p>ACE SID : S-1–1–0 .</p><h3>A Look into SIDs</h3><p>A sid is an identifier for any security principal, It follow the following structure :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ypi4oFzalwO3jkFKsVNN3Q.png" /></figure><p><strong>S</strong>: Indicates the string is a SID</p><p><strong>1</strong>: Revision Level, Always set to 1.</p><p><strong>5</strong>: Identifier authority in which the SID is created, 5 is the a common one (stands for “NT Authority”).</p><p><strong>21: </strong>It means Domain account. 18 used for local accounts.</p><p><strong>397955417–6268811260188441444</strong> : It’s 48 numbers to make the account unique.</p><p><strong>1010</strong>: Relative ID (RID) used to identify user type in the domain. For example,512 for domain admins. Administrator has 500 RID.</p><p><strong>Common known RIDs :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8fncQ0DvnJf056xxX81ew.png" /></figure><h3><strong>Access Token Object</strong></h3><p>A token is kernel object to identify the security context of a process or thread. It contains the privileges of the user with accounts and groups associated with it. It can be created by login to a different user in the same system using windows API LogonUser .</p><p><strong>User Token != Access Token object : </strong>The user token is an object stored at LSASS.exe after successful authentication of the user. While Access Token is attached to process or thread to give the privilege and rights of the user. However, Lsass.exe creates the access token and pass it to winlogon.exe.</p><p>Every process has primary token. A thread will inherit that token by default. However, it can impersonate a token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AdXMZMubrTR0QoLNYOh8Pg.png" /></figure><p>An Impersonation will allow the thread to execute code in different security context (Access Token) from that of the process owning the thread. An example of Win API to create different token is CoImpersonateClient Com function.</p><p><strong>Impersonation levels :</strong></p><p>This where you will get confused (why Microsoft???) , apparently when you impersonate a token, you are allowing the server to use your token. MS decided to take it further step and limit the server on how far (locally and in the network ) it can use the impersonation. It differentiate each level to based if the server is accessed locally or over a network. The table below summarizes the impersonation level differences :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTfvXySLJRn0matynoM8aQ.png" /></figure><h3>Windows Privileges</h3><p>It’s a right to perform system-level operations such as shutdown the computer, change timezone, .. etc. A list of Windows privileges can be showed in Local Policy editor :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hT9Ut5TBkbDDTAAPz8OKtA.png" /></figure><p>Windows privileges follows SE_*_NAME format and translated to Se*Privilege. For example, SE_DEBUG_NAME (SeDebugPrivilege)privilegee.</p><p>There are 36 windows privileges as per MS doc:</p><p><a href="https://docs.microsoft.com/en-us/windows/win32/secauthz/privilege-constants">Privilege Constants (Winnt.h) - Win32 apps</a></p><h3>Windows Privileges vs User Rights</h3><p>If you returned back to local Security Policy, you will notice something like DenyLogonAsBatch :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbfmgbTxxbwfuFIM0Z3ang.png" /></figure><p>You can notice Log on as a batch has administrator users and other groups, it allows to log in non-interactively. It’s called a user rights because it affects user before it login. If the user not part of log on as batch job, it won’t be able to log in non-interactively.</p><p>While privileges on the other hand, stored in token after user login.</p><p>When a process created most of it’s privileges are disabled by default :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*WuSV4L7s-rZFKhIfEu63WA.png" /></figure><p>Its disabled by default, all what you need is to call Windows API to enable it, so the OS will make sure that you really want to use that privilege.</p><h3>Integrity Levels (IL)</h3><p>Every object in windows has Integrity level property. Integrity level divided into 4 levels:</p><ol><li><strong>Low (AppContainer) integrity level: </strong>UWP processes.</li><li><strong>Medium integrity level (default one): </strong>Standard users.</li><li><strong>High integrity level: </strong>Administrators.</li><li><strong>System (Highest) integrity level: </strong>System services.</li></ol><p><strong>Mandatory Integrity Control (MIC)</strong></p><p>The idea of integrity level to disallow a process with a certain integrity level (e.g. medium) from accessing OS objects with higher integrity level (e.g. High). ILs are represented as SIDs</p><p>○ Low — S-1–16–4096<br>○ Medium (default) — S-1–16–8192<br>○ High — S-1–16–12288<br>○ System — S-1–16–16384</p><p>So, the OS will check the process/thread/object integrity level before checking security descriptor, so integrity level always win:</p><h4><strong>Integrity level &gt; Security descriptor</strong></h4><p>So, it solves the issue of if an attacker able to run malicious code in the browser, it will be running on the system with low integrity level.</p><h3>Conclusion</h3><p>It’s a long post I know 😂, but this is my summary from several books and courses such windows internals course. The next post, I will demonstrate the abuses for almost every component of windows access control.</p><h3>References</h3><ul><li><a href="https://itconnect.uw.edu/wares/msinf/other-help/understanding-sddl-syntax/">Understanding SDDL Syntax</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-security_descriptor">SECURITY_DESCRIPTOR (winnt.h) - Win32 apps</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/com/impersonation-levels">Impersonation Levels (COM) - Win32 apps</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff4c20b918e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detailed Guide of PE Structure for Reversers]]></title>
            <link>https://medium.com/@jasemalsadi/understanding-pe-file-for-reversers-9aa3b59ab13c?source=rss-e4a893265a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aa3b59ab13c</guid>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[windows-internals]]></category>
            <dc:creator><![CDATA[Jasem Al-Sadi]]></dc:creator>
            <pubDate>Tue, 30 Jun 2020 19:23:12 GMT</pubDate>
            <atom:updated>2022-01-29T11:19:16.711Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the things that really fuzz me when I started learning reverse engineering is to get solid understanding for how the portable executable is structured and why it’s structured in that why. So, I decided to be brave and jump to the MS PE specification hoping to get good understanding, but I was wrong 😂</p><p>So, the below (maybe :) a good starting point if you started to get confused about PE structures.</p><p>Before we get to PE file structures, we need to rehash some concepts :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*L_pC12_AM5QO2NsazweOFA.png" /></figure><p>Virtual address (VA) vs relative virtual address RVA: <br>let assume that our address space got it is :<br>0x10000000<br>and the main function located at :<br>0x10001000<br>Then,:<br>VA = 0x10001000<br>RVA. = VA — Base_address = 0x10001000–0x10000000 = 0x00001000.<br>So the RVA is like the offset in memory, it was invented to ease relocations. <br>That why it called Relative to Virtual address.</p><p>The value of RVA of a method/variable is NOT always its offset from the beginning of the file. <br> The RVA of an item will almost always differ from its position within the file on disk</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*S1D2L51CudGLhYwSSYuyxQ.png" /></figure><p>PE file = MS-DOS MZ header + stub program + PE file signature + PE file header + the PE optional header + all of the section headers + all of the section bodies.<br> <br>The PE file format has 11 common predefined sections, but developer can write his own unique section. <br> <br>Each PE file has a debug section but it can be extracted to separate debug file. <br> <br>Most definitions of the PE file attributes exist in WINNT.h file.<br> <br>Structure of a Portable Executable file image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*TzepNt9CiHKyR22r1BM4dg.png" /></figure><h3><strong>1. MS-DOS/Real-Mode Header</strong></h3><p>The main reason for keeping the same structure intact at the beginning of the PE file format is so that, when u create the file in windows 3.1 or newer or MS DOS v2.0 or older, the newly OS ( Greater than windows 3.1 and MS-DOS 2.0 ) will be able to read the MS DOS header and see that it’s an old file, so it will send this message :<br>“This program cannot be run in DOS mode.” <br>And exit, because if the header doesn’t exist, the OS will alert a stupid useless message:<br>“The name specified is not recognized as an internal or external command, operable program or batch file.”</p><p>DOS header Struct :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3uvF8Fnpsmbu_WrkxSMH7w.png" /></figure><h3>2. Real-Mode Stub Program</h3><p>When u want to develop an actual old MS-DOS executable file, u need some code to run as Stub or “backup code” when a new OS doesn’t support your old MS-DOS file.<br> So u need a code to be executed to tell the user that it doesn’t support your OS, the default is alerting the message :<br>“This program cannot be run in DOS mode” <br> But the developer can put any code in the sub and any message.<br> <br>when the MS-DOS executable file is run in MS-DOS OS . The user can specify a different stub by using the <strong>/STUB linker</strong> option.</p><h3>3. PE Signature and File Header</h3><p>The PE file signature address = base_address + e_lfanew == NTSIGNATURE, e_lfanew will point us to the start of the COFF header which is the start of the NT header :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OVMxtwzfmTkJz7fOcTZMw.png" /></figure><p>We can define it as macro “constant” c variable :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwi1DqQoOn2Qowgmi9SHkw.png" /></figure><p><strong>Note</strong>: “a” input means pointer to the PE file address in the memory.</p><p>File signatures specifies the target OS version. The size of it signature differs from version to version but in general it’s before PE file header.<br> <br>To determine the type of the file from the signature, the following code :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6VfzA090SO-w3NWKTflnXg.png" /></figure><p>The PE file header is defined as struct in winNT.h file :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9ldsNsRZAF_mJTGmoE7Jw.png" /><figcaption>PE file header struct</figcaption></figure><p>You can see example of Characteristics flag in tools like CFF explorer :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*nLt-jjJkulQUifGN-Ftx9g.png" /></figure><h3>4. PE Optional Header:</h3><p>The size of it is 224 Bytes, it’s directly after the file header <br>#define OPTHDROFFSET(a) ((LPVOID)((BYTE *)a + \<br> ((PIMAGE_DOS_HEADER)a)-&gt;e_lfanew + SIZE_OF_NT_SIGNATURE + \<br> sizeof (IMAGE_FILE_HEADER)))<br>// IMAGE_FILE_HEADER is struct defined above</p><p>The optional header contains most important information such as the entry point, preferred base address, section alignment and so forth. <br>It’s long one, but we will discuss important fields. We can separate the fields into :<br><strong>1. Standard Fields.<br></strong>First, note that the structure is divided into “Standard fields” and “NT additional fields.” The standard fields are those common to the Common Object File Format (COFF), which most UNIX executable files use.<br><strong>2. Windows NT Additional Fields.<br></strong>The additional fields added to the Windows NT PE file format provide loader support for much of the Windows NT-specific process behavior.</p><p>I detailed every element of the PE optional image header struct :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nlVDqV_tdgmA3oOt0eQRkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V7_vL8RXy5VfIc3TXEPXaA.png" /></figure><p>Subsystem field possible targets :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*2USoptIqQ0GrhehFuG7nDQ.png" /></figure><p>Data Directories: Think of them as pointers to table or string that Windows uses. Each directory will contain a struct that will point u to the stating point of the table/string :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2zDovrEP1gZcLbknML-2A.png" /></figure><p>They are loaded into the memory and used in run time.<br>There are 16 possible data directory we can generate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9b6oTitxKVDG7Q3NQgboQ.png" /></figure><p>Can we get the location of a certain Data Directory from VirtualAddress in the above struct ? <br>No, because the VA is added from the baseAddreess which might not be the same in memory, also the data directory itself is inside the a section, to illustrate it :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeJwq7RtORGxgRiSZrgDEA.png" /></figure><p>So the virtual address in the data directory struct in an offset only inside the body that holding it. <br>Note: imageBase/Base Address in our case is 0 since the file is not loaded to memory and we are inspecting it on the disk</p><h3>5. PE File Sections</h3><p>PE file consists of many sections, each section = header section + body section = code + data + resources + executable information.<br><strong>1. Section header:<br></strong>Located after the optional header, each is 40 Bytes with no padding between each section header. All of them put in sequential order. Example :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*47IeWOf9DY5H9Bce5ynGHg.png" /></figure><p>The section header is struct defined in WINNT.h file :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zNpM-K36LD6sZlJ-8x4FhQ.png" /></figure><p>Characteristics important values :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*ID5f5e5baRVO7ahNuRZBBA.png" /></figure><p>How do you go about getting section header information for a particular section? <br>Since each of the sections header sequentially ordered, we can loop them and compare with the name because the name is unique. <br>The following function can be used:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71b635fdc951428238ca0a1087e3e9d4/href">https://medium.com/media/71b635fdc951428238ca0a1087e3e9d4/href</a></iframe><p><strong>2. Section body <br></strong>To define a new custom section, u need to pass to the compiler compiler option -NT — . <br><strong>A) .text section <br></strong>It contains the executable code, Windows NT compiler combines all the code segments into on single section “.text section”, because it’s easier to the memory manger to manage the code base. <br>Note: malware authors can put a code in any section and then later jump to that section. The default behavior for the loader is to go to the text section to execute some code but nothing prevent to the developer to jump to another section that contains executable code. <br> <br>The .text section started with Import Address Table (IAT) , IAT is just an array of fixed addresses of the functions used in the .text section. These jumps are Windows API’s functions. <br> <br> <br>The loader takes these fixed addresses and substitute them with another addresses that point to the memory locations of the corresponding library functions. Because these function might be loaded in a different address than the one in IAT array. <br>After the IAT table, the entry point of the executable code. <br> <br>So the loader finds the IAT table ? <br>The IMAGE optional header struct contains a field called “AddressOfEntryPoint”, it used to find the entry point address of the executable code, then the loader move back to get the last jumps of the IAT table, then it goes backward to get the starting point of the IAT table. <br>The loader relies on the fact that the IAT occurs immediately before the entry point and each entry in the IAT is the same size.<br> <br><strong>B) .bss section <br></strong> <br>It stands for Better Save Space, it contains all uninitialized data. e.g. static variables. Not all data items need to have values before the program begins running. When you’re reading data from a disk file, for example, you need to have a place for the data to go after it comes in from disk. So .bss only here to hold the size (bytes) needed for the uninitialized variable. So the main objective of this strategy is to reduce binary size in disk and allowing faster loading time. <br>For example, let see this code :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ng--RCfOGf04UeaSohwL5w.png" /></figure><p>Variable ”a” will be in the data section while “b” will be in the .bss section , Once the program is loaded, the distinction becomes immaterial. At run time, b occupies 20 * sizeof(int) bytes.<br><strong>C) .rdata section :<br></strong> <br>read-only data, such as literal strings, constants, and debug directory information.<br> <br><strong>D) .data section :<br></strong> <br>Variables that are application or module global. Also initialized variables. <br> <br><strong>E) .rsrc Resource section :<br></strong> <br>It contains resource such as images, videos, icons, strings. <br>What the difference between the string stored in the resource section and the strings stored in the .rdata section ? <br>Strings are located in either resources or in read-only data sections of PE file, the most common is in the .rdata section. So Microsoft gives many ways to store strings.<br> <br>The resource directory is stored in a tree structure, each branch equal one resource, u can think of it as the file structure of linux, where there is a root directroy, <br>and it contains sub directories and the sub directories might contains sub directories or might contains raw data (file). <br>To illustrate more, let’s look at this resource example of a PE file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ju7l-kK4mYaz3gZqUDj04Q.png" /></figure><p>So if t we take it as analogy : <br>1. the root node of the image above correspond to the root directory in the file system. The root node follow IMAGE_RESOURCE_DIRECTORY structure. <br>2. The children can be represented in two types :</p><p><strong>a. </strong>Raw data or called file (file system terminology) ===&gt; correspond to raw data (pink boxes) , they called “entry” in PE terminology. They follow _IMAGE_RESOURCE_DATA_ENTRY struct. They are the leafs of the tree. <br>The _IMAGE_RESOURCE_DATA_ENTRY struct :</p><pre>typedef struct _IMAGE_RESOURCE_DATA_ENTRY {<br>    ULONG   OffsetToData;<br>    ULONG   Size;<br>    ULONG   CodePage;<br>    ULONG   Reserved;<br>} IMAGE_RESOURCE_DATA_ENTRY, *PIMAGE_RESOURCE_DATA_ENTRY;</pre><p><strong>b. </strong>Subdirectory (file system terminology) ===&gt; correspond to another _IMAGE_RESOURCE_DIRECTORY structure in the resource section. The job of this struct to knows the children resources of it. <br> Because sometimes, an image/resource may contains multiple sub images/resource children inside it, so the same thing in linux, directory might have multiple sub directories.</p><p>The struct definition :</p><pre>typedef struct _IMAGE_RESOURCE_DIRECTORY {<br>    ULONG   Characteristics;<br>    ULONG   TimeDateStamp;<br>    USHORT  MajorVersion;<br>    USHORT  MinorVersion;<br>    USHORT  NumberOfNamedEntries;<br>    USHORT  NumberOfIdEntries;<br>} IMAGE_RESOURCE_DIRECTORY, *PIMAGE_RESOURCE_DIRECTORY;</pre><p>U notice, it doesn’t has a pointer to any child node, because after the struct, there is an array of _IMAGE_RESOURCE_DIRECTORY_ENTRY immediately follow it, <br> <br>IMAGE_RESOURCE_DIRECTORY_ENTRY DirectoryEntries[]<br>So to illustrate more, the picture shows how Microsoft align them in the PE file on the disk :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*8eW-L1Yt_15oiFWfpIqIrw.png" /></figure><p>So, in the resource section address, and the entries occur after the size of t_directroy struct == sizeOf(_IMAGE_RESOURCE_DIRECTORY). <br>The _IMAGE_RESOURCE_DIRECTORY_ENTRY contains the name/type of the resource and a pointer to _IMAGE_RESOURCE_DIRECTORY.</p><pre>typedef struct _IMAGE_RESOURCE_DIRECTORY_ENTRY {<br>    ULONG   Name; // It can be used as integer or pointer to another struct. <br>/*<br>This field contains either an integer ID or a pointer to a structure that contains a string name. If the high bit is zero, this field is interpreted as an integer ID. If the high bit is nonzero, the lower 31 bits are an offset (relative to the start of the resources) to an IMAGE_RESOURCE_DIR_STRING_U structure. <br>*/<br>    ULONG   OffsetToData; // pointer to child node in the tree. <br>} IMAGE_RESOURCE_DIRECTORY_ENTRY, *PIMAGE_RESOURCE_DIRECTORY_ENTRY;</pre><p>What is the difference between _IMAGE_RESOURCE_DIRECTORY_ENTRY and _IMAGE_RESOURCE_DIRECTORY ? <br><strong>_IMAGE_RESOURCE_DIRECTORY</strong> : think of it as container that hold an array of _IMAGE_RESOURCE_DIRECTORY_ENTRY<br> _IMAGE_RESOURCE_DIRECTORY_ENTRY contains the metadata (e.g. language, id, sibling node) <br> To illustrate it more, let’s look at this _IMAGE_RESOURCE_DIRECTORY example :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*4uhQ4573_jrP0-yvQ5wP_A.png" /></figure><p>U can notice that it’s the root node because the ID equal to zero. Also it has Three _IMAGE_RESOURCE_DIRECTORY_Entry elements. Each one point to _IMAGE_RESOURCE_DIRECTORY child.</p><p>Also another, where Image_resource_directory points to raw data :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*qZMYIbLz6T-k4I1BsKRf0A.png" /></figure><p>U can see, that the child contains a pointer to raw heart image. <br> <br>To get the big picture, look at this example that contains resource section :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o27dwV7b1WGlP12ddXoG4g.png" /></figure><p>U can see that resource root node have 3 sub node == 3 resources. <br> <br>Let looks at the depths/levels of the tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJct9Pq0hVtnvRcUBXgFOg.png" /></figure><p><strong>Level 1</strong> is _IMAGE_RESOURCE_DIRECTORY struct that contains two entries. Each entry follows “_IMAGE_RESOURCE_DIRECTORY_Entry” struct, they define the type and pointer to another _IMAGE_RESOURCE_DIRECTORY entry.</p><p>The type of resource is defined in the winnt.h file :</p><pre>/*<br> * Predefined Resource Types<br> */<br>#define RT_CURSOR           MAKEINTRESOURCE(1)<br>#define RT_BITMAP           MAKEINTRESOURCE(2)<br>#define RT_ICON             MAKEINTRESOURCE(3)<br>#define RT_MENU             MAKEINTRESOURCE(4)<br>#define RT_DIALOG           MAKEINTRESOURCE(5)<br>#define RT_STRING           MAKEINTRESOURCE(6) // represent string in unicode or ascii hex format. <br>#define RT_FONTDIR          MAKEINTRESOURCE(7)<br>#define RT_FONT             MAKEINTRESOURCE(8)<br>#define RT_ACCELERATOR      MAKEINTRESOURCE(9)<br>#define RT_RCDATA           MAKEINTRESOURCE(10)<br>#define RT_MESSAGETABLE     MAKEINTRESOURCE(11)</pre><p><strong>Level 2</strong> is also is _IMAGE_RESOURCE_DIRECTORY struct represent an identifier for the resource, the identifier can be : <br>1. Pointer to IMAGE_RESOURCE_DIR_STRING_U struct : the left hand of the tree uses the “name” attribute as pointer to another object, which follows IMAGE_RESOURCE_DIR_STRING_U. <br>2. Integer only as identifier : The right hand of the tree uses “name” attribute as integer or id. <br> <br> <br><strong>Level 3</strong>: used to defines the language used for the resources, they use hex decimal to represent a resource language. Also the pSibling “OffsetToData attributes” used to point to the actual resource raw data. <br> <br>Leafs: Just an _IMAGE_RESOURCE_DATA_ENTRY struct. <br> <br><strong>Why the .rsrc section is so complex ? ???<br></strong>To gain flexibility and time optimization in-terms of gathering the meta data of a single resource without digging to the resource actual data. <br>For example, u can very fast gather all resources for a certain language.</p><p><strong>E) .edata Export section :<br></strong>It contains the exported functions/data for the application or the dll. It starts with a directory structure that has information about the struct itself. The struct defined in the WINNT.h file :</p><pre>typedef struct _IMAGE_EXPORT_DIRECTORY {<br>    ULONG   Characteristics; // unused<br>    ULONG   TimeDateStamp; // the time the table was created<br>    USHORT  MajorVersion; // often 0<br>    USHORT  MinorVersion;// often 0<br>    ULONG   Name; // RVA address to the name of the executable module<br>    ULONG   Base;<br>    ULONG   NumberOfFunctions; // Total number of functions exported. Maybe called by name or ordinal.<br>    ULONG   NumberOfNames; // / Total number of functions exported and named. <br>    PULONG  *AddressOfFunctions;  // RVA to a list of exported function entry points<br>    PULONG  *AddressOfNames; // An RVA to a null-separated list of export function names.  <br>// how many functions and function names are being exported from the module<br>    PUSHORT *AddressOfNameOrdinals; // RVA to  ordinal(integer) values to represent the exported functions in integer style. <br> <br>/*<br>The three AddressOf... fields are relative virtual addresses into the address space of a process once the module has been loaded<br>*/<br>} IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY;</pre><p>So, to give better idea to the exported function layout in the PE file, let assume that we have a DLL that has 10 exported functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*659qIk9M9Lk7O5nO1rwb9A.png" /></figure><p><strong>We can see that it has 10 exported functions. And it named 5 only of them. But why ??<br></strong>Because functions can be called either by name or ordinal(integer). <br> We can see the AddressOfNameOrdinals fields point to a list of numbers, each one correspond to the same index in the AddressOfNames list. Then after that it’s only mapped to the the AddressOfFunctions list. <br>Note: Remember that there is no indication which name links to which address in the AddressOfNames array. We showed the arrows just so we can better illustrate the example. <br><strong>But how we u know which name to which address ? <br></strong>using the ordinals value. We knew that each ordinal correspond index to the same index in the function names list. But the value of the ordinal correspond to which address the function name belong to. <br>For example, we can see the that ordinal “8” value correspond to addr8 in the address of function list.</p><p><strong>F) .idata Import section == import table<br></strong>NOTE: import table is different from import address table, import table is the container of import address table and other structures. <br>Most of the Microsoft code written as DLLs, which are nothing but just libraries with public functions to be used by anyone.<br> While in order to call a certain function from a certain dll, I need to know the address of the function, the issue is the developer of the dll might change the name of the function or update the dll code. <br>So relaying in static global addresses for each function in each dll written in the world is bad idea because every thing change. <br>IDT (Import Directory Table) table contains IMAGE_IMPORT_DESCRIPTOR entries. <br>So Microsoft invent something called “_IMAGE_IMPORT_DESCRIPTOR”, which is a structure that define what imported functions I use for a certain DLL, so windows loader look to it and then it does the necessary steps to load the dll to memory or just grab the address from the memory.<br> <br>But let’s see the big picture of _IMAGE_IMPORT_DESCRIPTOR structure :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JHHcsPcJTw1ACYljqgiM3g.png" /></figure><p><strong>Hint names table == Import names table == Import lookup table<br></strong>The OriginalFirstThunk points to the Import Name Table (also called Hint names table HNT )and the FirstThunk points to the Import Address Table.<br>So the idata section starts with array of _IMAGE_IMPORT_DESCRIPTOR struct, <br>each struct describe the imported functions for a certain dll. <br>There is no length attribute to count the array elements. Instead Microsoft append to the end an empty null _IMAGE_IMPORT_DESCRIPTOR structure .</p><p>To be more precise, the struct:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDQiFPGVdl58RFMZXlFg7w.png" /></figure><p>Each entry of the IAT and INT follow this struct:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQSbh5oaq4jz2kEhemI4gg.png" /></figure><p>These two tables (HNT and IAT) are exactly the same. <br><strong>But why we need two tables ??<br></strong>Because HNT is fixed table and never modified, while IAT will be overwritten by the PE loader when your PE file loaded into memory. <br>So when u have an instruction like this : <br>JMP DWORD PTR [XXXXXXXX]<br>let assume that it calls function in another dll, The [XXXXXXXX] portion is point to a function in the Import address table because it’s the one who have the real pointer the function address. <br>So HNT is quite useless or stub. <br>So before the PE loader override the IAT, the structure look like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZlMKWUmTL8yGLDAgYFBjQA.png" /></figure><p>INT and IAT point to the same IMAGE_IMPORT_BY_NAME struct which contains only two attributes , hint ( ordinal value) and name of the function. <br>But after the PE loader overwrite IAT, they become different in terms of values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dNEIAlXe3D97bN8AgOQtQ.png" /></figure><p><strong>Note</strong>: IAT and INT preserve same order or the array, e.g. look at loadLibrayA , in both tables, they are in index 2. So lets see the bigger picture from developer perspective :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zfAdX_Ld-aoipeKxbhjysg.png" /></figure><p>Note: ILT = = Import lookup table == just another name for INT == Import Name Array. <br>Note: For each imported DLL, it has its own IMAGE_IMPORT_DESCRIPTOR. Each function from a certain DLL has entry in IAT and ILT.</p><h3><strong>Conclusions :</strong></h3><p>Well, going through PE file structure is never an easy tasks 😂 . Hopefully, this will serve you a good reference when get lost at the details of PE file. If you have any comments , additions or suggestions to improve it, let me know and I will add you as collaborator to modify thearticlee.</p><h3><strong>References:</strong></h3><ol><li><a href="https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#:~:text=This%20specification%20describes%20the%20structure,(COFF)%20files%2C%20respectively.">https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#:~:text=This%20specification%20describes%20the%20structure,(COFF)%20files%2C%20respectively.</a></li><li><a href="https://docs.microsoft.com/en-us/archive/msdn-magazine/2002/february/inside-windows-win32-portable-executable-file-format-in-detail">https://docs.microsoft.com/en-us/archive/msdn-magazine/2002/february/inside-windows-win32-portable-executable-file-format-in-detail</a></li><li><a href="https://resources.infosecinstitute.com/topic/2-malware-researchers-handbook-demystifying-pe-file/">https://resources.infosecinstitute.com/topic/2-malware-researchers-handbook-demystifying-pe-file/</a></li><li><a href="https://blog.kowalczyk.info/articles/pefileformat.html">https://blog.kowalczyk.info/articles/pefileformat.html</a></li><li><a href="https://www.cnblogs.com/night-ride-depart/p/5776107.html">https://www.cnblogs.com/night-ride-depart/p/5776107.html</a></li><li><a href="https://malwology.com/2018/10/05/exploring-the-pe-file-format-via-imports/">https://malwology.com/2018/10/05/exploring-the-pe-file-format-via-imports/</a></li><li><a href="https://docs.microsoft.com/en-us/previous-versions/ms809762(v=msdn.10)#pe-file-imports">https://docs.microsoft.com/en-us/previous-versions/ms809762(v=msdn.10)#pe-file-imports</a></li><li><a href="https://ired.team/miscellaneous-reversing-forensics/pe-file-header-parser-in-c++#code">https://ired.team/miscellaneous-reversing-forensics/pe-file-header-parser-in-c++#code</a></li><li><a href="https://lief.quarkslab.com/doc/stable/tutorials/07_pe_resource.html">https://lief.quarkslab.com/doc/stable/tutorials/07_pe_resource.html</a></li><li><a href="http://bytepointer.com/resources/pietrek_peering_inside_pe.htm">http://bytepointer.com/resources/pietrek_peering_inside_pe.htm</a></li><li><a href="http://read.pudn.com/downloads756/ebook/3008316/Bin_Portable_Executable_File_Format_%E2%80%93_A_Reverse_Engineer_View_2012-1-31_16.43_CBM_1_2_2006_Goppit_PE_Format_Reverse_Engineer_View.pdf">http://read.pudn.com/downloads756/ebook/3008316/Bin_Portable_Executable_File_Format_%E2%80%93_A_Reverse_Engineer_View_2012-1-31_16.43_CBM_1_2_2006_Goppit_PE_Format_Reverse_Engineer_View.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aa3b59ab13c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dissecting  COM objects]]></title>
            <link>https://medium.com/@jasemalsadi/dissecting-com-objects-9b1ea3f18964?source=rss-e4a893265a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b1ea3f18964</guid>
            <category><![CDATA[com-servers]]></category>
            <category><![CDATA[com]]></category>
            <category><![CDATA[dissecting-com-objects]]></category>
            <category><![CDATA[com-clients]]></category>
            <category><![CDATA[com-objects]]></category>
            <dc:creator><![CDATA[Jasem Al-Sadi]]></dc:creator>
            <pubDate>Fri, 20 Mar 2020 02:12:11 GMT</pubDate>
            <atom:updated>2020-03-20T02:12:11.633Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dissecting COM objects</h3><p>One of the things I always had confusion about it in windows is COM objects because if you go to Microsoft documentation, you will this unbelievable Introduction :</p><p>“</p><p>The Microsoft Component Object Model (COM) is a platform-independent, distributed, object-oriented system for creating binary software components that can interact. COM is the foundation technology for Microsoft’s OLE (compound documents), ActiveX (Internet-enabled components), as well as others.</p><p>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*8WDMh7uu-BzyWyLDWsEOgQ.gif" /></figure><p>So I decided to eliminate all confusions and put an effort to understand what, why and how this technology works in windows, and here is my journey.</p><h3>What is COM Objects ?</h3><p>COM is just a standard to define how objects are configured/constructed/deconstructed. It’s independent (like JSON) from any language and also not tight coupled to windows stuff. For example, java uses COM objects.</p><p>So if I want to create a calculator library and I want to be used by exe file, java application , web page or any other kind of clients, I can create a DLL library which implements functionality of the calculator, then I make the DLL implement COM interfaces ( <strong>IUnknown </strong>or <strong>IDispatch </strong>interfaces<strong>),</strong> so the dll functions and attributes became a COM object that can be used by anyone.</p><p>COM works as a client server architecture :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tFN1tgQZwzkDFsYSJVEnuA.png" /><figcaption>A COM client requesting an object form a COM server.</figcaption></figure><p>So, our calculator DLL will be the “Server” and anyone “” can request a service from that server. COM objects are the data that will be transferred during the communication.</p><p>There are three types of communication between client and server that can be happen :</p><ol><li><strong>In-Process COM Components:</strong> A process will request our calculator COM object, so OS will decide to the load the DLL to a memory and share the memory region of the DLL between processes.</li><li><strong>Out-of-Process COM Components:</strong> Same as <strong>In-process</strong>, but the OS will create a separate process that will load the DLL.</li><li><strong>Remote COM Components</strong>: Same as <strong>Out-of-Process </strong>but over a network.</li></ol><h3>Example of Using pre-built COM objects in Powershell :</h3><p>Below is an example using shell.Application COM object in PS, where we show all available methods and properties and we use shellExecute Method to run calc.exe from PS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1WfGyfULcmt7fAIXfWcDDA.png" /></figure><p>So, we request a COM object of Shell.Application , the OS will find in registry which DLL correspond to Shell.Application COM object namespace. Then, it will load it to memory and execute the constructor function of it, then OS will return the object to us in PS.</p><p>So, let’s go a little deeper to understand how Shell.Application COM works internally :</p><p>Each COM object has a unique name that represented like this : “namespace.className”</p><p>While, it’s not necessary to be with “namespace.className” syntax, it just need to be a string. As it’s only convention.</p><p>So we see that we use shell.Application COM object name. This unique name called Programmatic Identifier (ProgID). All available ProgIDs are stored in the registry, we can get a list of ProgIds in the PC using PS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Erqb08QdGbAipHyyvROUqw.png" /></figure><p>The Powershell command is returning first 10 progid from the HKEY_CLASSES_ROO\clsid subkey.</p><p>So, we can modify the PS command to search for Shell.Application value from VersionIndependentProgID subkey :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSrQQJOa_KurZf_7ePyiNA.png" /><figcaption>shell.Application COM object</figcaption></figure><p>VersionIndependentProgID will point to the progID as MS docs says:</p><p><a href="https://docs.microsoft.com/en-us/windows/win32/com/versionindependentprogid">VersionIndependentProgID - Win32 apps</a></p><p>We see we got two registry keys with shell.Application progID, this is logical because one compiled for 64-bit and the other for 32-bit.</p><p>We can see above we got the full path of the registry : HKEY_CLASSES_ROOT\CLSID\{13709620-C279–11CE-A49E-444553540000} .</p><p>So first let’s understand, what this “CLSID\{13709620-C279–11CE-A49E-444553540000} “ means ?</p><p>CLSID : stands for class identifier, it’s Global unique identifier ( GUID) 32 bit Hexadecimal that windows use to differentiate between each class. COM object use it because a Class/COM class can have multiple version of it with the same name.</p><p>Think of it as DNS, where the class name or progID is the domain name and the CLSID GUID is the IP of the domain name.</p><p>let’s fetch all subkeys of it :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*khKRfKU0c3760bHI1oaw6g.png" /></figure><p>Let’s describe each value in the CLSID GUID of shell.Application:</p><p>The <strong>ProgID</strong>/versionIndepndentProgID is a friendly name which relates to a Class ID. Already we talked about it before.</p><p><strong>InProcServer32</strong>: It means In-Process Server communication COM type, it has a value of the DLL path that implement the functionality.</p><p><strong>TypeLib</strong>: It’s used to describe the type of content of the class, here we refer to it to another guid that has more information about shell32.dll type ( C++ or C# or .. Etc). So, let’s discover it’s content from the HKCLR\TypeLib\{guid} registry path :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27HVt34_Ccs88Q301WMCMg.png" /></figure><p>We see it gave us 3 subkeys describing each version of the DLL and the path for the 32-bit DLL.</p><p><strong>But, How all of these information registered to the registry ?</strong></p><p>This done at compilation time, but you have to do it manually when move the DLL to another PC, it’s done using REGSVR32.exe file.</p><p>I thought that I have eliminated all my confusions, but my Curiosity ask me for more…</p><p><strong>So, How we do create our Own COM objects ??</strong></p><p>I saw some articles about implementing it in C++ but it was amazingly complex code, so I thought it’s better to write it in C#, because the code become much more cleaner and make us more to focus in understanding COM objects. But Since C# is managed code, we can instruct the CLR to wrap our C# code with C++ code, so it appears as normal DLL.</p><p>This is done using a feature called C++ interop aka. It Just Works (IJW).</p><p>So if you want to create COM Server using C#, you need to tick the interop feature, so CLR knows that it will compile the code as COM server and register it in the registry. So, we will create a simple calculator COM server that has three function : add, multiply and divide. here are the steps to create a COM server :</p><ol><li><strong>Create a C# project with interface that will be exposed to the server</strong></li></ol><p>Start by creating a C# project with .Net framework library type, then create an interface that will be used as the COM server and class to implement the interface methods.</p><p>The interface :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*ijxA_fEicf1gv-mOKfsMfg.png" /><figcaption>Basic Calculator interface.</figcaption></figure><p>The class that implement the interface :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YQrwchtOA5y_OHpEdzlEVA.png" /><figcaption>COM implementation.</figcaption></figure><p>Note: I forgot to add public keywork to the constructor definition please add it.</p><p>2. <strong>Adding annotations to the interface and the class to make it COM Server</strong></p><p>We will add some annotations that is needed in-order to make windows knows it’s a COM .</p><p>The Interface :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNf3zmXDP2Zd4_KeSFaEYA.png" /></figure><p>The class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ohCM-hAMqnDLZngRfsNsg.png" /></figure><p>3. <strong>Register our DLL to Registry</strong></p><p>We need to get a GUID for the class and the interface, so windows can register them to registry, we can GUIDs from VS studio tool-&gt;Create GUID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9uDvm3r2vWvIsT71fmu-g.png" /><figcaption>GUID</figcaption></figure><p>U need to create GUID like above for the class and the interface.</p><p>After that, we need to create a .snk file ( strong name ) . A strong name gives this assembly a unique signature and allow multiple versions of the code to run side-by-side. To create it we execute the snk command on the class directory using developer command line ( not normal command line):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSG6fFMgOzsW0kaDwr45mA.png" /><figcaption>snk file created for signature.</figcaption></figure><p>-k means to create a key pair.</p><p>Then we add the newly created file in the project setting: ( Project tab -&gt; “project_name” Properties) , then we go to the singing tab to attach the file :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEcc5d40_gnx9ZoMWWRlVg.png" /></figure><p><strong>Note</strong>: You have to run VS in administrator in order to attach the sign file and for the next steps.</p><p>4. <strong>Tell the compiler that it’s COM Server</strong></p><p>We need to tell the compiler that it’s a COM object , but before compilation, we need to choose a platform to compile your COM object on it, I will choose x64 and a release version ( not debug version ):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*ajL_4O2onNhp7KI0C86b9w.png" /></figure><p>Then, we can tell MS compiler that it’s a COM server, so it will register it to the registry:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4fnuu3IIgtkXpLMhE8smKA.png" /></figure><p>Tick the “Register for COM intereop”.</p><p>Then build the solution, using build tab -&gt; build Solution, if you a successful build, you see a successful compilation console message.</p><p>5. <strong>Test the new COM Server in PS</strong></p><p>Then you just create a COM object in PS using the progId defined in the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*naNB4LPHaeQarOR6apNiYg.png" /><figcaption>Calling our COM Server from PS</figcaption></figure><p>Note: You don’t need to create a new PS process if you add a COM object, because PS don’t cache the registry, it fetch it live.</p><p>Let’s see if we can find the DLL in the registry :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-jf3V3qVokbucPMhRDmwQ.png" /><figcaption>DLL path of our COM server</figcaption></figure><p>I have uploaded the repo to github, so you can start directly creating your own COM objects:</p><p><a href="https://github.com/Jasemalsadi/comObjectCsharp">Jasemalsadi/comObjectCsharp</a></p><p><strong>Resources:</strong></p><p><a href="http://symantec.com/connect/articles/basic-understanding-com-and-related-registry">symantec.com/connect/articles/basic-understanding-com-and-related-registry</a></p><p><a href="http://support.ptc.com/help/creo/creo_pma/usascii/index.html#page/detail/About_OLE_Objects.html">http://support.ptc.com/help/creo/creo_pma/usascii/index.html#page/detail/About_OLE_Objects.html</a></p><p><a href="https://www.codeproject.com/Articles/7859/Building-COM-Objects-in-C">https://www.codeproject.com/Articles/7859/Building-COM-Objects-in-C</a></p><p><a href="https://whoisburiedhere.wordpress.com/2011/07/12/creating-a-com-object-from-scratch-with-c/">https://whoisburiedhere.wordpress.com/2011/07/12/creating-a-com-object-from-scratch-with-c/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b1ea3f18964" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>