<?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 Shaked Wiessman on Medium]]></title>
        <description><![CDATA[Stories by Shaked Wiessman on Medium]]></description>
        <link>https://medium.com/@shakedwe2?source=rss-8eb24ca38cda------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kzyUPX4ND0rZD9NI</url>
            <title>Stories by Shaked Wiessman on Medium</title>
            <link>https://medium.com/@shakedwe2?source=rss-8eb24ca38cda------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:13:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shakedwe2/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[From Sector Zero to Herohttps://miro.medium.com/v2/resize:fit:484/1*o82QISpXRB9tX90JrDVw0A.png]]></title>
            <link>https://medium.com/@shakedwe2/from-sector-zero-to-herohttps-miro-medium-com-v2-resize-fit-484-1-o82qispxrb9tx90jrdvw0a-png-e23965b4825c?source=rss-8eb24ca38cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/e23965b4825c</guid>
            <category><![CDATA[forensics]]></category>
            <category><![CDATA[red-team]]></category>
            <dc:creator><![CDATA[Shaked Wiessman]]></dc:creator>
            <pubDate>Sat, 25 Apr 2026 08:54:05 GMT</pubDate>
            <atom:updated>2026-04-25T16:39:37.702Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Sector Zero to Hero</h3><h3>Below the API: Extracting Files from Raw Disk Without Windows Knowing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*o82QISpXRB9tX90JrDVw0A.png" /></figure><p><strong>Link for Repo -&gt; </strong><a href="https://github.com/ShkudW/NTFS-forensics"><strong>https://github.com/ShkudW/NTFS-forensics</strong></a></p><p>Every time we open a file on Windows, we trust the operating system to do the right thing!</p><p>we call <strong>CreateFile </strong>WinAPI, windows finds the file, and returns a handle.</p><p>But what actually happens underneath?? and more important what happens when we decide to skip Windows entirely?</p><p>In this article we’ll go from the very first byte on a physical disk all the way to reading the raw content of any file including files that Windows will refuse to open for you, like SAM and SYSTEM. No Win32 API. No NT Native API. Just a handle to <strong>“\\.\PhysicalDrive0</strong>” and the knowledge of how NTFS actually works.<br>To get there, we need to understand the full stack: how a disk is physically organized, how partition tables work, how NTFS structures its data and why all of this exists below the layer that most developers ever see.</p><p>Every Red Teamer has been there. You’ve escalated to SYSTEM, you’re on a server, and you want the SAM file.</p><p>so you’re trying:</p><pre>reg save HKLM\SAM C:\Temp\sam.hive</pre><p>yes, it might work on vanilla machine, but on hardened EDR-monitored environment.. Flagged in seconds!</p><p>maybe that?</p><pre>vssadmin list shadows<br>copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM C:\Temp\</pre><p>Sometimes there are no shadow copies, Sometimes VSS is disabled by policy, Sometimes the EDR catches the <strong>vssadmin </strong>call before you even get the output.</p><p>ok! so that will work!!!</p><pre>regedit /e C:\Temp\sam.reg HKEY_LOCAL_MACHINE\SAM</pre><p>Blocked. The SAM key is protected even from registry exports while the system is running.</p><p>also this:</p><pre>esentutl /y C:\Windows\System32\config\SAM /d C:\Temp\sam.bak /o</pre><p>Even if we will try to get an handle to SAM file:</p><pre><br>#include &lt;iostream&gt;<br>#include &lt;windows.h&gt;<br><br>int main()<br>{<br>    HANDLE SAMI = CreateFileA(<br>        &quot;\\\\?\\C:\\Windows\\System32\\config\\SAM&quot;,GENERIC_READ,0,NULL,OPEN_EXISTING,0,NULL);<br><br>    if (SAMI == INVALID_HANDLE_VALUE) {<br>        printf(&quot;Error: %lu\n&quot;, GetLastError());<br>        <br>    }<br>}</pre><p>Error 32. ERROR_SHARING_VIOLATION. Even as SYSTEM.<br>This isn’t a permissions problem it’s a locking problem.</p><p>The Windows kernel holds an exclusive lock on SAM, SYSTEM, and SECURITY for as long as the OS is running. No sharing mode combination gets around it. <strong>SeBackupPrivilege </strong>with <strong>FILE_FLAG_BACKUP_SEMANTICS</strong> is one workaround, but it still goes through the API, which means it still goes through the security layer, which means it gets logged, flagged, and blocked on hardened systems.</p><p>But here’s the thing: that lock only exists at the file system level. Windows locks file handles. It has no concept of locking sectors on a disk.</p><p>so what if we will do something like that:</p><pre>    HANDLE hDisk = CreateFileW(L&quot;\\\\.\\PhysicalDrive0&quot;, GENERIC_READ,FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,OPEN_EXISTING, 0, NULL);<br><br>    if (hDisk == INVALID_HANDLE_VALUE) {<br>        return 1;<br>    }</pre><p>This handle doesn’t talk to ntfs.sys!<strong> It talks directly to the disk driver.</strong></p><p>There are no file objects, no access checks against the file system, no opportunity for the OS to say “that file is locked.” From this point forward, you’re reading raw bytes off a spinning platter (or flash chip), and Windows is completely out of the loop.<br><strong>The question is</strong>: how do we find any file in those raw bytes?<br>That’s what this article is about.</p><h3>The Disk Doesn’t Know What a File Is</h3><p>A hard drive doesn’t speak in concepts we’re familiar with, no files, no permissions, no attributes, no names, no folders.</p><p>At the hardware level, a disk is nothing more than a flat, numbered array of fixed-size blocks called sectors, each one exactly 512 bytes.</p><p>Sector 0, sector 1, sector 2…… all the way to the end of the disk.</p><p>Now, to make use of that space, the disk needs a way to describe how it’s divided into partitions. That description lives in a partition table, this is a small data structure written at the very beginning of the disk that tells the OS: here’s where each partition starts, here’s where it ends, here’s what type it is.</p><p><strong>There are two common partition table formats:</strong></p><p><strong>MBR (Master Boot Record) - </strong>the older format, found on legacy systems and anything using a traditional BIOS. It lives in sector 0 and has significant limitations: maximum disk size of 2TB, maximum of 4 primary partitions.</p><p><strong>GPT (GUID Partition Table</strong>) - the modern format, used on any system running UEFI firmware. It lives in sector 1, supports disks well beyond 2TB, and allows up to 128 partitions. Every modern Windows installation uses GPT.</p><p>In fact, the <strong>C:</strong> drive we’re familiar with is nothing more than one of those partitions sitting on the physical disk.<br>When we open File Explorer and see “Local Disk (C:)”, we’re not looking at the whole disk you’re looking at one slice of it.</p><p>The physical disk may also contain a <strong>hidden UEFI</strong> System Partition, a <strong>recovery partition</strong>, and potentially others. Windows just picks the right partition, mounts it, and gives it a drive letter.</p><p>Now that we understand the disk is divided into partition, each partition can speak a different “language.” That language is called a file system, and it’s what turns a flat array of sectors into something meaningful: folders, files, permissions, timestamps.</p><p><strong>There are several common file systems we’ll encounter:</strong></p><ul><li><strong>NTFS (New Technology File System)</strong> - the standard for Windows system drives (your C: drive). It supports complex security permissions, file ownership, encryption, journaling, and the attribute-based structure we’ll be diving into throughout this article. If you’re attacking a Windows machine, you’re almost certainly dealing with NTFS.</li><li><strong>FAT32</strong> - an old and simple file system with no concept of permissions whatsoever. Anyone can read anything, no restrictions. You’ll find it on USB drives and - importantly -on the EFI System Partition, the small hidden partition that holds the bootloader.</li><li><strong>exFAT</strong>- the successor to FAT32, designed for external drives and memory cards. No permissions either, but it handles large files and large drives better than FAT32. It’s the go-to format when you need seamless compatibility between Windows and macOS.</li><li><strong>ReFS (Resilient File System) -</strong> Microsoft’s modern answer to large-scale storage. Built to detect and recover from data corruption automatically. You’ll find it on enterprise file servers, Storage Spaces, and Azure infrastructure. Not something you’ll encounter on a typical workstation.</li></ul><p>For this article, we’re focused entirely on NTFS - because that’s where the interesting structures live, and that’s where SAM is hiding.</p><h3>Welcome To Sector 0:</h3><p>You can find all the code files I wrote for the investigation on my GitHub page -&gt; https://github.com/Shkudw/NTFS-forensics</p><p>In this part, we will understand in a practical way how to communicate with the hard disk, how to read data and how to find our file.</p><p>For this part I’ll create a text file on my Desktop - “Shak123.txt” with the text “Hey From File!” inside it and save it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*3T0-ECdOavNEmFUZh5Nseg.png" /></figure><p>That’s our target, a real file, sitting somewhere on your physical disk right now, with content you can verify.</p><p>As I mentioned, we’ll open a handle directly to the physical disk - this requires Administrator privileges -and read the very first sector: Sector 0.<br>Let’s see what’s actually there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*OgOXRD8XxUWecOlgIWsDIg.png" /></figure><p>Three things worth noting here:</p><ol><li>The last two bytes: 0x55 0xAA<br>This is the boot signature - a magic number that tells the BIOS “this is a valid, bootable disk.” Every bootable disk ends sector 0 with exactly these two bytes.</li><li>The first 400 bytes are all zeros<br>On a traditional MBR disk, the first part of sector 0 contains x86 assembly code a small bootloader that the BIOS executes before the OS even starts loading. You’d see it clearly on older systems like Windows 7. Here, it’s all zeros. No boot code. That’s our first hint that this is a GPT disk - UEFI handles the boot process differently and doesn’t need that stub.</li><li>Offset 0x1C2 = 0xEE<br>This byte sits inside the partition table entry embedded in sector 0. It’s the partition type field. The value 0xEE is specifically reserved for one thing: GPT Protective Partition. Its entire purpose is to tell old MBR-aware tools “this disk uses GPT don’t touch it.” This is our explicit confirmation: we’re dealing with a GPT disk.<br>Sector 0 gave us orientation.</li></ol><h3>Welcome To Sector 1:</h3><p>Now we will use the “<strong>Sector_HEX_Dumper”</strong> tool again, but this time on Sector 1.</p><p>The first 8 bytes spell out EFI PART in ASCII that’s the GPT signature, confirming this disk uses a GPT partition table. The rest of the sector contains a data structure called GPT_HEADER. Most of the sector is empty the header itself is only 92 bytes. The field that interests us is <strong>PartitionEntriesLBA</strong>, located at offset 0x0048. Its value is 2 meaning the partition entries are stored in Sector 2. That’s where we’ll find the start of our Windows partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*LpqS3BlCLS8btwzSIuqkvw.png" /></figure><h3>Welcome To Sector 2:</h3><p>To make sense of the raw bytes in Sector 2, we map them onto a data structure called:</p><pre>struct GPT_PARTITION_ENTR{<br>    BYTE     PartitionTypeGUID[16];<br>    BYTE     UniquePartitionGUID[16];<br>    UINT64   StartingLBA;<br>    UINT64   EndingLBA;<br>    UINT64   Attributes;<br>    WCHAR    PartitionName[36];<br>} Y;</pre><p>Each GPT_PARTITION_ENTRY is 128 bytes. Sector 2 is 512 bytes. That means exactly 4 partition entries per sector and indeed, parsing gives us four:</p><ul><li><strong>EFI System Partition:</strong> exists in 2048 sector.</li><li><strong>Microsoft Reserved Partition:</strong> exists in 206,848 sector.</li><li><strong>Basic Data Partition:</strong> exists in 239,616 sector = !! <strong>our NTFS partition </strong>!!</li><li><strong>Windows Recovery (WinRE):</strong> exists in 1,998,637,056 sector.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*pLy1--CiPbmoNHhzXuTSGA.png" /></figure><h3>Welcome To Sector of NTFS:</h3><p>We’ve now reached sector 239,616 — the first sector of our NTFS partition. Using the NTFS_BOOT_SECTOR structure, we can extract the information we need from this sector and locate the Master File Table (MFT).</p><pre>struct NTFS_BOOT_SECTOR{<br>    BYTE  JumpInstruction[3];<br>    BYTE  OemID[8];<br>    WORD  BytesPerSector;<br>    BYTE  SectorsPerCluster;<br>    WORD  ReservedSectors;<br>    BYTE  Fats;<br>    WORD  RootEntries;<br>    WORD  SmallSectors;<br>    BYTE  MediaDescriptor;<br>    WORD  SectorsPerFat;<br>    WORD  SectorsPerTrack;<br>    WORD  HeadsPerCylinder;<br>    DWORD HiddenSectors;<br>    DWORD LargeSectors;<br>    BYTE  PhysicalDiskNumber;<br>    BYTE  CurrentHead;<br>    BYTE  ExtendedBootSignature;<br>    BYTE  Reserved1;<br>    ULONGLONG TotalSectors;<br>    ULONGLONG MftLcn;<br>    ULONGLONG MftMirrLcn;<br>    CHAR  ClustersPerMftRecord;<br>    BYTE  Reserved2[3];<br>    CHAR  ClustersPerIndexBuffer;<br>    BYTE  Reserved3[3];<br>    ULONGLONG VolumeSerialNumber;<br>    DWORD Checksum;<br>    BYTE  BootCode[426];<br>    WORD  BootSignature;<br>} ;</pre><p>The MFT is NTFS’s index of everything on the volume. Every file, every folder, every system structure each one gets a dedicated record inside it. Think of it as a giant database: if a file exists on this NTFS partition, it has a row in the MFT. If it doesn’t have a row the operating system doesn’t know it exists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*h67LGevm6vaMsTfu21Jw7g.png" /></figure><p>But before we can navigate to the MFT, we need to understand how NTFS measures distance on disk. NTFS doesn’t think in sectors it thinks in clusters. A cluster is a group of consecutive sectors that NTFS treats as a single unit. On our volume, <strong>SectorsPerCluster</strong> = 8, meaning one cluster equals 8 × 512 = 4,096 bytes.<br>Every location in NTFS is expressed as a cluster number called an LCN (Logical Cluster Number). So when NTFS_BOOT_SECTOR tells us where the MFT begins, it gives us an LCN, not a sector number.<br>To convert to an absolute sector one we can actually seek to on the physical disk we apply this formula:</p><pre>786432 X 8 = 6,291,456<br>6,291,456 + 239,616 = 6,531,072</pre><p>Sector 6,531,072, That’s where every file on this disk is catalogued.</p><h3>Welcome To Sector of MFT:</h3><p>To present the information that this Sector brings us in a better way, we use the MFT_RECORD_HEADER data structure:</p><pre>struct MFT_RECORD_HEADER {<br>    BYTE        Signature[4];<br>    WORD        UpdateSeqOffset;<br>    WORD        UpdateSeqCount;<br>    ULONGLONG   LogFileSeqNum;<br>    WORD        SequenceNumber;<br>    WORD        HardLinkCount;<br>    WORD        FirstAttrOffset;<br>    WORD        Flags;<br>    DWORD       UsedSize;<br>    DWORD       AllocatedSize;<br>    ULONGLONG   BaseFileRecord;<br>    WORD        NextAttrId;<br>    WORD        Padding;<br>    DWORD       MftRecordNumber;<br>};</pre><p>And we’ll see this information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*YakHWU6RRAz66TcUC5Z31Q.png" /></figure><p>Every file, folder, and system object in NTFS is represented as a record with this exact structure. So the question is: can we just loop through all records from sector 6,531,072 forward until we find shaked123.txt?</p><p>In theory yes. In practice no.</p><p>The MFT itself isn’t guaranteed to be one contiguous block on disk. It can be fragmented, just like any other file. The first few thousand records might start at sector 6,531,072, but then the MFT might continue from a completely different location on the disk. A naive linear scan would miss everything past the first fragment.</p><p>To find all MFT records, we need to know exactly where all the fragments are. And that information is stored inside MFT record #0 — the $MFT file, the record that describes the MFT itself.<br>Starting at FirstAttrOffset = 0x0038, we walk through its attributes until we reach the $DATA attribute (type 0x80). Inside it are the Data Runs a compact list of every disk location where MFT data lives.<br>That’s our next step.</p><h3>Welcome to Four attributes of MFT$ record:</h3><p>Now we will work with another data structure that will help us interpret the field <strong>FirstAttrOffset, </strong>The data structure is: ATTR_HEADER:</p><pre>struct ATTR_HEADER {<br>    DWORD  Type;<br>    DWORD  Length;<br>    BYTE   NonResident;<br>    BYTE   NameLength;<br>    WORD   NameOffset;<br>    WORD   Flags;<br>    WORD   AttrId;<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ZvPRNlOdzG-RIAXe8WjFw.png" /></figure><p>Three things to notice:</p><ol><li>$STANDARD_INFORMATION and $FILE_NAME are both Resident - their values are stored directly inside this MFT record. They hold metadata: timestamps, file attributes, the name $MFT. Not what we need right now.</li><li>$DATA - this is what we came for. It’s Non-Resident, which means the actual content of the MFT all those millions of file records is too large to fit inside a single 1024-byte MFT entry. It lives elsewhere on disk. The $DATA attribute doesn’t hold the data itself; it holds a map telling us where to find it. That map is called Data Runs.</li><li>$BITMAP - also Non-Resident. This tracks which MFT records are in use and which are free. We’ll ignore it for now.<br>Our target is Step 3. Inside that $DATA attribute, at offset 0x0100, the Data Runs are waiting.</li></ol><p>Resident vs Non-Resident, What Does It Mean? Every attribute in an MFT record has one job: store a value.</p><p><strong>Resident</strong> means the value is stored inside the MFT record itself - right there in the same 1024 bytes</p><p><strong>Non-Resident</strong> means the value is too large to fit inside the 1024-byte record. Instead of storing the data directly, the attribute stores a compact list of disk locations called Data Runs that point to where the actual data lives on disk.</p><h3>Welcome to SHOW_DARA_RUN:</h3><p>Now that we know the $DATA attribute of $MFT is Non-Resident, we need to extract the Data Runs from it. For that we use a second structure that sits immediately after the ATTR_HEADER:</p><pre>struct ATTR_NONRESIDENT_EXT {<br>    ULONGLONG StartVCN;<br>    ULONGLONG EndVCN;<br>    WORD      DataRunsOffset;<br>    WORD      CompressionUnit;<br>    DWORD     Padding;<br>    ULONGLONG AllocatedSize;<br>    ULONGLONG DataSize;<br>    ULONGLONG InitializedSize;<br>};</pre><p>The field we care about is <strong>DataRunsOffset -</strong> it tells us where inside the attribute the Data Runs begin. We take that offset, add it to the attribute’s start position, and we’re pointing at the raw bytes that encode the MFT’s location on disk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*9RcEuVhrf13s3_3gXuKk4Q.png" /></figure><p>So how can we read the HEX?</p><p>We’ll start from the left side, where the 0x33 is</p><pre>0x33<br> ││<br> │└─ low nibble  = 3 → the next 3 bytes are the LENGTH  (how many clusters)<br> └── high nibble = 3 → the 3 bytes after that are the OFFSET (starting cluster)</pre><p>In little Endian:</p><pre>Length (3 bytes): 20 C8 00  →  little-endian: 0x00C820  =  51,232 clusters<br>Offset (3 bytes): 00 00 0C  →  little-endian: 0x0C0000  =  786,432 cluster</pre><p>Then we will move on to the next HEX byte 0x43</p><pre>0x43<br>  ││<br>  │└─ low nibble  = 3 → the next 3 bytes are the LENGTH  (how many clusters)<br>  └── high nibble = 4 → the 4 bytes after that are the OFFSET (starting cluster)</pre><p>In little Endian:</p><pre>Length (3 bytes): 0C C8 00     →  little-endian: 0x00C80c  =  51,212 clusters<br>Offset (4 bytes): 74 07 AA 00  →  little-endian: 0x00aa0774  =  11,143,028 cluster</pre><p>and so on until we reach 0x00.</p><p>Now to physically get to the Cluster we need to convert the cluster to a sector (as I mentioned before, 1 Cluster is equal to 8 Sectors)<br>so if we take for example the first part of the information<br>it is located in:</p><pre>0x00C820  =  51,232 clusters = 51,232 X 8 = 409,856 Sectors<br>0x0C0000  =  786,432 cluster = 786,432 X 8 = 6,291,456 + 239,616 = 6,531,072</pre><p>To get the exact number of the Sector ‘e took the Cluster where the information of the first part is located We multiplied it by 8 and got to Sector, Now because it is a relative number we must add the starting Sector of the NTFS partition to it.</p><p>Therefore if we go through our HEX dump we can see that the MFT record information is divided into the following parts:</p><pre>Part 1)     Start Sector = 6,531,072    End Sector = 6,940,927  Size = 409,856<br><br>Part 2)     Start Sector = 95,663,008    End Sector = 96,072,703  Size = 409,696<br><br>Part 3)     Start Sector = 216,304,800   End Sector = 216,714,495  Size = 409,696<br><br>Part 4)     Start Sector = 196,336,192   End Sector = 196,745,983  Size = 409,792<br><br>Part 5)     Start Sector = 489,150,888    End Sector = 489,560,575  Size = 409,688<br><br>Part 6)     Start Sector = 515,738,144    End Sector = 515,832,135  Size = 93,992</pre><p>Now we get a full snapshot of the <strong>Master File Table,</strong> where every file, document, object of the file system is found<br>the MFT divided into 6 parts in the physical memory of the disk<br>What do we see in each part?<br>The same MFT_RECORD_HEADER structure of size 1024 Byte<br>which represents each file in the file system<br>And now according to the name it is created to run in a loop, in each part and search for our file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*dfIc9StmYsShlxCCufRYFQ.png" /></figure><h3>Finding out File:</h3><p>Now that we’ve decoded all six runs of the MFT, we know exactly where every MFT record lives on disk. The MFT isn’t one contiguous block — it’s spread across six separate extents, totaling over 2.1 million sectors.<br>To find our file, we need to scan through those extents and look for an MFT record whose $FILE_NAME attribute matches shak123.txt. We’ll use a tool that takes a start sector, an end sector, and a filename — and walks every 1024-byte record in that range:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNg8CJPO1Xchs8VHt6Z6ig.png" /></figure><p>Now that we have the sector number where the document is located, we will check whether the data in the document is stored in a Resident configuration (within the Struct) or as non-Resident (in another physical location on the disk).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xT1audunCVJb4pOctNmw5g.png" /></figure><p>You can see that the information is stored in Resident format<br>With the help of another tool, we can read the information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M10Sx2pZ4noLb6ohNkVcvw.png" /></figure><p><strong>success!</strong></p><p>Now let’s see if our file contained large information, of a length that would force NTFS to store the information not in the record itself but somewhere else on the disk. And the file is called shak321.txt</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*PrGk_q-HuypB3LtnDo2uBg.png" /></figure><p>We found our file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*llvDsdNy7nJIBwRzYWRu2Q.png" /></figure><p>And now we will examine how the information is stored:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gKCijGAYMlxoe-vwgmfQg.png" /></figure><p>You can see that the information is stored in Non-Resident configuration.</p><p>We use our tool to read the HEX dump found in the DATA field, which directs us to the Cluster where the information is located:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*2YrZKG6y2IZ0qug91mBmog.png" /></figure><p>And now as we already know, let’s calculate the HEX:</p><pre>0x31<br>  ││<br>  │└─ low nibble  = 1 → the next 3 bytes are the LENGTH  (how many clusters)<br>  └── high nibble = 3 → the 4 bytes after that are the OFFSET (starting cluster)</pre><p>In little Endian:</p><pre>Length (1 bytes): 0B        →  little-endian: 0x0b  =  11  clusters<br>Offset (3 bytes): 29 F1 02  →  little-endian: 0x02f129  =  192,809  cluster</pre><p>That is, we will now multiply the Cluster by eight and add the NTFS Sector to it:</p><pre>192,809 X 8 = 1,542,472<br>1,542,472 + 239,616 = 1,782,088</pre><p>And we will use<strong> Sector_HEX_Dumper</strong> to dump the HEX value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*9JUoQt8EGZgdROkf3Jn92w.png" /></figure><h3><strong>Mitigation:</strong></h3><p>Throughout this article we demonstrated the technique on a regular user file - shak123.txt. But as we showed at the very beginning, the same approach works on sensitive system files like SAM and SYSTEM. The only difference is knowing where to look in the MFT.<br><strong>So how do you defend against this?</strong></p><ol><li><strong>BitLocker Full Disk Encryption - </strong>If the disk is encrypted with BitLocker, raw reads return ciphertext. An attacker reading the sectors where SAM lives will get nothing usable without the volume master key. This is the strongest mitigation for offline scenarios - stolen drives, forensic imaging by an adversary - but also applies to live attacks on locked volumes.</li><li><strong>Credential Guard - </strong>For domain environments, enabling <strong>Credential Guard</strong> moves credential material (NTLM hashes, Kerberos tickets) out of LSASS and into an isolated VSM (Virtual Secure Mode) enclave. Even if an attacker reads the SAM hive raw, the most valuable secrets are no longer there.</li><li><strong>Detect with Sysmon Event ID 9 (RawAccessRead) - </strong>Microsoft’s Sysinternals Sysmon logs raw disk reads as <strong>Event ID 9</strong>. Any process calling ReadFile on a physical drive or volume handle generates this event. On a healthy workstation, you should almost never see it - making it a high-fidelity detection signal.</li></ol><pre>&lt;RuleGroup name=&quot;RawDiskAccess&quot; groupRelation=&quot;or&quot;&gt;<br>    &lt;RawAccessRead onmatch=&quot;include&quot;&gt;<br>        &lt;ProcessName condition=&quot;is not&quot;&gt;System&lt;/ProcessName&gt;<br>    &lt;/RawAccessRead&gt;<br>&lt;/RuleGroup&gt;</pre><p>Any alert on this rule - outside of backup software and disk utilities — is worth investigating immediately.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e23965b4825c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understating CVE-2025–55182 (React4Shell)]]></title>
            <link>https://medium.com/@shakedwe2/understating-cve-2025-55182-react4shell-01b2f542976d?source=rss-8eb24ca38cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/01b2f542976d</guid>
            <category><![CDATA[react2shell]]></category>
            <dc:creator><![CDATA[Shaked Wiessman]]></dc:creator>
            <pubDate>Sat, 06 Dec 2025 17:53:21 GMT</pubDate>
            <atom:updated>2025-12-08T07:20:22.368Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding CVE-2025–55182 (React4Shell)</h3><p>React and Node.js Vulnerability had Many Security Teams Working Overtime This Weekend, After this crazy discovery of the vulnerability, I had to understand and investigate it in depth.</p><p>In this article I will divide the topics into five parts</p><ol><li>Part 1 — We will understand how JavaScript manages its memory</li><li>Part 2 — We will understand the inheritance chain in JavaScript</li><li>Part 3 — We will talk about await and the then() function</li><li>Part 4 — We will talk about how any object can change any structure at runtime (what is called this is not a bug, it is a feature)</li><li>Part 5 — We will connect all the parts to understand the essence of the vulnerability</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*-1IUlt9EWkWzjAJI" /></figure><p><strong>Part 1 — Not like C++</strong></p><p>To fully grasp this vulnerability, we must first examine JavaScript’s underlying memory model. Unlike statically-typed languages such as C++, JavaScript is dynamic by design. This fundamental difference leads to the following key distinctions:</p><p>what is the meaning?</p><ul><li>In JavaScript, everything is an object on the heap, unlike in C++ where a function is simply a sequence of instructions stored in a read-only text section of memory. In JavaScript, however, almost everything is considered an “object.” This means that functions, arrays, and objects are all dynamically allocated structures on the heap, managed by the V8 engine.</li><li>Objects are Open HashMaps A critical distinction lies in the flexibility of data structures. In C++, once a struct or class is defined, its memory layout is fixed at compile-time. It is static, you cannot alter its layout, append new fields, or change types at runtime. In contrast, JavaScript objects behave like open HashMaps. They lack a fixed memory layout. The runtime environment permits the arbitrary addition of properties and methods to any object at any time, without restriction.</li><li>The Single Thread Execution Model The third distinction, which serves as the trigger for this vulnerability, is the execution model. C++ supports native multi-threading. When a computationally intensive task is required (such as file I/O or a network request), the standard approach is to spawn a new thread. This thread can “block” and wait for the operation to complete without freezing the application, In contrast, JavaScript operates on a Single Thread (the Main Thread). This implies that the thread must never block. If the Main Thread were to halt while awaiting a server response, the entire application would freeze. This architectural constraint necessitated the development of asynchronous mechanisms, such as the Promise and the await keyword, which we will examine later as the root cause of the exploit.</li></ul><p>Let’s look at the following example we will create a variable called shak, with console.dir we will see its structure as it is currently displayed in HEAP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*jaPDLW7jpb4Qt8V8Ed5uew.png" /></figure><p>It can be seen that we have created a kind of struct and our variable is called an “object i”</p><p>Now we will insert a new field into the variable</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*29yeJK8HeWTOpeM5ndIPKQ.png" /></figure><p>It can be seen that the structure of the variable has changed at runtime.</p><p><strong>Part 2 — The inheritance chain in JavaScript:</strong></p><p>As we discussed in the previous part, every function and variable in JavaScript is effectively treated as an object, represented as a separate structure within the HEAP.</p><p>To fully understand the implications of this architecture, let’s analyse the internal heap representation of a simple function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*cGKJlh1XzitRqjle7qjwhQ.png" /></figure><p>It can be seen that in the structure of such a function, it is more complex than the structure of a regular variable</p><p>We have the following fields:</p><ul><li>Length = The number of variables the function accepts, a + b.</li><li>Name = The name of the object (HeyFunction).</li><li>ProtoType = The Blueprint for Future Instances, This field is unique to functions and acts as the “Virtual Table” (vtable) for objects created by this function, The function itself does not use this prototype. Instead, when you create a new instance the JavaScript engine assigns this specific object to be the parent (__proto__) of the new instance.</li><li>[[Prototype]] or __proto__ = The parent object of the function, while the prototype field (above) is for the descendants of the function, this field represents the ancestors of the function itself. Since “HeyFunction” is an object itself, it inherits some properties (some functions) from its parent object.</li></ul><p>Are you lost?, Don’t worry, let’s understand this in depth :)</p><p>In JavaScript, every object has a parent object from which everything starts.<br>It is called “Object.Prototype”.<br>That is, every created object (function or variable) is linked to Obejct.Prototype.<br>From which every object is allowed to consume properties and functions that were not defined on it</p><p>For example, we defined a function:</p><pre>function wow(a,b){<br>  if (a &lt;= 5 || b &lt;= 10) {<br>      return 0;<br>  }<br><br>  return a + b;<br>}</pre><p>You can see that the function does something very simple receives two variables, it checks a condition if the condition is not met it returns the result of variable “a” plus “b”</p><p>What will happen if we do the following?</p><p>We will ask the function we created (wow) to execute a function called hasOwnProperty, which will receive a string variable</p><pre>console.log(wow.hasOwnProperty(&#39;name&#39;));</pre><p>the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*e7HA6wIWIBK1IKzIb9gp2A.png" /></figure><p>What happened here?</p><p>We called the “wow” function, and asked it to perform another action (another function) “hasOwnProperty”. The “hasOwnProperty” function accepts a string (in our case “name”) and it returned “true”.</p><p>The constructor accesses the memory address in the Heap and checks to see if the “wow” function has a property called “hasOwnProperty”. Since there is no such property, the constructor navigates to the [[Prototype]] field (usually called __proto__). This field contains a link to the parent object of our function, <br>Function.Prototype which is essentially the parent of every function in JavaScript.</p><p>The constructor looked for the “hasOwnProperty” function in Function.Property, after not being able to find it there, it navigated to the “__proto__” field found in “Function.prototype”, the field linked it to the superobject (the “grandfather”) of all objects in JavaScript</p><p>“Object.prototype”, where it looked for the “hasOwnProperty” field, found and executed the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*4PaCK6eMWua26Vsqv8qG7w.png" /></figure><p>It can be seen that inside the second [[Prototype]] (which is the entry for object.prototype) there is a function called “hasOwnProperty” that accepts a single variable (Length 1)</p><p>In object variables, “__proto__” will lead directly to Object.Prototype (and not go through function.prototype) because they are not functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*Sw93-40C37D1GV_iWgmcvg.png" /></figure><p>Let’s understand what happened here.</p><p>The wow function has a __proto__ field that is linked to Function.Prototype <br>Through this link, the WOW function can inherit from Function.Prototype additional properties and functions that are not defined on it</p><p>Function.Prototype is a parent object that all objects in JavaScript inherit fromת i.e. even “function yes(){}” can inherit from it</p><p>Function.Prototype also has a ”__proto__” field that links it to a higher object that is allowed to all axes and is called Object.Prototype<br>In fact, every object is connected in one way or another to this main object and can inherit from it.</p><p><strong>Part 3 — Async / Await and then()</strong></p><p>As mentioned earlier, JavaScript runs on a single thread for example, in a situation where we use a browser to download a file and we know that there is only a single thread if the thread was waiting for the file to finish downloading, the entire browser would simply wait and freeze and we as users would be a little annoyed</p><p>Given JavaScript’s Single Thread architecture, the Main Thread must never be blocked by heavy operations such as file I/O or network requests. To solve this, JavaScript utilises the Promise mechanism to perform Offloading.</p><p>When a Promise is instantiated (for example, via fetch), the JavaScript engine (V8) offloads the heavy lifting to the underlying Operating System (Kernel), which executes the task in parallel.<br>What constitutes ‘heavy lifting’? Downloading a file, running a timer, or essentially any operation that could cause the Main Thread to halt execution (block) — even for a few mere seconds.<br>When the JS engine encounters such a function, it performs a delegation of duties, requesting the Operating System to execute the task on its behalf.<br>Simultaneously, it registers the .then() callback in memory. This function serves as a listener, waiting for the Operating System to complete the operation delegated by the engine.</p><p>But how does the JS engine know that it needs to execute a Promise? The developer needs to define an object and bind it to Promise.Prototype.</p><pre>const ObjA= new Promise(...)}{</pre><p>Once the object is created, a link is created in the “__proto__” field to Promise.prototype, where the then() function exists.</p><p>Let’s look at the object definition (the following variable is a promise):</p><pre>const ObjA= new Promise((resolve, reject) =&gt; {<br>  console.log(&quot;System: Starting background task...&quot;);<br>  <br>    setTimeout(() =&gt; {<br>    console.log(&quot;OS: Task finished!&quot;);<br>    resolve(&quot;This is the data from the DB&quot;);<br>  }, 2000);<br>});</pre><p>The code has defined that the object ObjA is a Promise<br>The constructor will search the object’s structure for the Promise.prototype field and there it will search for the field that contains the then() function.</p><p>The following actions occur in order:</p><ul><li>Immediate Execution: The log “System: Starting background task…” is printed to the screen immediately.</li><li>Offloading: The constructor encounters the next instruction (the timer). Since waiting for 2 seconds would block the Main Thread and freeze the user interface, it offloads this task to the Operating System.</li><li>Registration: The main JavaScript code proceeds to execute ObjA.then(). This instruction effectively tells the object: ‘Listen, once you have a result, execute this specific code.’</li><li>Completion: Concurrently, the Operating System finishes counting the 2 seconds. The internal function within the constructor runs and calls resolve().</li><li>Resolution: The resolve() function checks the memory to identify who registered a listener via then() and triggers that execution.</li></ul><p>The Modern Standard: await, In older JavaScript codebases, handling asynchronous operations required manually chaining callbacks using .then(), a pattern that often led to deeply nested and unreadable code (famously known as “Callback Hell”).</p><p>To solve this, modern JavaScript introduced the await keyword, . It allows developers to write asynchronous code that appears linear and synchronous similar to C++</p><p>Instead of writing</p><pre>ObjA.then(data =&gt; { … });</pre><p>a developer simply writes</p><pre>const data = await ObjA;</pre><p>So, when the JS engine sees:<br>“await ObjA”<br>it immediately understands that it needs to run the then() function, which is a function it is familiar with (it will wait to receive a message from the one the engine has delegated to perform tasks on its behalf)</p><p><strong>Part 4 — Any object can change any structure:</strong></p><p>So we noticed that every object is stored in the HEAP as a type of Struct<br>and we saw that there is a relationship between structures in memory<br>An object that is chained to Object.Prototype</p><p>We also noted that it is possible to affect the values ​​of the structure while running , As mentioned in Part 1</p><p>What if I told you that it is also possible to affect fields of other structures</p><p>Even worse, it is possible to actually affect fields within the data structure of function.prototype and also of “Object.Proptotype”<br>The function.prototype is the “father” of all function structures<br>and the Object.prototype is the “grandfather” of all objects</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*zTeTMJOJaaCHsbn4B9ON7Q.png" /></figure><p>what just happened here??</p><p>We created two objects, ObjA and ObjB</p><p>By the way, it is important to note<br>such an object (variable) will have a __proto__ connection directly to Object.Prototype<br>it will not pass through function.prototype (since this object is a function)</p><p>After creating the two objects, we used ObjA to connect to Object.Prototype via __proto__ and define a new field named Description and give it a value of: “Hey From ObjectA”</p><p>Then we did an experiment<br>We used Console.log to print the value of Description found in ObjB.</p><p>But we never defined a Description field in ObjB. The constructor will go to the structure of ObjB, realize that there is no such field there, connect to Object.Prototype via __proto__, and there it will find the Description field that ObjA actually created.</p><p>Which means that we have completely influenced “ObjA” on “ObjB”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*XxK6jRsZcuMwEse0U6MAyA.png" /></figure><p><strong>Part 5 — the vulnerability:</strong></p><p>In this final section, we witness how the theoretical concepts of memory management and asynchronous execution converge into a critical Remote Code Execution (RCE) vulnerability (CVE-2025–55182). The exploit chain can be broken down into three distinct stages: The Injection, The Pollution, and The Detonation.</p><p>To understand how the exploit works, we must look at how React handles Server Actions internally. When a server action is processed, React/Next.js often wraps the data in an internal structure containing specific properties like _response, _formData, and _prefix.</p><p>The vulnerability lies in the server’s <strong>blind trust</strong> in the structure of the incoming JSON. The server assumes that if an object contains these private properties (prefixed with an underscore), it must be a legitimate internal object generated by the framework itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*O7IxCNK1qRwH08DzPjaZXQ.png" /></figure><p>In a legitimate scenario, _formData is an instance of the FormData class, which inherits a get() method from its prototype. In our exploit, _formData is a plain JSON object. It is not a real FormData instance. However, the attacker manually injects a get property directly into this object.</p><p>Using syntax ($1:constructor:constructor), the attacker wires this get property to point directly to the JavaScript Function Constructor. Effectively, this transforms _formData.get from a data-retrieval method into a code-execution machine (Function).</p><p>The _prefix field is designed to hold the Action ID string. The server uses this string to look up which function to run. The attacker replaces this ID with the malicious JavaScript payload (e.g., the reverse shell code).</p><p>React Server Components communicate using a specialized serialization format (“Flight Protocol”). When the server receives a request, it must parse strings into objects in the Heap. The Flaw: The parser responsible for this task was naive. It iterated over user-supplied keys and assigned them to objects without filtering restricted keywords. Specifically, it allowed a user to supply the key “__proto__”. As we learned in Part 4, accessing this key allows an attacker to break out of the specific object’s instance and modify the shared Object.prototype.</p><p>An attacker sends a payload structured as: “$1:__proto__:then”. Translated to JavaScript operations, the parser executes:</p><pre>targetObject.__proto__.then = MaliciousFunction;</pre><p>Since $1 is an object of type (variable) it has no stop in the way of function.prototype so the link from the “__proto__ “ field leads directly to object.prototype<br>what will happen there<br>we will define a field called then() that will contain a malicious function (like writing code to a machine), like: “require(‘child_process’).exec(‘/bin/sh …’);</p><p>As discussed in Part 3, the then function is the specific signal the V8 engine looks for to identify Promises,</p><p>The pollution sits dormant in memory. To execute the code, the attacker relies on the framework’s own behavior. Modern frameworks like Next.js often process data generically using “Await”, assuming inputs might be asynchronous. Somewhere in the server’s lifecycle, the code executes:</p><pre>await genericData;</pre><p>Waiting for the await command, is a feature of React it does this all the time behind the scenes!</p><p>We are dealing with a standard object that was not defined as a Promise, yet the code applies await to it (this is the heart of the vulnerability).</p><p>The Engine searches for a then() method (typically found in Promise.prototype).</p><ul><li>Since the object is not a Promise, it lacks this specific link.</li><li>The Constructor does not give up; it traverses up the chain to Object.prototype, There, it discovers the injected then() field</li><li>The Constructor: ‘Ah, okay, here is the then() function. This object is indeed a Promise.’</li><li>Constructor decides: ‘To avoid blocking the Main Thread, I must execute this function immediately to register the callback.’</li><li>The Result: The engine executes the malicious code, handing over control to the Operating System to spawn a shell -&gt; Remote Code Execution (RCE).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01b2f542976d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deconstructing Kerberos Authentication on windows]]></title>
            <link>https://medium.com/@shakedwe2/deconstructing-kerberos-authentication-on-windows-6f9c1aa469e2?source=rss-8eb24ca38cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f9c1aa469e2</guid>
            <dc:creator><![CDATA[Shaked Wiessman]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 19:56:37 GMT</pubDate>
            <atom:updated>2025-10-13T19:48:10.721Z</atom:updated>
            <content:encoded><![CDATA[<h4>Author : Shaked Wiessman, Red Teamer.</h4><p><a href="https://github.com/ShkudW">https://github.com/ShkudW</a> — My GitHub</p><p><a href="https://github.com/ShkudW/KerbFlow">https://github.com/ShkudW/KerbFlow</a> — Tool for this article.</p><p><a href="https://www.linkedin.com/in/shaked-wiessman/">https://www.linkedin.com/in/shaked-wiessman/</a> — My LinkedIn</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*hqypX0aYDa0pGO9yB620Yg.png" /></figure><p>Kerberos protocol serves as the authentication backbone of Active Directory environments, Many of us, whether we are penetration testers, security researchers, or IT professionals are familiar with its fundamental workflow:</p><ul><li>Requesting a TGT</li><li>Requesting a TGS with the TGT</li><li>Connecting to the target SPN</li></ul><p>However, my objective was to investigate the protocol beyond this common knowledge and gain a deeper understanding of its inner workings.<br>In this article I tried to investigate</p><ul><li><strong>how a user-mode application can use Kerberos </strong>: explore how client-side applications interact with Kerberos and demonstrate how an application can use the logged-on user’s security context to request a Service Ticket (TGS) for a remote service. We will focus on SSPI abstraction layer and the pivotal roles of <strong>AcquireCredentialsHandleW()</strong> and <strong>InitializeSecurityContextW().</strong></li><li><strong>What happens behind the scenes when a domain user account logs into the operating system</strong>: take a deep dive into Windows logon process itself, by attaching a debugger, and trace the real-time execution flow and identify the chain of Win-APIs that are triggered when a user authenticates to their workstation.</li><li><strong>Try to understand in depth the entire network flow from the client to the KDC and from the Client to the SPN connection over the Kerberos protocol </strong>: analyze the protocol on the wire, Using a custom Python-based tool, and parse the raw Kerberos packets, from AS-REQ to AP-REP to understanding of their structure and content, tying everything we’ve learned back to the network traffic.</li></ul><p>This article is structured into three main sections, each providing a different layer of insight into Kerberos.</p><h3><strong>Part 1 — SSPI (Security Support Provider Interface) :</strong></h3><p>First, let’s understand the role of SSPI -&gt; Security Support Provider Interface.</p><p>To illustrate its purpose, consider a common scenario in a corporate environment.<br>An application running on a user’s workstation needs to access a resource within the Active Directory domain, such as a file server, a database, or an internal web portal.</p><p>This application is faced with a fundamental two choice regarding authentication:<br><strong>A)</strong> The application could explicitly prompt the user to re-enter their password. With this credential, the application would then perform the necessary steps to authenticate against the KDC and acquire a Service Ticket (TGS) for the requested resource.<em><br></em><strong>B) </strong>Alternatively, the application can perform the entire authentication process on behalf of the user, without any direct involvement. From the user’s perspective, they simply click a “Connect” button, and access is granted.</p><p>This is the core of SSO experience, where the application leverages the user’s existing logon session to authenticate to remote resources automatically.<br>In many cases, such as when an application needs to aggregate data from various remote resources, this seamless experience isn’t just a convenience it’s a requirement. The user is not involved in the authentication process at all; they simply benefit from the application’s ability to operate on their behalf. This is precisely the problem that SSPI is designed to solve.</p><p>The Security Support Provider Interface is a key enabler of the Single Sign-On experience in Windows environments. It can be best understood through an analogy: think of SSPI as a universal power socket for authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*m2G8TFhqLMct6PnOYLusWg.png" /></figure><p>It provides applications with a standardized API to establish secure connections to network resources, without needing to know in advance which authentication protocol the resource supports.<br>For example, the application doesn’t need to be hardcoded to handle Kerberos or Net-NTLM specifically. Instead, the application that running on user’s workstation only needs to “speak” to SSPI mechanism.</p><p>At its core, SSPI is a set of Win-APIs, with functions like AcquireCredentialsHandle() and InitializeSecurityContext() being called by the client-side application.</p><p>It’s important to note that SSPI does not perform the authentication itself, rather, it acts as an intermediary.<br>The actual ”workers” in this architecture are the Security Support Providers (SSPs).</p><p>Each SSP is a DLL that implements a specific authentication protocol. Some of the most common SSPs in Windows include:</p><ul><li><strong>kerberos.dll</strong>: Implements the Kerberos protocol.</li><li><strong>msv1_0.dll</strong>: Implements Net-NTLM1/2 and NTLM protocols.</li><li><strong>schannel.dll</strong>: Implements certificate-based protocols like TLS and SSL for authentication and encryption.</li><li><strong>secur32.dll : </strong>This SSP acts as a meta-provider or a “negotiator.” When an application requests authentication without specifying a particular protocol (as we will demonstrate later in this article with a code sample that I wrote), It attempts to use the most secure protocol supported by both the client and the target resource.<br>In an Active Directory environment, by default it will attempt to use Kerberos first, if Kerberos authentication fails for any reason, it will automatically fall back to Net-NTLM. This built-in fallback mechanism is why most applications developed for Windows prefer to use the Negotiate package, as it provides greater flexibility and resilience.</li></ul><p>Let’s look at this simple code:</p><pre>#define SECURITY_WIN32 <br>#include &lt;windows.h&gt;<br>#include &lt;sspi.h&gt;<br>#include &lt;stdio.h&gt;<br><br>#pragma comment(lib, &quot;secur32.lib&quot;)<br><br><br>void PrintMeBaby(const char* title, PVOID data, DWORD length) {<br>    printf(&quot;%s (Size: %lu bytes):\n&quot;, title, length);<br>    if (length == 0) {<br>        printf(&quot;(empty)\n\n&quot;);<br>        return;<br>    }<br><br>    unsigned char* p = (unsigned char*)data;<br>    for (DWORD i = 0; i &lt; length; i++) {<br>        printf(&quot;%02X &quot;, p[i]);<br>        if ((i + 1) % 16 == 0) {<br>            printf(&quot;\n&quot;);<br>        }<br>    }<br>}<br><br>int main() {<br><br>    WCHAR SPN[] = L&quot;CIFS/GODCA.GODFATHER.LOCAL&quot;;<br><br>    CredHandle hCredentials;<br>    TimeStamp lifetime;<br><br>    SECURITY_STATUS first = AcquireCredentialsHandleW(<br>        NULL,<br>        (LPWSTR)L&quot;Negotiate&quot;,<br>        0x00000002,<br>        NULL,NULL,NULL,NULL,<br>        &amp;hCredentials,<br>        &amp;lifetime<br>    );<br><br>    if (first!= SEC_E_OK) {<br>        printf(&quot;Faild.... 0x%08x\n&quot;, first);<br>        return 1;<br>    }<br>    printf(&quot;Great!!! We got an Handle on Crednetials and Lifetime :)\n&quot;);<br><br> <br>    CtxtHandle hContext;<br>    hContext.dwLower = 0;<br>    hContext.dwUpper = 0;<br>    <br>    SecBufferDesc outputBufferDesc;<br>    SecBuffer outputTokenBuffer;<br><br>      outputBufferDesc.ulVersion = SECBUFFER_VERSION;<br>      outputBufferDesc.cBuffers = 1;<br>      outputBufferDesc.pBuffers = &amp;outputTokenBuffer;<br><br>    <br>      outputTokenBuffer.cbBuffer = 4096; <br>      outputTokenBuffer.BufferType = SECBUFFER_TOKEN;<br>      outputTokenBuffer.pvBuffer = new unsigned char[outputTokenBuffer.cbBuffer];<br>    <br>    ULONG contextAttributes;<br>    <br>    SECURITY_STATUS sec= InitializeSecurityContextW(<br>        &amp;hCredentials,<br>        NULL,<br>        SPN,<br>        ISC_REQ_DELEGATE,<br>        0,SECURITY_NATIVE_DREP,NULL,0,<br>        &amp;hContext,<br>        &amp;outputBufferDesc,<br>        &amp;contextAttributes,<br>        &amp;lifetime<br>    );<br><br>    if (sec== SEC_I_CONTINUE_NEEDED) {<br>        PrintMeBaby(&quot;AS-REQ: &quot;,outputTokenBuffer.pvBuffer,outputTokenBuffer.cbBuffer);<br>    }<br>    else {<br>        printf(&quot;Faild.... 0x%08x\n&quot;, sec);<br>        delete[] outputTokenBuffer.pvBuffer;<br>        FreeCredentialsHandle(&amp;hCredentials);<br>        return 1;<br>    }<br><br>    delete[] outputTokenBuffer.pvBuffer;<br>    FreeCredentialsHandle(&amp;hCredentials);<br>    DeleteSecurityContext(&amp;hContext);<br><br>    system(&quot;pause&quot;);<br>    return 0;<br>}</pre><p>Let’s break down what the code does.<br>First, we instruct the linker to include the secur32.lib import library using a pragma directive: #pragma comment(lib, “secur32.lib”).</p><pre>#pragma comment(lib, &quot;secur32.lib&quot;)</pre><p>This tells the linker that if it cannot resolve any of the WinAPI functions our code uses, it should look for them within this library.<br>Moving to the beginning of our main function:</p><pre>CredHandle hCredentials;<br>TimeStamp lifetime;<br><br>SECURITY_STATUS secStatus = AcquireCredentialsHandleW(<br>    NULL,<br>    (LPWSTR)L&quot;Negotiate&quot;,<br>    0x00000002,<br>    NULL,NULL,NULL,NULL,<br>    &amp;hCredentials,<br>    &amp;lifetime<br>);</pre><p>we see the first key API call: AcquireCredentialsHandleW.</p><p>The primary purpose of this function is to populate two output variables by writing to the memory addresses we provide:<br><strong>&amp;hCredentials</strong>: This will be filled with a handle to the credentials of the currently logged-on user. This handle is an opaque structure that represents the user’s security context for outbound authentication.<br><strong>&amp;lifetime</strong>: This will be filled with a timestamp indicating the validity period of the returned credentials handle.”</p><p>The parameters for AcquireCredentialsHandleW are configured as follows:<br><strong>Parameter 1 (NULL):</strong> By passing NULL, we are telling the SSP to simply use the identity of the currently running user, which is the standard approach for Single Sign-On.<em><br></em><strong>Parameter 2 ((LPWSTR)L”Negotiate”): </strong>We select the “Negotiate” package for maximum flexibility. As previously discussed, this allows the system to automatically choose the best available protocol (typically Kerberos in a domain environment) by negotiating with the target server, rather than hardcoding Kerberos or Net-NTLM.<em><br></em><strong>Parameter 3 (0x00000002):</strong> This value, SECPKG_CRED_OUTBOUND, specifies that we are acquiring these credentials for client-side, outbound authentication.<em><br></em><strong>Parameter 8 (&amp;hCredentials)</strong>: This is the most critical output parameter. It’s a pointer to a handle that the function will populate. This handle encapsulates the user’s identity and is essential for our next function call.<em><br></em><strong>Parameter 9 (&amp;lifetime)</strong>: This output parameter is a pointer to a timestamp that the function fills with the handles expiration time.</p><p>Now, let’s continue to the secomde Win Api function:</p><pre>CtxtHandle hContext;<br>hContext.dwLower = 0;<br>hContext.dwUpper = 0;<br><br>SecBufferDesc outputBufferDesc;<br>SecBuffer outputTokenBuffer;<br><br>  outputBufferDesc.ulVersion = SECBUFFER_VERSION;<br>  outputBufferDesc.cBuffers = 1;<br>  outputBufferDesc.pBuffers = &amp;outputTokenBuffer;<br><br>  outputTokenBuffer.cbBuffer = 4096; <br>  outputTokenBuffer.BufferType = SECBUFFER_TOKEN;<br>  outputTokenBuffer.pvBuffer = new unsigned char[outputTokenBuffer.cbBuffer];<br><br>ULONG contextAttributes;<br><br><br>SECURITY_STATUS sec= InitializeSecurityContextW(<br>    &amp;hCredentials,<br>    NULL,<br>    SPN,<br>    ISC_REQ_DELEGATE,<br>    0,SECURITY_NATIVE_DREP,NULL,0,<br>    &amp;hContext,<br>    &amp;outputBufferDesc,<br>    &amp;contextAttributes,<br>    &amp;lifetime<br>);</pre><p><strong>CtxtHandle hContext:</strong> First, we allocate memory for a context handle. This handle will represent the specific security context for this authentication session. The CtxtHandle is a structure containing two fields, dwLower and dwUpper, both of which we initialize to zero. This initialization signifies that we are initiating a new security context, as opposed to referencing an existing one.<br><strong>SecBuffer outputTokenBuffer: </strong>Next, we declare a SecBuffer structure. This structure acts as a container (or “tray”) where the Security Support Provider Interface (SSPI) will place the security token it generates.<br><strong>SecBufferDesc outputBufferDesc:</strong> This structure serves as a descriptor for the SecBuffer. It effectively tells the SSPI, “Here is a buffer container, this is its description, and this is where you should place the output token.</p><p>This InitializeSecurityContextW() function performs the core authentication work. It takes all the previously prepared handles and buffers and uses them to construct the initial Kerberos AS-REQ packet.<br>A critical aspect of using the Negotiate package is that this single function call triggers a full, automated exchange with the KDC</p><p>This includes:</p><ul><li>Building the AS-REQ (Authentication Service Request).</li><li>Transparently sending it to the KDC and receiving the AS-REP (Authentication Service Reply), which contains the Ticket-Granting Ticket (TGT).</li><li>Using the TGT to build and send a TGS-REQ (Ticket-Granting Service Request) for the specified SPN.</li><li>Receiving the TGS-REP (Ticket-Granting Service Reply), which contains the Service Ticket.</li><li>Finally, constructing the output token, which is the AP-REQ (Application Request), ready to be sent to the target server.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HD3f7kt67S25fZSkaoXQ_A.png" /><figcaption>we can see that we built successfully AS-REQ packet</figcaption></figure><h3>Part 2 — Logging Flow and Lsass.exe debugging:</h3><p>As we demonstrated in the first part of this article, we successfully built a simple application that utilizes SSPI Security Support Provider Interface to generate a Kerberos authentication first request (AS-REQ).</p><p>To briefly recap, for a user-mode application to leverage the SSPI framework, it must load the SspiCli.dll library. This DLL serves as the gateway for all user-space security operations</p><p>for better understanding of these mechanisms, I have set up a Windows 11 virtual machine and performed remote debugging from the host system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vOcCUkRkLBXlk5WepFGjQ.png" /></figure><p>After the operating system has booted, I have set a breakpoint on the kerberos!KerbCredIsoInProc::CreateAsReqAuthenticator function, which is responsible for generating the AS-REQ Request.</p><p>This function is in SSP — Kerberos.dll<br>which lsass process loads into it<br>I wanted to stop the debugger at the memory address where the function starts to try and see the path the operating system took to this function<br>which can be seen from its name — it is the one that creates the AS-REQ request for us</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7eAuwLO2fbtBS3bRiE8Sw.png" /></figure><p>Now that the debugger has reached the breakpoint, I can dive into the interactive login process, where I log in to the operating system with a domain user account called “shakedw”.<br>I used the debugger to see the trace that happened in the background when I pressed the submit key (the little arrow on the login screen).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_h6SFbLt43angKZdX6I5g.png" /></figure><pre>00 00000072`2e17d5b8 00007ff9`c6d42d25     kerberos!KerbCredIsoInProc::CreateAsReqAuthenticator<br>01 00000072`2e17d5c0 00007ff9`c6d4861d     kerberos!KerbBuildPreAuthData+0x475<br>02 00000072`2e17d730 00007ff9`c6d44601     kerberos!KerbGetPreAuthDataForRealm+0x77d<br>03 00000072`2e17d8a0 00007ff9`c6cfa6d8     kerberos!KerbGetAuthenticationTicketEx+0x1671<br>04 00000072`2e17de80 00007ff9`c6d126ec     kerberos!KerbGetTicketGrantingTicket+0x4e8<br>05 00000072`2e17e4c0 00007ff9`c6d10332     kerberos!KerbILogonUserEx3+0x239c<br>06 00000072`2e17ea90 00007ff9`c7894bd9     kerberos!LsaApLogonUserEx3+0xb2<br>07 00000072`2e17eb30 00007ff9`c78938b3     lsasrv!NegLogonUserEx3Worker+0xa81<br>08 00000072`2e17ecc0 00007ff9`c791de13     lsasrv!NegLogonUserEx3+0x373<br>09 00000072`2e17efa0 00007ff9`c7935b0f     lsasrv!LsapCallAuthPackageForLogon+0xdb<br>0a 00000072`2e17f050 00007ff9`c78d558b     lsasrv!LsapAuApiDispatchLogonUser+0x53b<br>0b 00000072`2e17f3a0 00007ff9`c6431957     lsasrv!SspiExLogonUser+0x2cb<br>0c 00000072`2e17f7d0 00007ff9`c693c796     SspiSrv!SspirLogo</pre><pre>10 00000072`2e17fd00 00007ff9`cae88d9c     KERNEL32!BaseThreadInitThunk+0x17<br>11 00000072`2e17fd30 00000000`00000000     ntdll!RtlUserThreadStart+0x2c</pre><p>These functions represent the underlying infrastructure for thread creation within any user-mode process.<br><br>In Windows operating system, the logon process is this way:<br>Winlogon.exe is the process that responsible for the overall management of the logon environment. It presents the secure desktop and launches essential system processes.<br>LogonUI.exe: is the process that handles the entire graphical user interface of logon screen. It is responsible for displaying the password text box, the user’s profile picture, and the sign-in button.<br>When we type the password and click the sign-in button, the LogonUI.exe process collects the username and password and then calls the LsaLogonUser():</p><pre>0d 00000072`2e17f950 00007ff9`c693c503     SspiCli!SspipLogonUser+0x286<br>0e 00000072`2e17fb40 00007ff9`c78cdf64     SspiCli!LsaLogonUser+0x83</pre><p>The LsaLogonUser() function, located in SspiCli.dll, is just a wrapper for a more internal function within that same DLL named SspipLogonUser(). The p prefix in the name typically denotes a “private” function.<br>The role of SspipLogonUser is to construct an ALPC (Advanced Local Procedure Call) message and send it to the lsass.exe process. It takes the parameters received from LsaLogonUser, packages them into a defined structure, and executes the call that crosses the boundary between the two <br>The lsass.exe process loads a wide variety of DLLs, two of which are critical here:<br><strong>lsasrv.dll</strong>: Contains the central core of the Local Security Authority (LSA) and is responsible for managing security policy and dispatching requests.<br><strong>SspiSrv.dll</strong>: A specific module that serves as the entry point for incoming SSPI requests.</p><p>In addition, lsass.exe will also load kerberos.dll later.</p><pre>0b 00000072`2e17f3a0 00007ff9`c6431957     lsasrv!SspiExLogonUser+0x2cb<br>0c 00000072`2e17f7d0 00007ff9`c693c796     SspiSrv!SspirLogonUser+0x267</pre><p>The request from SspiCli.dll arrives at lsass.exe via ALPC, The kernel then wakes a dedicated thread within lsass to handle this request. This thread begins its execution in the code of SspiSrv.dll, specifically at SspiSrv!SspirLogonUser. This function unpacks the request and calls the lsasrv!SspiExLogonUser function, located in lsasrv.dll.</p><p>Now, deep inside lsass.exe, the functions responsible for dispatching the request are:</p><pre>09 00000072`2e17efa0 00007ff9`c7935b0f     lsasrv!LsapCallAuthPackageForLogon+0xdb<br>0a 00000072`2e17f050 00007ff9`c78d558b     lsasrv!LsapAuApiDispatchLogonUser+0x53b</pre><p>These functions examine the requested logon type (interactive or network) and the requested authentication package (Negotiate or Kerberos).<br>From there, they forward the request to:</p><pre>07 00000072`2e17eb30 00007ff9`c78938b3     lsasrv!NegLogonUserEx3Worker+0xa81<br>08 00000072`2e17ecc0 00007ff9`c791de13     lsasrv!NegLogonUserEx3+0x373</pre><p>At this stage, the LSA has decided that the request should be handled by the Negotiate authentication package. Negotiate then determines that the resource being accessed (in this case, the local machine) requires Kerberos authentication, which is the default in an Active Directory environment. This triggers the subsequent calls into the Kerberos security provider to begin the authentication protocol.</p><pre>00 00000072`2e17d5b8 00007ff9`c6d42d25     kerberos!KerbCredIsoInProc::CreateAsReqAuthenticator<br>01 00000072`2e17d5c0 00007ff9`c6d4861d     kerberos!KerbBuildPreAuthData+0x475<br>02 00000072`2e17d730 00007ff9`c6d44601     kerberos!KerbGetPreAuthDataForRealm+0x77d<br>03 00000072`2e17d8a0 00007ff9`c6cfa6d8     kerberos!KerbGetAuthenticationTicketEx+0x1671<br>04 00000072`2e17de80 00007ff9`c6d126ec     kerberos!KerbGetTicketGrantingTicket+0x4e8<br>05 00000072`2e17e4c0 00007ff9`c6d10332     kerberos!KerbILogonUserEx3+0x239c<br>06 00000072`2e17ea90 00007ff9`c7894bd9     kerberos!LsaApLogonUserEx3+0xb2</pre><p>As with any complex subject, I find that visualizing the concepts through diagrams greatly enhances my understanding and allows me to grasp the broader context more effectively.</p><p>Yes, I know… my PowerPoint editing skills are excellent :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFJl116d05w6PkVTLhNLuA.png" /></figure><h3>Part 3 — Kerberos protocol traffic analysis:</h3><p>We are now moving to the final section, where I will analyze the authentication packets transmitted over the network. For an in-depth analysis, I have developed a Python tool that leverages the impacket.krb5 and pyasn1.codec.der libraries.</p><p>The tool is available on my github page:</p><p><a href="https://github.com/ShkudW/KerbFlow">https://github.com/ShkudW/KerbFlow</a></p><p>This tool is designed to optimally present the structure of these packets prior to encryption, providing clear insight into their contents.</p><p>First, I cleaned the ticket cache on our machine. Then, I attempted to connect to C$ share on a remote server named godca.godfather.local.</p><p>As observed, I have captured the network traffic using Wireshark, and all Kerberos authentication packets are visible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ncugjzyNlNbeFMbROG005g.png" /></figure><p>Let’s focus on the first request AS-REQ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJaowsz35ZJ_ZOus0F6SmQ.png" /></figure><p>As can be observed, this request is not encrypted. This is because a legitimate action by a user account requesting a TGT is initially sent unencrypted. The KDC, on its part, checks whether Pre-Authentication is configured for the user account. If it is, the KDC will return an error message: KRB Error: KRB5KDC_ERR_PREAUTH_REQUIRED:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1qVKEwhbPNSj4ROcECHEg.png" /></figure><p>In this message returned by the KDC, we can observe:<br>ERR-PREAUTH-REQUIRED (25), This is a typical response to an AS-REQ that does not contain Pre-Authentication data, indicating that the KDC requires it.<br>The KDC utilizes the PA-DATA PA-ETYPE-INFO2 field to inform the client about the encryption types it supports and requires for Pre-Authentication:<br><strong>ETYPE-AES256-CTS-HMAC-SHA1–96 (18)</strong>: This represents AES256 encryption with a salt, which is typically derived from the domain name combined with the username, e.g., GODFATHER.LOCALshakedw.<br><strong>ETYPE-ARCFOUR-HMAC-MD5 (23)</strong>: This is RC4 encryption with HMAC-MD5, an older encryption method that is still supported for compatibility reasons.</p><p>Additionally, the KDC also informs the client what data it expects to be encrypted. This can be observed in the PA-DATA pA-ENC-TIMESTAMP (2) field, where all values are currently missing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cSzZiTQu8aeLy-QciWbMqw.png" /></figure><p>Now that the client understands it must encrypt the current timestamp and provide the Pre-Authentication data using an encryption key derived from its password, as the KDC offered two encryption types, the client will perform a hashing function on its password, combined with the salt received from the KDC (comprising the domain name and username), to generate the specific encryption key. Subsequently, the timestamp will be encrypted, and this packet will be sent to the KDC as the initial AS-REQ in the authentication mechanism.</p><p>The client generates a unique number called a nonce (number used once). This is a one-time random number that it sends to the KDC.<br>The KDC will return the same nonce, encrypted, within the AS-REP response. The client then compares the nonce present in the AS-REP packet with the nonce it originally sent in the AS-REQ packet. If they match, the client knows that the response is indeed from a legitimate KDC.<br>Without the nonce, an attacker could potentially capture an AS-REP request and replay it to the client.</p><p>Now, we will use KerbFlow.py tool to inspect the encrypted content.</p><p>I used Rubeus to generate the encryption key for the user account shakedw with the password Ss123456.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*PWBhf-OHoKVAMLQAANUOjA.png" /></figure><p>And I extracted all the necessery hashes for: krbtgt, godca$ accounts using the NTDS.dit hive.</p><p>From Wireshark window I copied the encrypted value of AS-REQ packet:</p><pre>.\python.exe kerbflow.py as-req --cipher &lt;xxx&gt; --key &lt;xxx&gt; --etype 18</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nrvGcmtoxszqqoR_hFCZ4w.png" /></figure><p>On the KDC side, It will receive the AS-REQ packet with the encrypted timestamp, since the Domain Controller hold the NTDS.dit hive, it can easily decrypt this message with the AES256 hash of shakedw user account. <br><strong>Important note :if more than five minutes have passed since the client sent the AS-REQ request, the KDC will reject the request and ask the client to match it again.</strong><br>Now let’s examine the AS-REP packet returned from the KDC to the Client:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzK4_95xi_XVVyG5zIAXNw.png" /></figure><p>As can be seen in the AS-REP packet, the KDC returns two main parts: the ticket (TGT) and enc-part for the User account.<br>The ticket field contains the TGT (Ticket-Granting Ticket) itself. This TGT is signed and encrypted using etype 18 (AES256 with a hash derived from the password of the krbtgt service account). The client will store this part in its cache and use it to prove prior authentication by the KDC, and to request Service Tickets (STs) from the KDC.<br>The enc-part (encrypted part) contains data encrypted with the client’s password hash, This section typically includes information like the session key for the TGT, the timestamp, and the nonce, all encrypted with a key derived from the client’s password. The client decrypts this part using its own password hash to retrieve the session key and verify the nonce.</p><p>Let’s use KerbFlow.py tool for decrypt these two parts of this packet.</p><pre>python.exe kerbflow.py as-rep --tgt-ticket &lt;xxx&gt; --krbtgt-key &lt;xxx&gt; --ticket-etype 18</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jm67Wwj8VlASAjjMiNOvCQ.png" /></figure><p>The TGT itself has two parts, The first part includes:</p><ul><li>The name of the user account to which the TGT was issued.</li><li>The Domain name.</li><li>When the authentication was performed.</li><li>The expiration date of the TGT.</li><li>Flags attached to the TGT.</li><li>Session key.</li></ul><p>The second part is the PAC:<br>The PAC is a critical extension to the Kerberos protocol<br>It is a digitally signed and encrypted data structure (as we have seen), which includes the user’s authorization data<br>In the Kerberos protocol, the Service Ticket mainly verifies who the user is who requests to use the service, but what the user can do while using the service is no less important.<br>The decision of what the user can do with the service relies on the SIDs (security identifiers) and which groups the user is a member of.<br>Without the PAC, the server receiving the Service Ticket would have to log in to the KDC each time in order to check with it what the user’s authorization level is<br>In the AS-REP package, the KDC already builds the PAC package for the user’s account<br>The PAC, as you can understand, is a pretty attractive target for attackers, because it contains critical information about the user. If an attacker manages to hack it, he can try to obtain higher authorization.</p><ul><li>The user’s username</li><li>The number of logins of the user</li><li>Groups to which the user is a member</li><li>Additional SIDs that can be assigned to the user</li><li>And of course the Session key</li></ul><p>As we mentioned, the AS-REP request has two parts: the first part is the TGT, which includes the PAC, and the second part is encrypted with the hash derived from the user’s password, let’s see that part using the Kerbflow tool.</p><pre>.\python.exe kerbflow.py as-rep --client-cipher &lt;xxx&gt; --client-key &lt;xxx&gt; --client-etype 18 --client-name shakedw</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KT_BDJzP1KOENJEr6AJ-ug.png" /></figure><p>In this second part og AS-REP packet, it can be found the same Session key that is also stored in the TGT, this Session key will be used by the user to send the TGS-REQ request for Service ticket requesting. <br>In addition, the operating system collects all the data and builds the friendly structure of the TGT that we know from the “klist” command<br>And it can be seen below the “nonce” that was sent in AS-REQ request from the client to the KDC.<br>This way the user knows that this tampering is reliable and has not been changed by an outside party.</p><p>Now let’s move on to the next request<br>TGS request for CIFS service (TGS-REQ):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLcuUqoTCnfRHdsmo3i8dg.png" /></figure><p>This message contains three parts also</p><p>The first part is the Ticket (the TGT) previously issued in the AS-REP and the second part is the Authenticator, which is encrypted with the session key that the User got in AS-REP packet, The third part is the sname-string<br>where the full SPN will be specified, i.e. the name of the requested service on the requested target server.</p><p>Upon receipt, the KDC decrypts the TGT with the krbtgt AES256 hash, retrieves the embedded session key, using that session key to decrypt and validate the Authenticator part.</p><p>Let’s use KerbFlow.py tool to see the authenticator part:</p><pre>.\python.exe kerbflow.py tgs-req --authenticator-cipher &lt;xxx&gt; --session-key &lt;xxx&gt; --authenticator-etype 18</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5iTt45jspIoMEYcMjm_plg.png" /></figure><p>You can see that the authenticator part contains the username of the service requester, and the domain name.<br><strong>Why does the user do this?</strong></p><p>The reason is very simple, the KDC does not maintain an authentication list, that is, it does not remember to whom it issued a TGT and when.<br>When a User wants to request a Service Ticket from the KDC, it will send it the TGT that is signed and encrypted with the hash of krbtgt and the authenticator part and there it will specify its name.<br>In this way, the KDC will understand that the person who sent it the TGT is a legitimate user, and based on the name that appears in the authenticator part, for whom to issue the service ticket.</p><p><strong>Note: It can be seen that in the TGS-REP request, the part where the user specifies the service name and the target server name (SPN) is not encrypted at all.<br>The existence of this field opens up the possibility for attackers to manipulate service tickets over the Kerberos protocol.<br>But I will elaborate on this manipulation and various attacks related to it in another article of mine.</strong></p><p>And let’s move on to the package that KDC returns to us:<br>TGS-REP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5Hgk8bYr8Dt41cRig45NQ.png" /></figure><p>The TGS-REP packet, similar to the AS-REP packet, also contains two parts: a part where the ticket is generated (in this case the TGS) and a part intended for the user, this time encrypted with the Session key that the user received from the KDC in the AS-REP packet.</p><p>Let’s use KerbFlow tool to see the encrypted parts:</p><pre>.\python.exe kerbflow.py tgs-rep  --tgs-ticket &lt;xxx&gt; --tgs-service-key &lt;xxx&gt; --tgs-ticket-etype 18</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGTfy194NCCm1Zvs-XfRaA.png" /></figure><p>When decoding the first part of the TGS-REP packet (TGS decoding), a similar structure can be seen as we saw in the TGT, a new session key (which will be used by the user for the AP-REQ request), and the PAC.</p><p>And now we will see with KerbFlow tool the encrypted part with the Session key (from the TGS-REP package)</p><pre>.\python.exe kerbflow.py tgs-rep --encpart-cipher &lt;xxx&gt; --session-key &lt;xxx&gt; --encpart-etype 18 --client-name shakedw</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*laTTQhbUuekhMKXyDmHUXg.png" /></figure><p>In this section, you can see that the User decrypts and receives the same Session key that exists in the TGS and assembles the TGS for presentation in the operating system.</p><p>Now, when the client has the TGS with him<br>he can make a direct call to the requested resource to try and authenticate himself against that resource (in our case that remote server named godca.godfather.local)<br>this packet is called AP-REQ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kljeR8G55xzZEv24txGiA.png" /></figure><p>This packet also consists two parts<br>The first part contains the TGS that the user received from the KDC<br>The second part contains the Authenticator part which is encrypted with the Session key that the user received in the TGS-REP packet from the KDC</p><p>Let’s decrypt this authenticator part with KerbFlow tool:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sxo8hfRLsjIz3I_z0_Ab9w.png" /></figure><p>When the target server receives this packet, it will decrypt the service ticket (TGS), extract the session key and the user’s PAC from there.<br>Using the session key, it will decrypt the Authenticator part and verify a match between the username appearing in the PAC and the username appearing in this part.</p><h3><strong>Now let’s talk about special situations:</strong></h3><p><strong>Unconstrained delegation:</strong></p><p>In a situation where a user account requests a Service Ticket for an SPN located on a host (a machine account for the benefit of the domain) and that host is configured for unrestricted delegation, when the KDC understands this, it will issue a special flag “ok_as_delegate” to the TGS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*d5R-Ox1YY4zEgrtIKDr-cA.png" /></figure><p>For the sake of understanding the process, I configured the target server GODCA.godfather.local with the Unconstrained delegation setting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*epbWK0U2U7tS-Q0Wav9U_A.png" /></figure><p>And now from the station where I am logged in with the account user “Shakedw”, I cleared the cache from tickets and requested to connect via Winrm (so that in the background full authentication will be performed against the KDC and my user will request TGS for HTTP transmission)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ii4ffseDHY6qDXiqk-djw.png" /></figure><p>As you can see something strange happened here,<br>The TGS-REQ and TGS-REP request was executed twice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*emJZEh-Bci1_xvf0CHWsoQ.png" /></figure><p>What happened here is actually a cool thing that sheds light on Kerberos<br>When the client requested a TGS for an HTTP service (like in our example), and the KDC realized that this SPN was on GODCA$ which is configured with Unconstrained delegation, it set a special flag in the TGS of ok_as_delegate</p><p>Upon receiving this ST, the client immediately requested another Service Ticket from the KDC<br><strong>But for which service?</strong></p><p>In the second TGS-REP request, you requested the SPN of Krbtgt, which is of course located in the Domain Controller itself, you see, recognized as a TGT.<br>But how does a TGS that requests krbtgt?<br>So we can summarize it like this — the TGT itself is actually a service Ticket</p><p>Another interesting thing is that in each TGS-REP a new session key was received.<br>The session key received in the first TGS-REP packet (for the HTTP service) will be used by the user in the AP-REQ packet which he will send directly to the target server in order to connect to the requested service</p><p>The session key received in the second TGS-REP packet (for the krbtgt service) will be used by the user (when he is already connected to the target service in godca$ to request each TGS from the KDC, which actually supports the definition of unconstrained delegation that we know</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSj9MoAcGkJlI8-ki6pedA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPl7zka_XSxcq3803QoKYw.png" /></figure><p>Now let’s see how the special TGS we received from our station passes to the target server<br>I remind you<br>We on the win 11 station connected via Winrm to godca.godfather.local<br>which is defined as unconstrained delegation<br>to which we will connect with the HTTP TGS<br>and in the part of the authenticator which is encrypted with the Session key received by the user in the first TGS-REP package (of HTTP) will enter the TGS intended for the krbtgt service (i.e. the TGT that will be used by my user on godca.godfather.local, for the purpose of connecting to the cifs service on godweb.godfather.local)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6C_D4MVnV19_4UOxXyaw7g.png" /></figure><p>And let’s decrypt the authenticator part using the session key:</p><pre>.\python.exe .\kerbflow.py ap-req --authenticator-cipher &lt;xxx&gt;  --session-key &lt;xxx&gt; --authenticator-etype 18</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qVBbUO93uNa632f__0tf5w.png" /></figure><p>As you can see, the authenticator part is very large and contains the krbtgt TGS and another part that is encrypted with the session key (received in the HTTP TGS-REP packet)<br>If we decrypt this small part, we can find the Session key (received in the second TGS-REP packet for the Krbtgt service)<br>so that its user can use his TGT on the target server to request TGS for other services</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BJLNmVK54amhQju4d-K5A.png" /></figure><p><strong>Trust Relationship:</strong></p><p>In a trust relationship,<br>where a user account in Domain A wants to connect to a service (SPN) located in Domain B and there is a Trust relationship between the two domains.<br>In the case I will demonstrate here, it is a parent-child relationship, with a user account from the Root Domain — shakenw I want to connect to a CIFS service on a target server that is associated with the Sub domain — abcgodweb.abc.godfather.local.</p><p>Also in this situation, similar (but different), in the background you can see the TGS-REQ and TGS-REP requests being made twice.<br>But the first time the TGS-REQ packet is directed to the KDC root domain — godc1.godfather.local<br>And the second time the TGS-REQ packet is directed to the KDC sub domain — abcgodc1.abc.godfather.local</p><p>As you can see from the Windows 11 workstation (which is connected to the Root Domain) I am requesting to connect to the CIFS service on the target server in the subdomain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pY31f67E3ef5RpHdIsdQRA.png" /></figure><p>The following packages were received in the background:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*vqB7wHC22puQEPnBLgu-HA.png" /></figure><p>As you can see, the AS-REP packet is received from the root KDC where the user account shakendw was able to authenticate itself and receive a TGT and a portion that is encrypted with the hash of its password:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-JHZZx6ZB4Ji93r9IFVQw.png" /></figure><p>Now the user account will request to connect to the SPN cifs\abcgodweb.abc.godfather.local</p><p>The KDC that receives the request will understand that this SPN does not belong to its domain of responsibility and will understand that the realm name is associated with a domain with which it has a Trust relationship.<br>The KDC will return a TGS-REP packet containing a special service ticket intended for the Krbtgt service<br>But this service ticket is encrypted with an Rc4_HMAC hash of the Trust key between the root domain and the sub domain</p><p>Now we will decrypt using our tool, on the encrypted part with the Session key in the first TGS-REP packet (the same Session key received in the AS-REP packet from the root KDC):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LK9DQTRsPwtbaC8VVATp5Q.png" /></figure><p>With this card, the user account in the Root Domain can contact the KDC in the Sub domain directly and request an additional service card for the CIFS service on the target server in the TGS-REQ packet.<br>The KDC in the sub domain also knows the Trust key, will decrypt the TGS part.<br>Extract the Session key from there and decrypt the Authenticator part</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GEZWKzAAgWSS3z9xm8G13Q.png" /></figure><p>That is, in this case, we see a TGS request with the help of TGS.<br>But again, we have already understood that TGT itself is also a service ticket.</p><p>I really hope you enjoyed reading. I really had fun researching Kerberos. I assume I’ll add more things later to this article or another article. See you in the next articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f9c1aa469e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>