The most popular stock and third-party Android ROM – used by 170 million people – contains a dangerous since-patched remote code execution hole that could hand attackers total control of handsets.

The flaw, found by IBM X-Force researcher David Kaplan (@depletionmode), now of Microsoft, exists in MIUI (pronounced Me, You, I) and allows attackers with privileged network access – say over cafe Wi-Fi – to fully compromise devices.

IBM researchers with the X-Force security team said in an advisory provided to The Register ahead of publication that the remote code execution flaw exists in the analytics package, which can be abused to provide malicious ROM updates.

"The vulnerability we discovered allows for a man-in-the-middle attacker to execute arbitrary code as the highly privileged Android ‘system’ user," IBM researchers say.

"The update transaction is performed over an insecure transport link [and] as such, a man-in-the-middle attack.

"As there is no cryptographic verification of the update code itself, com.xiaomi.analytics will replace itself with the attacker-supplied version via Android's DexClassLoader mechanism."

The security wonks say the flaw allows attackers to inject a JSON response to force an update by replacing the URL and md5 hash with those of a malicious Android application package containing malicious code.

Bugged update mechanisms that fail to verify downloaded updates are increasingly common flaws, the researchers say.

A further flaw was found in stock ROM app com.cleanmaster.miui which sported a code injection flaw attackers could exploit to gain system-level privileges.

The ROM ships on devices manufactured by developer Xiaomi and is also ported and maintained for more than 340 different handsets including Nexus, Samsung, and HTC.

CyanogenMod, the most popular strictly third-party ROM, has about 50 million users and supports about 200 devices.

Affected users should upgrade to version 7.2, released as an over-the-air update.

X-Force researchers thanked Xiaomi for what they say was a rapid response with the vulnerability confirmed, triaged, and a patch date issued within days of first disclosure.

They say developers should "transact only code-related data over a verified, secure transport such as TLS with certificate pinning" and ensure code is "cryptographically signed and properly verified" before execution.

More specifically, they say Android developers should sit down and discuss banning apps from executing unsigned code via DexClassLoader, dynamic library injection or any other method, a feat that would eliminate such flaws. ®