<?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 Luciano Pereira on Medium]]></title>
        <description><![CDATA[Stories by Luciano Pereira on Medium]]></description>
        <link>https://medium.com/@zaikoarg?source=rss-a25e297d14c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y645k48lo3oZrlgI_64YSQ.jpeg</url>
            <title>Stories by Luciano Pereira on Medium</title>
            <link>https://medium.com/@zaikoarg?source=rss-a25e297d14c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 23 May 2026 16:25:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zaikoarg/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[Unmasking Kerberos | Attacking the Kerberos Authentication Layer]]></title>
            <link>https://medium.com/@zaikoarg/unmasking-kerberos-attacking-the-kerberos-authentication-layer-7c05a6efa52b?source=rss-a25e297d14c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c05a6efa52b</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[ethical-hacking]]></category>
            <category><![CDATA[active-directory]]></category>
            <dc:creator><![CDATA[Luciano Pereira]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 18:40:16 GMT</pubDate>
            <atom:updated>2023-10-03T18:40:16.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFF3fHne85URlp_6zbMkdw.png" /><figcaption>Banner</figcaption></figure><h3>Introduction</h3><p>Hello everyone, I’m Luciano Pereira, also known as ZaikoARG. Today, I invite you to dive into another article where we will explore the fascinating world of Kerberos authentication and the potential threats lurking in this layer.</p><p>The purpose of this article, as in most of my writings, is to provide a deep understanding. Beyond learning how to exploit the vulnerabilities we will discuss, my goal is for you to grasp the underlying workings. This understanding will offer you significant advantages, such as improving lateral thinking, honing your instincts, and increasing your flexibility to adapt to each exploitation scenario.</p><p>I want to make it clear that this article will not provide instructions on which commands to execute to carry out the attacks we will discuss. In my opinion, these attacks are widely known, and there are numerous websites on the Internet where you can easily find the necessary instructions with just a few clicks. My primary objective is to focus on explaining the workings of these vulnerabilities, as that is what I aim to highlight in this article.</p><h3>Kerberos Authentication Layer</h3><p>To fully grasp each vulnerability that will be addressed in this article, it is essential that we have a solid understanding of how the Kerberos authentication layer operates and how the authentication flow unfolds. Next, we will explore fundamental concepts that lay the groundwork for our comprehension, such as: What is Kerberos? and how does a basic authentication flow in Kerberos work?</p><h4>What is Kerberos?</h4><p>Kerberos is a widely used network protocol, primarily in Windows systems, for user and service authentication processes in a network. Authentication in Kerberos operates through encrypted tokens known as Ticket Granting Ticket (TGT) and Ticket Granting Service (TGS or ST).</p><h4>What is a KDC (Key Distribution Center)?</h4><p>The Key Distribution Center (KDC) is a component of the Kerberos authentication and authorization protocol. Its primary function is to manage and distribute access tickets to enhance security in user and service authentication on the network.</p><p>The KDC consists mainly of two parts:</p><ul><li><strong>Authentication Service (AS)</strong>: This is the first component that a user communicates with when they want to authenticate themselves in the system. It is responsible for validating the user’s identity and issuing Ticket Granting Tickets (TGTs).</li><li><strong>Ticket Granting Server (TGS)</strong>: This is the second component that a user communicates with. The client communicates with the TGS after obtaining a TGT from the AS. It is responsible for validating the TGT and granting Service Tickets (STs) to access a specific service.</li></ul><h4>TGT and TGS Structure</h4><p><strong>Ticket Granting Ticket (TGT)</strong>: When a user authenticates themselves on a network, they communicate with the Kerberos authentication service, specifically the Key Distribution Center (KDC). The KDC then issues a TGT, which is saved by the client. This TGT is an encrypted token that contains information about the authenticated user and a temporary session key known as the TGS Session Key.</p><ul><li><strong>Contents of the TGT</strong>: The TGT includes information such as the user’s name, the authentication server’s name, a timestamp, and the TGS Session Key. Initially, this TGT is encrypted with the KDC Master Key (which is essentially derived from the <strong>KRBTGT</strong> user account key) and then encrypted with the User Master Key (derived from the user’s password).</li></ul><p><strong>Ticket Granting Service (TGS) or Service Ticket (ST)</strong>: When a user wishes to access a network resource, such as a file server, they request an ST from the KDC (specifically, the Ticket Granting Server). The ST is also an encrypted token that allows a user to access a specific resource.</p><ul><li><strong>Contents of the ST</strong>: The ST contains information about the user, the resource server, a timestamp, and the Session Key encrypted with the resource server’s secret key.</li></ul><h4>What is PAC (Privilege Attribute Certificate)?</h4><p>The PAC, which stands for Privilege Attribute Certificate, is a crucial component of TGT (Ticket Granting Ticket) used to store additional information about the user’s privileges. The PAC contains information about the user’s group memberships and certain other security attributes.</p><p><strong>PAC Validation</strong>: PAC validation is a process in which the information within the PAC is verified for legitimacy before granting access.</p><h4>Kerberos Authentication Flow</h4><p>Kerberos authentication utilizes a system of tokens called “tickets” and, simultaneously, employs cryptography to safeguard packets and prevent them from being read or tampered with.</p><p>The Kerberos authentication process initiates when a user wishes to access a resource or service on the network. A Kerberos authentication flow is considered complete when a user successfully acquires a Ticket Granting Service (TGS) or Service Ticket (ST), which enables them to authenticate themselves to the service and make use of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11BzsrOZEixodHc_4gOGsQ.png" /><figcaption>Kerberos Authentication Flow Diagram</figcaption></figure><p>Below, I will detail what happens at each step of the Kerberos authentication flow:</p><ol><li><strong>KRB_AS_REQ: Request TGT from Authentication Service (AS)</strong><br>The client requests a TGT (Ticket Granting Ticket) by presenting the UPN (User Principal Name) of the user and a timestamp to the AS (Authentication Service). Additionally, the client sends “<strong>Pre-Authentication</strong>” information, which includes data like a timestamp and a nonce (a one-time-used number) encrypted with the client’s key.</li><li><strong>KRB_AS_REP: TGT Received from Authentication Service</strong><br>Here, the KDC (specifically, the Authentication Service) checks whether the UPN from the user’s request is in its database. Then, it uses the hashed password of the user to decrypt and verify the pre-authentication.<br>It’s crucial that the client and KDC clocks are synchronized for the timestamp to be valid and within acceptable tolerance. If the pre-authentication verification is successful, and the timestamp is valid, authentication is successfully completed.<br>At this point, the KDC (specifically, the Authentication Service) issues a TGT (Ticket Granting Ticket). Within this TGT, the TGS Session Key (Ticket Granting Server Session Key) is stored. This TGS Session Key will be used in the subsequent steps to encrypt and decrypt communication with the TGS (Ticket Granting Server).<br>The TGT is first encrypted with the KDC Master Key and then encrypted a second time with the User Master Key. Finally, it’s sent to the client as part of the Kerberos Authorization Service Response (<strong>KRB_AS_REP</strong>).</li><li><strong>KRB_TGS_REQ: Present TGT and TGS request</strong><br>The client presents the TGT to the KDC (specifically, the Ticket Granting Server) through a request that contains the SPN (Service Principal Name) of the service it wants to access. The request is encrypted using the TGS Session Key obtained earlier.</li><li><strong>KRB_TGS_REP: Receive TGS from KDC</strong><br>The KDC (specifically, the Ticket Granting Server) attempts to validate the TGT. If successful, it proceeds to create a TGS that contains information about the requester, such as their SID and the groups they belong to. This Service Ticket is encrypted with the service’s password hash.<br>The service ticket and the session key are encrypted again using the TGS Session Key and sent to the client.</li><li><strong>KRB_AP_REQ: Present TGS to Application Server for Authorization</strong><br>The client sends the TGS it received from the KDC to the Application Server, along with an authenticator message that is encrypted with the service session key.</li><li><strong>KRB_AP_REP: Grant Client Access to the Service</strong><br>The Application Server receives the message and decrypts it using the service session key.<br>The Application Server extracts the Privilege Attribute Certificate (PAC) from the Service Ticket to verify its contents with the Domain Controller (PAC Validation).<br><em>Ticket and PAC validation only occur when the TGT is older than 20 minutes.</em></li></ol><h3>Kerberos Authentication Attacks</h3><p>Below, we will delve into some of the numerous vulnerabilities and attacks that exist within the Kerberos authentication system, now that we have gained an understanding of how it operates.</p><p>As mentioned earlier, a Kerberos authentication flow consists of 6 steps. Next, we will explain each of the attacks and vulnerabilities, organizing them according to the step in which they occur within the Kerberos authentication process.</p><h4>AS-REP Roast Attack</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1YyyvTqBLGMm_ujLP-63cQ.png" /><figcaption>AS-REP Roast Attack Console Illustration</figcaption></figure><p><strong>Kerberos Authentication Flow Step</strong>: <em>2) KRB_AS_REP: TGT Received from Authentication Service</em></p><p>The attack known as AS-REP Roasting is based on obtaining a Ticket Granting Ticket (TGT) from a user without prior knowledge of their password. This attack is made possible by a special attribute in the domain called <strong>UF_DONT_REQUIRE_PREAUTH</strong>.</p><p><strong>¿How the attribute UF_DONT_REQUIRE_PREAUTH works?</strong></p><p>As mentioned earlier, in a conventional Kerberos authentication process, specifically in the first step (KRB_AS_REQ), the client sends a request for a TGT to the KDC (Authentication Service). Within this request, the User Principal Name (UPN), a timestamp, and Pre-Authentication data are included, which is sent encrypted with the user’s password hash.</p><p>When a user is assigned the UF_DONT_REQUIRE_PREAUTH attribute, it informs the KDC (Authentication Service) that Pre-Authentication is not necessary to request a TGT (Ticket Granting Ticket). This allows a client to request TGTs on behalf of that user without knowing their password.</p><p><strong>Brute-Forcing the TGT</strong></p><p>Previously, we described the composition of a TGT. Now, we will delve even deeper to understand the process of a brute force attack targeted at a TGT.</p><p>As mentioned earlier, in the AS-REP, the Key Distribution Center (KDC) provides us with a TGT, which is encrypted twice:</p><ol><li>The first time, it is encrypted with the KDC Master Key, which is derived from the service account <strong>KRBTGT’s password</strong>.</li><li>The second time, it is re-encrypted using the User Master Key, derived from the user’s password requesting the TGT.</li></ol><p>In the typical case of a legitimate client, the client would decrypt the TGT using their own password to gain access to the TGS Session Key. However, in the scenario of an attacker who does not know the user’s password for which the TGT is requested, the attacker attempts to decrypt the TGT through offline dictionary-based brute force attacks. If the attacker successfully decrypts the TGT, it means they have obtained the user’s password.</p><h4>Golden Ticket Attack</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-iMfG1YD-1e2M6K30e8WOA.png" /><figcaption>Golden Ticket Attack Console Illustration</figcaption></figure><p><strong>Kerberos Authentication Flow Step:</strong> <em>2) KRB_AS_REP: TGT Received from Authentication Service</em></p><p>The attack known as the “Golden Ticket Attack” is based on the generation of a fake TGT (Ticket Granting Ticket), which can be presented to the TGS (Ticket Granting Server) with the purpose of requesting a Service Ticket for any service within the domain, also allowing for the impersonation of any user within the domain.</p><p><strong>How Golden Ticket Attack Works?</strong></p><p>The attack known as the “Golden Ticket Attack” is based on knowledge of the <strong>KRBTGT</strong> service account credentials, which are responsible for managing the Kerberos service. To understand this attack, it is necessary to review the Kerberos flow described earlier.</p><p>When a user requests a TGT (Ticket Granting Ticket) from the Key Distribution Center (KDC), they do so through a request called <strong>KRB_AS_REQ</strong>. The server responds with a <strong>KRB_AS_REP</strong>, which includes the TGT encrypted twice. The first encryption is done with the KDC Master Key, derived from the KRBTGT account’s password. The second encryption is done with the User Master Key, derived from the user who requested the TGT.</p><p>The first encryption protects the entire TGT and ensures that no one can modify it without knowing the KDC Master Key. The second encryption is applied to the already encrypted TGT and ensures security during the transmission of the TGT. An attacker intercepting the communications would need to know the User Master Key to view the TGT.</p><p>When a user decrypts the <strong>KRB_AS_REP</strong>, they gain access to the TGT and the TGS Session Key, which is used to encrypt the connection with the Ticket Granting Server when requesting a Service Ticket.</p><p>When a user sends a <strong>KRB_TGS_REQ </strong>to request a Service Ticket, the TGS attempts to decrypt the TGT using the KDC Master Key. Once decrypted, the TGS can access the Ticket’s information, such as the user to whom the TGT belongs and the groups it belongs to. The TGS verifies the user and issues a Service Ticket for that user.</p><p>Now, an attacker who knows the credentials of the KRBTGT account in the domain can calculate the KDC Master Key and decrypt the TGT. With this information, the attacker can create a fake TGT using a template, specify that it belongs to any domain user, set its lifetime, and encrypt it with the calculated KDC Master Key. By sending this fake TGT in a KRB_TGS_REQ, the Ticket Granting Server will receive it and, since it is encrypted with the KDC Master Key, can decrypt it without any issues and issue a Service Ticket for the user specified in the fake TGT.</p><p>In summary, this allows the attacker to impersonate any domain user on any service within the domain.</p><p><strong>Creating the Fake TGT</strong></p><p>To carry out a Golden Ticket Attack, it is necessary to create a Fake TGT (Ticket Granting Ticket). For this, an attacker must possess the following information:</p><ul><li><strong>The NTLM hash of the krbtgt service account</strong>, which is the Kerberos service account used to encrypt and decrypt TGTs (Ticket Granting Tickets).</li><li><strong>The Domain’s Security Identifier (SID)</strong>, which is a unique identifier for the specific domain in question. The SID is used in the creation of security tokens and is essential for calculating the PAC (Privilege Attribute Certificate) in the fake TGT. The PAC contains information about security groups and user privileges, and its accurate creation requires the domain’s SID.</li></ul><p>With this information in their possession, an attacker can generate a fake TGT that appears to be authentic and valid for accessing resources and systems within the compromised domain’s network. This can result in unauthorized access to sensitive systems and privilege escalation.</p><h4>Kerberoasting Attack</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*adGnjGus0s1bpksMZ1Ijbw.png" /><figcaption>Kerberoasting Attack Console Illustration</figcaption></figure><p><strong>Discovery of the Kerberoasting Attack</strong></p><p>The Kerberoasting attack was discovered by <strong>Tim Medin</strong> at DerbyCon 2014. This type of attack occurs when an attacker has already gained access to a company’s network and has initiated the necessary reconnaissance process to carry out lateral movement.</p><p><strong>Kerberos Authentication Flow</strong></p><p>As we have previously seen when explaining the Kerberos authentication flow, to request a Service Ticket, it is necessary to have a pre-existing Ticket Granting Ticket (TGT) and a Ticket Granting Service (TGS) Session Key. Once these elements are in place, a Service Ticket can be requested from the Ticket Granting Server (TGS) using a <strong>KRB_TGS_REQ</strong>. In this request, both the TGT and the Service Principal Name (SPN) of the desired service are sent. All of this communication is encrypted with the TGS Session Key. The Ticket Granting Server validates the information and returns a Service Ticket encrypted with the NTLM hash of the service account, all within the <strong>KRB_TGS_REP</strong> response.</p><p><strong>The Kerberoasting Attack</strong></p><p>The Kerberoasting attack is based on the attacker’s ability to request a Service Ticket for a specific SPN, which<strong> they have the potential to crack</strong>.</p><p><strong>What’s a Kerberoastable User?</strong></p><p>It is important to highlight that Kerberoasting attacks primarily target Service Principal Names (SPNs) that have been modified by users, meaning those that are not automatically generated by the system. This is because host-based SPNs are protected by randomly generated 128-character passwords that change every 30 days, making them virtually impervious to brute force attacks.</p><p>On the other hand, SPNs created by domain users tend to have passwords that follow more predictable and human patterns, making them more susceptible to cracking techniques. Additionally, these passwords are rarely updated, making them a prime target for this type of attack. These accounts are known as <strong>“Kerberoastable Users.”</strong></p><h4>Silver Ticket Attack</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sue-hCSxxivqcMt7HEOWhw.png" /><figcaption>Silver Ticket Attack Console Illustration</figcaption></figure><p><strong>Kerberos Authentication Flow Step:</strong> <em>6) KRB_AP_REP: Grant Client Access to the Service</em></p><p>The attack known as the Silver Ticket Attack focuses on the creation of a fake Ticket Granting Service (TGS) or Service Ticket. This action would allow an attacker to connect to a specific service by impersonating any user within the relevant domain.</p><p><strong>How Silver Ticket Attack Works?</strong></p><p>The Silver Ticket Attack primarily works because an attacker possesses the credentials of a service account.</p><p>To thoroughly grasp the functioning of the Silver Ticket Attack, it is essential to refer to the previous explanation we provided about the Kerberos authentication flow.</p><p>As we mentioned earlier, specifically in a <strong>KRB_TGS_REP</strong> response, a Service Ticket is generated and encrypted with the service key. This key is essentially a derivative of the password of the account running the service.</p><p>Subsequently, this Service Ticket is presented to the Application Server, representing the relevant service, through a <strong>KRB_AP_REQ</strong> request. The Application Server decrypts the Service Ticket, and if it successfully decrypts it and the Service Ticket is properly structured, it grants access to the service.</p><p>When an attacker gains access to the credentials of a user running a service, they can create a forged Service Ticket on behalf of any system user. Next, they encrypt this Service Ticket with the NTLM hash of the service key and directly present it to the Application Server using a <strong>KRB_AP_REQ</strong> request.</p><p><strong>Creating the Fake Service Ticket</strong></p><p>To create a fake Service Ticket, it is essential to have the following information:</p><ol><li><strong>SPN (Service Principal Name)</strong>: Specifically for the service you want to access.</li><li><strong>Domain SID</strong></li><li><strong>Service Account’s NTLM Hash</strong></li><li><strong>Service Ticket User:</strong> This would be the user you intend to gain access to the service with.</li></ol><p>Creating a Service Ticket manually can be a highly complex process. One tool that can be used to streamline the Service Ticket creation process is the “ticketer.py” tool from the Impacket suite.</p><h4>MS14–068 (Kerberos Checksum Vulnerability)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZ7Th5_ruIMJpX1bZ9hmFQ.png" /><figcaption>MS14–068 Console Illustration</figcaption></figure><p><strong>Introduction to MS14–068</strong></p><p>MS14–068, also known as the Kerberos Checksum Vulnerability, was discovered as a critical threat to the Kerberos authentication system in November 2014. Its impact was so significant that it gained considerable notoriety within the cybersecurity community.</p><p>This vulnerability allowed any domain user to perform privilege escalation surprisingly easily. To grasp the seriousness of the situation, it is important to highlight that this vulnerability granted any domain user the ability to join any group of their choice within the domain, including those with administrator privileges.</p><p><strong>Delving into the cause of MS14–068</strong></p><p>If we wish to delve into the root of this vulnerability, we must step back and analyze the Kerberos authentication flow, focusing specifically on an essential component of this process: the Ticket Granting Ticket (TGT).</p><p>To comprehend this vulnerability, we must understand how a TGT is structured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*UrFT-Tey4T4yX7b7D4driA.png" /><figcaption>Ticket Granting Ticket Simplified Visual Representation</figcaption></figure><p>The TGT (Ticket Granting Ticket) includes a structure known as the Privilege Attribute Certificate (PAC), which stores information related to the user to whom the TGT belongs, such as their RID (Relative Identifier) and the groups they are associated with. In order to safeguard the integrity of the PAC, the KDC (Key Distribution Center) encrypts it using the KDC Master Key, a key that is known only to the KDC.</p><p>This vulnerability originates from a flaw in how the KDC validates the PAC signature. This error in PAC signature validation allowed attackers to create their own PACs, which were subsequently validated by the KDC. Since the PAC contains information about the user’s group memberships, it was possible to abuse this vulnerability to add the attacker to a group they didn’t belong to, potentially granting administrative privileges.</p><p>The underlying problem is of a rather straightforward nature.</p><p>Within the Microsoft Privilege Attribute Certificate (MS-PAC) Data Structure, there is a specific structure known as <strong>PAC_SIGNATURE_DATA</strong>.</p><p>The <strong>PAC_SIGNATURE_DATA</strong> structure is defined in the code as follows:</p><pre> typedef struct _PAC_SIGNATURE_DATA {<br>     ULONG SignatureType;<br>     UCHAR Signature[ANYSIZE_ARRAY];<br> } PAC_SIGNATURE_DATA, *PPAC_SIGNATURE_DATA;</pre><p>As we can observe, this structure requires the specification of an argument called <strong>SignatureType</strong>. According to Microsoft, this field can take one of these three values:</p><ul><li>KERB_CHECKSUM_HMAC_MD5</li><li>HMAC_SHA1_96_AES128</li><li>HMAC_SHA1_96_AES256</li></ul><p>The issue here lies in vulnerable Key Distribution Centers (KDC) affected by the MS14–068 vulnerability, where proper verification is not performed to ensure that the value of the <strong>SignatureType </strong>field falls within these expected three values. Instead, any type of checksum implemented in the low-level cryptographic library is accepted. To grasp the gravity of this situation, it’s important to highlight that it would be possible to forge a Privilege Attribute Certificate (PAC) without possessing any knowledge of a secret key, simply by using the CRC32 checksum function.</p><p>Below, we present a simplified visual representation of a TGS-REQ message designed to exploit the MS14–068 vulnerability. In this case, a valid TGT is included, albeit notably lacking the expected PAC (Privilege Attribute Certificate) information. Instead, the attacker has inserted a tampered PAC into the “enc-authorization-data” field. This counterfeit PAC falsely claims that the user in question is a member of various high-privileged groups, including the domain administrators group. Furthermore, it’s crucial to emphasize that this PAC has been ‘signed’ using a simple MD5 technique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ElX86xqtfABNj_KRwS3eCQ.png" /><figcaption><em>TGS-REQ containing a forged PAC to exploit MS14–068</em></figcaption></figure><h3>Final Conclusions</h3><p>In conclusion, we’ve reached the end of this article, and I want to thank you for dedicating your time to explore in detail the fascinating world of Kerberos authentication and the related authentication flow attacks. I understand that theory can sometimes be overwhelming, especially in a field as practice-oriented as Pentesting.</p><p>However, as we close this chapter, I want to remind you that the beauty of understanding concepts at a high level of detail lies in the ability it gives you to maneuver more effectively in real-world situations. You now possess a solid knowledge of the fundamentals of Kerberos authentication and the types of attacks that can be carried out.</p><p>I sincerely hope that this reading has been enriching, and that you take pride in the deep understanding you’ve gained. As you continue your journey in the world of Pentesting, remember that knowledge is a powerful tool. Use it wisely and responsibly in your future challenges.</p><p>Thank you once again for your time and dedication. Until the next adventure in the vast world of cybersecurity!</p><p>I’ll leave my social media links here so you can follow me if you’d like.</p><p>It was a pleasure writing this for you and contributing to the community.</p><p><strong>Linkedin: </strong><a href="https://www.linkedin.com/in/luciano-pereira-3a2825248/">Click Here!</a></p><p><strong>Twitter: </strong><a href="https://twitter.com/ZaikoARG">Click Here!</a></p><p><strong>GitHub: </strong><a href="https://github.com/ZaikoARG">Click Here!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c05a6efa52b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Buffer Overflow]]></title>
            <link>https://medium.com/@zaikoarg/understanding-the-buffer-overflow-3951396903dc?source=rss-a25e297d14c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3951396903dc</guid>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[buffer-overflow]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[pentesting]]></category>
            <dc:creator><![CDATA[Luciano Pereira]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 21:15:44 GMT</pubDate>
            <atom:updated>2023-09-08T13:22:34.585Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A bit different introduction to Buffer Overflow</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_UkYs98r3n5RQiwJipESA.png" /></figure><h3>Introduction</h3><p>Hello everyone, my name is Luciano Pereira, known in the internet world by the name ZaikoARG.</p><p>In this article, I want to invite you to think about Buffer Overflow in a different way, beyond the usual methodology and step-by-step instructions that we were taught. The goal of this article is to truly understand what happens when we exploit a Buffer Overflow, to understand the reasoning behind each step, and not just follow the classic methodology taught in the OSCP Buffer Overflow course.</p><p><strong>Warning:</strong> This is not a write-up, nor will I teach you how to exploit a Buffer Overflow step-by-step. Instead, I will provide you with the resources to understand each step of the attack, and by understanding what you are doing, you will be more flexible in solving problems during the attack.</p><h3>Basic Concepts</h3><p>To truly understand what a Buffer Overflow is, we first need to know some <strong>basic concepts</strong> of <strong>how operating systems work</strong>.</p><p>When we run programs on our computers, they create <strong>processes</strong> that run in the background. Essentially, everything we see in the operating system is made up of a set of processes executing in the background, performing different tasks.</p><p>These running processes need a place to temporarily store the data they require to function. This is where the RAM comes into play. Each process is assigned a space in <strong>virtual memory</strong>, where it can temporarily store the data required for its execution. We should imagine virtual memory as a set of slots, where each slot stores data and has a specific address to locate it within the memory. This address is known as a <strong>Memory Address</strong>.</p><p>In this unique virtual memory space for each process, we can find the famous Registers, such as EIP and ESP, and the stack.</p><p>Let’s take a look at a couple of definitions:</p><p><strong>Buffer:</strong> a reserved memory space for a process where data is temporarily stored while it’s in use.</p><p><strong>Stack:</strong> A data structure used to temporarily store data in a process, such as local variables and function arguments. It is essential to note that the stack does not have a fixed position, but rather moves throughout memory, moving downwards as data is added and upwards as data is removed. It is also important to understand that the flow of data in the stack is from bottom to top, much like a stack of books, so data is removed from the top of the stack downwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*1dmuNPlXgK9_uFpmHJdTkA.jpeg" /><figcaption>Stack Data Flow Representation</figcaption></figure><p><strong>ESP (Extended Stack Pointer):</strong> Works like a pointer, storing the memory address where the last element added to the stack is located. This is the highest position in memory assigned to the stack for that process.</p><p><strong>EIP (Extended Instruction Pointer):</strong> Works like a pointer, storing the memory address where the next instruction to execute is located.</p><p><em>It is important to emphasize that these registers are specific to a 32-bit architecture and in 64-bit architecture, they have different names</em></p><h3>What is a Buffer Overflow?</h3><p>Now that we understand the basic and necessary concepts, we can jump directly to <strong>what a Buffer Overflow is</strong>:</p><p>A <strong>Buffer Overflow</strong> is a vulnerability that occurs due to a flaw in the source code of an application or service, usually in <strong>some input of data</strong> provided by the client, <strong>where more data is entered than the buffer has reserved</strong>, and this data starts overwriting important parts of memory, such as the EIP register.</p><h4>How dangerous is a Buffer Overflow?</h4><p>A Buffer Overflow <strong>can cause</strong>, in the first instance, a <strong>DoS (Denial of Service)</strong>. And if the system doesn’t have adequate protections and the attacker knows how to exploit a Buffer Overflow, this can lead to an Arbitrary Code Execution.</p><h3>Exploiting a Stack-Based Buffer Overflow</h3><p>Although the Buffer Overflow has different techniques such as Ret2libc or ROP, we are going to focus on the most basic and common one: <strong>Stack-Based Buffer Overflow</strong>.</p><p>The Stack-Based technique is the most common and occurs when a buffer overflow causes more data to be written to the stack than it can handle, which can result in overwriting important registers such as the EIP.</p><h4>Understanding the Vulnerability</h4><p>Example of vulnerable code in C:</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;<br><br>void vulnerable(char *input){<br>    char buffer[100];<br>    strcpy(buffer, input);<br>    printf(&quot;Buffer: %s\n&quot;, buffer);<br>}<br><br>int main(){<br>    char input[200];<br>    printf(&quot;Enter an Input: &quot;);<br>    gets(input);<br>    vulnerable(input);<br>    return 0;<br>}</pre><p>What is happening here is that the user’s input is being taken and stored in the variable ‘input’, which has a reserved buffer size of 200 bytes. If an attacker were to enter more than 200 bytes, they would exceed the buffer assigned in memory and the entered data would begin to overwrite the values of other variables on the stack, potentially escalating up to the EIP register depending on the amount of data entered.</p><p>In addition to this, the misuse of input functions such as the gets() function in this case, makes our application vulnerable to BOF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swlo5liGmCrpLHTghE8tFw.png" /><figcaption>Buffer Overflow Representation</figcaption></figure><h4>OS Security Measures</h4><p>Although, as we mentioned earlier, the Stack-Based Buffer Overflow arises from an error on the programmer’s part, there are system-level measures that can help prevent an attacker from exploiting the vulnerability.</p><p>These include:</p><ul><li><strong>NX (No eXecute):</strong> is a security technology that works by marking parts of memory as “Non-Executable” to prevent execution of shellcode in the heap or stack.</li><li><strong>DEP (Data Execution Prevention):</strong> is practically the same as NX, only this is the name adopted in Microsoft operating systems.</li><li><strong>ASLR (Address Space Layout Randomization):</strong> is a security technique that works by randomly changing the location of objects in memory, causing memory addresses to change with each execution.</li></ul><p>Although these techniques can make it difficult to exploit a buffer overflow, <strong>it does not mean they completely mitigate it</strong>. An attacker with enough knowledge can find a way to bypass these security parameters.</p><p><em>It is important to note that in this article, as it is an introduction to buffer overflow, we will not be explaining how to bypass these protection measures.</em></p><h4>What we need to exploit a Stack-Based Buffer Overflow?</h4><p>Now that we understand how the vulnerability works and the security measures, let’s review the steps we need to follow to exploit a Stack-Based Buffer Overflow.</p><ol><li><strong>Recognize the vulnerability:</strong> First, we need to identify where the vulnerability exists in the service. Typically, a large number of “A” characters are used to verify if the program is corrupted. If this happens, it means we have successfully overflowed the buffer.</li><li><strong>Determine the required amount of data to overwrite the registers:</strong> Once we have recognized the vulnerability, we need to debug the service using a debugging tool like GDB, x64dbg, or Immunity Debugger to determine how much data is needed to overwrite the EIP registers. We can do this easily using patterns created with the Metasploit <strong>pattern_create</strong> tool. These patterns are specifically designed to filter and recognize how many characters are needed to reach a specific part of the pattern.</li><li><strong>Identify the BadChars:</strong> After determining the required amount of data, we need to identify the characters that we cannot use in the exploit, known as “bad chars.” This is because some characters can alter the behavior of the exploit or shellcode, preventing proper execution.</li><li><strong>Build the shellcode:</strong> Once we have identified the “bad chars,” it is necessary to build the shellcode that will be executed on the target machine. The shellcode should be designed to perform the specific task desired, such as opening a remote shell or providing access to a compromised system.</li><li><strong>Send the final payload:</strong> Finally, we need to send the final payload to the vulnerable service. This can be done using tools like Netcat or Metasploit, among others. If everything has been done correctly, the exploit will execute on the target machine and allow the attacker to take control of the system or perform other malicious actions.</li></ol><h3>Some explanations of the why behind each thing in Stack-Based Buffer Overflow.</h3><p>Well, now that we’ve covered all the basic aspects of Stack-Based Buffer Overflow, let’s take a look at some more specific things to keep in mind. These are some explanations for all those people who just follow instructions without understanding why things are done a certain way. Here, I’m going to explain why we do certain things when we execute the classic Stack-Based Buffer Overflow, so you can understand when to use them and when not to.</p><h4>Why JMP ESP?</h4><p>When it comes to exploiting a vulnerability in a program, a commonly used technique is to redirect the EIP (Instruction Pointer) register to a memory address that contains a <strong>JMP ESP</strong> (Jump to ESP) instruction. But why do we do this?</p><p>To understand this, let’s remember that the <strong>ESP (Stack Pointer)</strong> register stores the memory address of the last element in the stack, that is, the position where the most recently saved data is located. By using the <strong>JMP ESP</strong> instruction, we are jumping to the memory address stored in the ESP register, which is the position in the stack where our shellcode is located and we want to execute.</p><p>In summary, by redirecting the <strong>EIP</strong> register to a memory address that contains a <strong>JMP ESP</strong> instruction, we are taking advantage of the fact that this register stores the position where our shellcode is located in the stack, and in this way, we manage to execute our malicious code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_MT5iy14gUeSMwVQBUCyw.png" /><figcaption>JMP ESP Flow Explaination</figcaption></figure><h4>Why not exclude “default” badchars?</h4><p>We start with something important for the “step-by-step guys”.</p><p>It’s common to be taught that you must recognize the accepted badchars in the program and always exclude the \x00. However, this is not always necessary, and I will explain why.</p><p>Each binary can have or not have badchars. While the null byte is a byte that “usually” is not interpreted and can corrupt your exploit, this is not true in all cases. Whether to exclude it or not will depend on the program you are trying to exploit and its code.</p><p>It is essential to always identify the badchars and exclude them only if necessary for the success of your exploit. Do not blindly follow tutorial instructions without fully understanding the context and possible scenarios.</p><h4>NOPs Use</h4><p>Well, here’s the most controversial thing lately among the “step-by-step guys”.</p><p>Why do we use <strong>NOPs (No Operation)</strong>? Many probably don’t know the answer, others will tell you it’s good practice to use them, others will say it’s to give the program time to execute all your shellcode, among other things. Almost none of these answers are entirely correct.</p><p>While NOPs are generally used to give the program time to execute the instructions in the shellcode, <strong>they are not always necessary</strong>. I see thousands of writeups where absurd amounts of NOPs are used when they are not necessary. Now I’m going to explain exactly why NOPs are used and when they shouldn’t be used.</p><p><strong>So, why should NOPs be used?</strong> The problem lies in shellcodes created with msfvenom. If we take a low-level look at these, they have instructions that store data on the stack, i.e., the place where our shellcode is located. After all, the shellcode is destroying itself. So when we use NOPs, the shellcode will write to the space where our NOPs are located and not the shellcode itself.</p><p>It’s important to note that NOPs are not the only solution. An alternative is to use a shellcode specifically designed for x86, such as the one shown in this article: <a href="https://www.abatchy.com/2017/05/tcp-bind-shell-in-assembly-null"><strong>https://www.abatchy.com/2017/05/tcp-bind-shell-in-assembly-null</strong></a></p><p>In summary, NOPs are a good practice in some cases, but they are not always necessary. The important thing is to understand why they are used and evaluate if they are necessary in each particular situation.</p><h4>Use of Stack Offset instead NOPs</h4><p>Although NOPs are a good practice when necessary, there is another alternative that I prefer to use: stack displacement.</p><p><strong>What is Stack Offset?</strong></p><p>It is the process of moving the position of the shellcode in memory when writing an exploit or shellcode. In simple terms, stack displacement is the number of bytes that need to be added or subtracted to the return address or EIP so that it points to the desired position of the shellcode in memory.</p><p><strong>Why is it a good alternative to using NOPs?</strong></p><p>Although both methods serve their purpose, stack displacement can be more efficient in cases where space in the stack is limited. Instead of adding multiple NOP instructions, we can simply load a single instruction that displaces the stack by a certain number of bytes.</p><p><strong>How is Stack Offset performed?</strong></p><p>To perform a stack displacement, an instruction such as sub esp, 0x10 can be used, which displaces the stack by 16 bytes (0x10 in hexadecimal). It is important to remember that the instruction must be entered in hexadecimal format in the shellcode. However, other instructions can be used depending on the architecture and context in which you are working.</p><h3>Conclusion and Farewell</h3><p>Well, after such an explanation, I think anyone who has read this can now go and check out the write-ups on how to do a Stack-Based Buffer Overflow. The lesson I want to leave to all newcomers in this field is that this field is not linear or methodical; you don’t have to follow the same steps for all cases. We have to understand that environments can vary, complications can arise, and if we don’t really understand what we’re doing, we won’t be able to overcome the obstacles that come our way. Be curious and ask yourself why everything works, I assure you that those are the best professionals.</p><p>I’ll leave my social media here so you can follow me if you like.</p><p>It was a pleasure to write this for you and help the community by contributing my grain of sand.</p><p><strong>Linkedin: </strong><a href="https://www.linkedin.com/in/luciano-pereira-3a2825248/">Click Here!</a></p><p><strong>Twitter: </strong><a href="https://twitter.com/ZaikoARG">Click Here!</a></p><p><strong>GitHub: </strong><a href="https://github.com/ZaikoARG">Click Here!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3951396903dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>