In recent years, phishing attacks have become increasingly sophisticated and are now being conducted through various messaging platforms such as Telegram. Telegram is a popular messaging app that allows users to send messages, photos, videos, and other files over the internet. It also provides APIs that allow developers to create custom bots and applications. Unfortunately, these same APIs can be used by malicious actors to exfiltrate credentials successfully phished from attacks.

ThreatSpike has detected numerous incidents of this nature and two real-world examples will be discussed in this blog. We will additionally delve into the specifics of the Telegram API, identify indicators of compromise and examine defensive measures that can be taken.

The Telegram API

In 2015, Telegram introduced its Bot API, which allowed developers to create bots to interact with Telegram users. The Bot API was designed to be user-friendly and gained popularity quickly. With the Bot API, developers were able to create chatbots, news bots, weather bots and more. However, users soon discovered the malicious possibilities the API could be used for.

The process for malicious actors to set up bots and carry out harmful activities involves only three steps:

  • Actors first refer to Telegram's official instructions for creating bots, which entails messaging the BotFather on Telegram (figure 1).
Figure 1: Telegram bot creation via the BotFather
  • Next, they use the Telegram bot's API exclusive endpoint (https://api.telegram.org/bot<bot_id>:<auth_token>/getUpdates) to acquire the chat ID, which is an identifier for chat sessions between the bot and the user/s. The chat ID now serves as the channel for transmitting the stolen credentials.
  • Finally, the actors integrate the Telegram bot token (used for authorising the bot and sending requests to the API) and chat ID into the malevolent scripts, programs, or files employed in their phishing campaigns to exfiltrate stolen credentials.

Now that we have outlined how to create a Telegram bot, let’s explore how it has been utilised in real-world attacks.

"Monthly Payable.htm"

While Telegram bots have been used for exfiltration before, they were not as commonly used as they are today. We attribute this significant increase to the current trend of using HTML attachments as a delivery mechanism, the simplicity of setting up a Telegram bot and the lack of bespoke detections for this transfer method.

The attachment usually contains the authentication token and location of a Telegram bot, either hardcoded and obfuscated, or linked to a domain that hosts a phishing kit with the bot's ID encoded in its resources.

Figures 2-6 presents one example of a malicious HTM file delivered through an email that contains a fake Microsoft Sharepoint login page.

Figure 2: Phishing email Figure 3: "Monthly Payable.htm" in browser

Inspection of the HTM file shows it has been base64 encoded (figure 4) to hide the bot's authentication token, chat ID and other content. The actor’s bot token and chat ID is used to authenticate with the Telegram bot's API and deliver the stolen information to the appropriate location.

The atob() function used is a pre-built method in JavaScript that decodes base64 encoded strings. The function name is derived from the phrase "ASCII to Binary", and it is the opposite of the btoa() function, which encodes a string to a base64 format.

Base64 encoding is a way of representing binary data as ASCII text. This is important when transmitting data over a medium that only accepts ASCII characters, such as email or HTTP requests. Actors also use base64 as an obfuscation method against static analysis.

Figure 4: Inspected “Monthly Payable.htm”

Figure 5 shows a request captured by ThreatSpike that contains the bot’s authorisation token as well as the chat ID the actor was using to receive the credentials (sensitive details have been removed).

Figure 5: Telegram API GET request for submitted credentials Figure 6: The threat actor's view of a successful exfiltration

If you have access to the bot’s authorisation token and chat ID, you can query the malicious bot for further information. Figures 7 and 8 shows some of these methods being used on the real bot that was used in this phishing campaign.

The getChat method enables bots to retrieve details about a particular chat by sending a request that includes the chat's ID. The response from the Telegram API includes a JSON object with information on the chat's type, title, description, participants, administrators, and creators. This method is particularly useful for bots that need specific data about a chat, such as group or channel information, that can then be utilised for actions like updating chat settings or sending messages.

Another method used was getChatAdministrators. The response from the Telegram API retrieves information about all the chat's administrators, including their user IDs, first and last names, and permissions.

Finally, the getMe method enables bots to retrieve information about themselves, such as their username, ID and other attributes. This method is typically one of the first API calls made by a bot when starting up, and it only requires the bot token to function correctly. Bots can use this information to confirm that they are authenticated and authorised to perform actions within the Telegram ecosystem.

Figure 7: Telegram API requests sent to the malicious bot curl -s "https://api.telegram.org/bot<bot_id>:<auth_token>/getChat?chat_id=<chat_id>"

curl -s "https://api.telegram.org/bot<bot_id>:<auth_token>/getChatAdministrators?chat_id=<chat_id>"

curl -s "https://api.telegram.org/bot<bot_id>:<auth_token>/getMe?chat_id=<chat_id>"
Figure 8: Template Telegram API requests from figure 7

Note to the reader: It is important to be aware that the API's getUpdates method can be a powerful tool, but it also poses a security risk. If a malicious actor gains access to a bot's authorisation token and chat ID, they can use getUpdates to eavesdrop on conversations and obtain chat history, as shown in the Python code example in figure 9.

# Replace 'your_bot_api_token' with your bot's API token
bot = TelegramBot('your_bot_api_token')

# Replace you_chat_id with the chat ID you want to retrieve
chat_id = <your_chat_id>

# Replace num_messages with the number of messages you want to retrieve
num_messages = 10

messages = bot.get_messages(chat_id, num_messages)

for message in messages:
    print(message.text)
Figure 9: Printing chat history using the getUpdates method in Python

The use of HTML/HTM files to conceal malicious activities is not a novel technique and continues to be widely used since it makes it challenging for security services to conduct automated analysis. Malicious actors have employed various techniques, such as JavaScript, HTML entities, and custom CSS to evade detection. Utilising Telegram bots is a smart strategy to further accomplish their objectives, mainly because the usage of a bot may not be immediately apparent during initial analysis.

"Fendi Performance Marketing Manager Recruitment Plan.exe"

We now understand that the API acts as a great and simple vector for exfiltrating data, but how else has it been implemented? One recently investigated incident used the API in conjunction with an infostealer payload.

An infostealer is a malicious program that aims to steal confidential or sensitive information from a computer or network. Typically, it disguises itself as a legitimate application, such as an email attachment or a download from the internet. It can capture a variety of data, including login credentials, personal documents, credit card details, and bank account information.

On February 28, 2023, at 10:31, a ZIP file named "New Project Fendii - Development Plan.zip" was downloaded by a user from a phishing campaign. Ten minutes later, a DNS request was detected, resolving the Telegram Bot API. This was followed by a connection being established to Telegram's Bot API servers at 149.154.167.220:443 (api.telegram.org) from an executable named "Fendi Performance Marketing Manager Recruitment Plan.exe". The executable was run from the temporary directory "C:\Users\\AppData\Local\Temp\Rar$EXa4356.37281".

At 10:43, the infostealer read two sensitive browser files, namely:

  • C:\Users\<user>\AppData\Local\Google\Chrome\User Data\Default\Login Data
  • C:\Users\<user>\AppData\Local\Microsoft\Edge\User Data\Default\Login Data

Following this, at 10:45, a substantial amount of data was sent from the executable to api.telegram.org. The data was encrypted by the attacker.

To mitigate the impact of the security incident, the device was then sandboxed to prevent any further unauthorised access to sensitive and personal data. It was observed that the infostealer was still attempting to communicate with the Telegram servers after the host was sandboxed.

Figure 10 reveals that the ZIP file contained two further executable files and other contents. The two executables functioned similarly to "Fendi Performance Marketing Manager Recruitment Plan.exe" from initial analysis. The inclusion of a video advertisement titled "FendiHandinHand Rome - Lazio Region.mp4" and photographs in the ZIP file indicates that the attackers put forth significant efforts in creating a successful phishing campaign. Figure 11 displays a screenshot from the video.

Figure 10: "New Project Fendii - Development Plan.zip" Figure 11: “FendiHandinHand Rome - Lazio Region.mp4”

Further analysis with VirusTotal revealed that the infostealer employs various defense evasion techniques. This includes techniques such as virtualisation/sandbox evasion, medium and long sleeps, memory allocation with a write watch, and DLL side-loading. Due to these techniques, performing dynamic analysis was difficult. This was proved in our own environment as well as a third-party analysis attempt from cuckoo.cert.ee. Despite having knowledge about the malware's process checking techniques, we were unsuccessful in deceiving the executable to believe that it was operating in a compatible environment.

We proceeded to use x64dbg to try and debug "Fendi Performance Marketing Manager Recruitment Plan.exe". We generated a process dump file of the executable using the debugger and employed FLOSS to recognise and extract obscured strings. Over 240,000 strings were extracted and figures 12-14 show a few examples.

Figure 12: Domain controller check Figure 13: Active Directory enumeration Figure 14: Bitlocker enumeration

It was concluded that the extracted strings originated from libraries imported at runtime, given that they were obtained prior to the main process of the infostealer and that the malware would not operate entirely in a virtual environment. The imported libraries found are listed below:

  • KERNEL32.dll
  • ADVAPI32.dll
  • USER32.dll
  • SHELL32.dll
  • api-ms-win-crt-runtime-l1-1-0.dll
  • api-ms-win-crt-stdio-l1-1-0.dll
  • api-ms-win-crt-heap-l1-1-0.dll
  • api-ms-win-crt-string-l1-1-0.dll
  • api-ms-win-crt-convert-l1-1-0.dll
  • api-ms-win-crt-locale-l1-1-0.dll
  • api-ms-win-crt-math-l1-1-0.dll
  • api-ms-win-crt-time-l1-1-0.dll
  • api-ms-win-crt-filesystem-l1-1-0.dll

Additionally, it was discovered that after execution, the executable saved five DLL files in the %temp% folder:

  • clrcompression.dll
  • clrjit.dll
  • coreclr.dll
  • e_sqlite3.dll
  • mscordaccore.dll

These were found to be necessary for the file to run properly. Additionally, .NET is also required for the infostealer to execute.

The VirusTotal and Cuckoo report for "Fendi Performance Marketing Manager Recruitment Plan.exe" can be found here:

In general, the delivered malware was highly advanced and showcased the actors’ considerable expertise and proficiency not only in constructing malicious software but also in their phishing tactics and defense evasion.

Detections and Indicators of Compromise

"Monthly Payable.htm"

How did we capture these threats? Well, our proprietary platform, ThreatSpike Wire, identifies sophisticated security threats by capturing real-time event data through direct monitoring of network traffic, machine activity, and user interactions. This information is then processed by an expert system that automates up to 90% of conventional investigative tasks, allowing for a faster alert to incident turnover.

This first phishing attack using the malicious HTM attachment was identified through the use of multiple indicators as shown in figure 15.

Figure 15: Incident details of malicious HTM attachment

The IOCs are as follows:

  1. Downloaded Phishing File tracked the process, OUTLOOK.EXE, downloading the HTM attachment.
  2. Next, Windows Defender alerted the downloaded attachment and identified it as malicious, but unfortunately, it was not fast enough to remove the file before the user opened it in Google Chrome.
  3. Lastly, the most important indicator was capturing the DNS request and connection to Telegram’s Bot API servers.

To remediate the situation, it is recommended that several steps be taken. Firstly, it is important to change the credentials of the affected user as soon as possible to prevent any further unauthorised access. Additionally, deactivating all active sessions can help to immediately terminate any ongoing unauthorised activity.

"Fendi Performance Marketing Manager Recruitment Plan.exe"

Figure 16 demonstrates the identification of the second phishing attack through the utilisation of various indicators.

Figure 16: Incident details of malicious ZIP

The IOCs are as follows:

  1. Downloaded ZIP Write tracked the process, msedge.exe, downloading the malicious “New Project Fendii - Development Plan.zip”.
  2. Capturing the DNS request and connection to Telegram's Bot API.
  3. Browser File Read tracked the malicious executable (“Fendi Performance Marketing Manager Recruitment Plan.exe”) reading the "Login Data" files from Chrome and Microsoft Edge.

Due to the collective threat score of these indicators, the ThreatSpike Bot automatically placed this device in a sandbox. Securing a compromised machine is critical in preventing further damage to the system and network.

When dealing with security incidents, it is crucial to investigate beyond simply isolating the affected machine. Conducting forensic investigations and thoroughly examining system data, logs, and network traffic is essential in determining the extent of the damage and preventing future incidents. Additionally, blocking the sender's email address and reporting the malicious binaries can help to prevent future attacks. It is also important to promptly delete any associated files to minimise potential damage. By following these remediation steps, the impact of the incident can be mitigated, and future breaches can be prevented.

It is crucial for organisations to also ensure the deployment of email defenses that can prevent the delivery of credential phishing attacks. This entails the development of more advanced behavioral analysis techniques to detect potential threats rather than relying on static indicators. As many credential phishing attacks, such as those that exploit Telegram bots, have dynamic features, traditional methods may not be able to identify them effectively.

Bot on Vacation

In terms of safeguarding users against the exploitation of Telegram, we suggest that businesses establish policies regarding the usage of api.telegram.org.

The absence of discussion on such policies is concerning. We have observed a substantial number of attempts to exfiltrate Telegram credentials since the commencement of 2023, and it is evident that this method is increasingly gaining popularity among malicious actors. This raises doubts about whether companies are even aware of the Telegram associations with phishing attacks. This could be due to the lack of information regarding and or the depth of feedback from investigations.

Now, let's delve into the reasons why companies may be reluctant to block the Telegram API. Some typical business use cases include:

  • Customer support: Companies can use Telegram to communicate with their customers and provide support services. Telegram’s API allows companies to create automated chatbots that can answer common customer queries and provide assistance.
  • Monitoring: Companies have the option to utilise Telegram to send monitoring updates to their employees. For instance, suppose a server executes a script on a regular basis to update a database with fresh stock prices for an e-commerce website. If the script fails, how could developers be notified? A Telegram sendMessage API request can be easily programmed into a success/failure condition to transmit error information and other relevant details directly to an employee's mobile device.

After conducting analysis on extensive corporate networks, we found minimal instances where Telegram bots were used for authentic business or personal use. Although we are uncertain of the extent of usage of Telegram within organisations worldwide, we are aware that there are numerous custom technologies that offer comparable functionality. Therefore, the usage of Telegram within a business should conform to the same security policies that we apply to other messaging platforms and services alike.

To reiterate, the implementation of said policies will depend on the extent of legitimate usage of Telegram bots within an organisation. If an organisation has legitimate usage of Telegram bots, then authorised bot tokens related to that usage should be permitted while other traffic should be obstructed. However, if an organisation has no legitimate usage of Telegram bots, then all traffic to api.telegram.org should be blocked.

Summary

Protecting against Telegram bot credential phishing is crucial to ensure the security of your users and organisation. As we’ve learnt, these sophisticated phishing attacks can bypass traditional defenses and trick users into providing their credentials, allowing attackers to gain unauthorised access to their accounts. This can lead to data theft and further damage to the company. Therefore, it is essential to take necessary precautions, such as security awareness training, enabling two-factor authentication and implementing detections to identify connections to Telegram APIs.