Skip to content

Latest commit

 

History

History
309 lines (239 loc) · 9.8 KB

File metadata and controls

309 lines (239 loc) · 9.8 KB

MtkClient.Library

License .NET Version Platform

A full-featured .NET Framework 4.8 C# port of the popular mtkclient Python tool by B.Kerler.
Flash, dump, exploit, and interact with MediaTek (MTK) devices — all from managed .NET code.


📖 Table of Contents


🔍 What Is This?

MtkClient.Library is a C# class library that brings the full power of mtkclient to the .NET ecosystem. It allows developers to build Windows/Linux/macOS applications that can:

  • Connect to MediaTek devices over USB or Serial
  • Bypass security mechanisms (SLA, DAA, SBC) using well-known exploits
  • Read/write/erase flash partitions
  • Dump memory and device information
  • Upload and execute payloads
  • Enter META mode and read IMEI

The library is a direct port of the Python mtkclient tool, maintaining the same logic while providing a clean C# API surface.


✨ Features

Category Features
🔌 Connection USB (LibUSB) & Serial port support, auto-detection
🔓 Security Bypass Amonet exploit, Kamakiri exploit, auto-detect mode
💾 Flash Operations Read / Write / Erase partitions, Sparse image support
📦 DA Loader Legacy DA, XFlash DA, XmlFlash DA support
🔍 Device Info HW Code, ME ID, SoC ID, BROM log, GPT partition table
🧠 Memory Read/Write/Dump arbitrary memory regions
📡 Payload Engine Upload and execute custom payloads
🔧 META Mode Enter META mode, read IMEI
♻️ Recovery Auto-recovery state machine for connection loss
🪵 Logging Structured logging with levels, packet dumping, crash dumps

🏗 Architecture

MtkClient.Library
├── Api/            ← High-level entry point (MtkApi, MtkIotApi)
├── Auth/           ← SLA key exchange and authentication
├── Config/         ← Device DB, BROM config, USB IDs, MTK config
├── Connection/     ← Port abstraction, USB (LibUSB), Serial
├── DA/             ← Download Agent loader & handlers (Legacy, XFlash, XmlFlash)
├── Exploit/        ← Amonet, Kamakiri, ExploitHandler
├── Flash/          ← FlashEngine with sparse image support
├── Hardware/       ← CQDMA, HwCrypto, SecCfg
├── Logging/        ← MtkLogger with structured output
├── Packet/         ← Packet builder for BROM communication
├── Partitions/     ← GPT, MBR, PMT partition parsers
├── Payload/        ← PayloadEngine for custom payload execution
├── Recovery/       ← RecoveryManager with state machine
├── State/          ← MtkStateManager (DeviceState enum)
├── Utils/          ← CryptUtils, ErrorHandler, LogBase, MtkUtils
├── MtkClass.cs     ← Core Mtk class (main orchestrator)
├── MtkMain.cs      ← High-level operations (dump/flash all, boot, etc.)
├── MtkPreloader.cs ← BROM/Preloader protocol implementation
└── ...

📋 Requirements

  • .NET Framework 4.8 (or .NET 6+ with compatibility shim)
  • Windows: WinUSB driver (install via Zadig), or Serial
  • Linux/macOS: libusb-1.0 installed, user in plugdev group
  • NuGet packages (auto-restored):
    • LibUsbDotNet 3.0.102-alpha
    • BouncyCastle.Cryptography 2.5.1
    • Newtonsoft.Json 13.0.3
    • System.IO.Ports 8.0.0

📦 Installation

Via NuGet (coming soon)

Install-Package MtkClient.Library

From Source

git clone https://github.com/QstDevTeam/MtkClient.Library.git
cd MtkClient.Library
dotnet restore
dotnet build

⚡ Quick Start

using MtkClient.Library;
using MtkClient.Library.Api;

// 1. Create the API instance
using var api = new MtkApi();

// 2. Connect to device (auto-detect USB)
if (!api.Connect())
{
    Console.WriteLine("No device found. Put device in BROM mode (hold Vol-Down while connecting USB).");
    return;
}

// 3. Bypass security and load DA
var result = api.BypassSecurity();
Console.WriteLine($"Exploit: {result.ExploitName}, Success: {result.Success}");

api.StartDa("path/to/your.bin");

// 4. Read a partition
byte[] data = api.ReadPartition("boot");
File.WriteAllBytes("boot.img", data);

// 5. Done
api.Disconnect();

📚 Usage Examples

Dump All Partitions

using var api = new MtkApi();
api.Connect();
api.BypassSecurity();
api.StartDa("loader.bin");

api.DumpAllPartitions("./output/");

Write a Partition from File

api.WritePartitionFromFile("recovery", "recovery.img");

Get Device Information

var info = api.GetFullDeviceInfo();
Console.WriteLine($"HW Code: 0x{info.HwCode:X4}");
Console.WriteLine($"ME ID: {BitConverter.ToString(info.MeId)}");
Console.WriteLine($"SoC ID: {BitConverter.ToString(info.SocId)}");

Read Raw Memory

byte[] mem = api.ReadMemory(0x00000000, 0x1000);
File.WriteAllBytes("mem_dump.bin", mem);

Listen to State Changes

api.OnStateChanged += (sender, e) =>
{
    Console.WriteLine($"State: {e.OldState}{e.NewState} ({e.Reason})");
};
api.Connect();

Custom Logging Level

var config = new MtkConfig(LogLevel.Debug);
using var api = new MtkApi(config);
api.EnablePacketDumping("packets.log");

📖 API Reference

MtkApi — Main Entry Point

Method Description
Connect(port?, token?) Connect to MTK device via USB or Serial
Disconnect() Safely disconnect
BypassSecurity(exploit?) Run exploit (auto / amonet / kamakiri)
StartDa(path?) Load and start Download Agent
ReadPartition(name) Read partition, returns byte[]
WritePartition(name, data) Write raw bytes to partition
WritePartitionFromFile(name, path) Write partition from .img file
ErasePartition(name) Erase a partition
GetPartitionList() Get list of partition names
DumpAllPartitions(dir) Dump every partition to directory
FlashAllPartitions(dir) Flash all .img files from directory
ReadMemory(addr, len) Read raw memory
WriteMemory(addr, value) Write 32-bit value to address
GetFullDeviceInfo() Returns BromInfo with HW/SW/ME/SoC IDs
ReadImei(slot?) Read IMEI (requires META mode)
PowerDown() Power off device
ColdReset() Reset device

📱 Supported Devices

This library supports the same MediaTek chipsets as the original mtkclient:

  • MT6261, MT6572, MT6580, MT6582, MT6589, MT6592
  • MT6595, MT6735, MT6737, MT6739, MT6750, MT6753
  • MT6755, MT6757, MT6761, MT6763, MT6765, MT6768
  • MT6771, MT6779, MT6785, MT6795, MT6797, MT6853
  • MT6873, MT6877, MT6883, MT6889, MT6893, MT8163
  • MT8167, MT8173, MT8183, MT8695, and many more

Note: Device support depends on the DA loader binary you provide. The library itself does not include DA binaries.


📁 Project Structure

MtkClient.Library/
├── Api/
│   ├── MtkApi.cs          ← Main API class
│   └── MtkIotApi.cs       ← IoT-specific API
├── Auth/
│   ├── Sla.cs             ← SLA authentication
│   └── SlaKeys.cs         ← SLA key database
├── Config/
│   ├── BromConfig.cs      ← BROM configuration per chip
│   ├── DeviceDb.cs        ← Device database
│   ├── MtkConfig.cs       ← Global configuration
│   ├── PathConfig.cs      ← Path configuration
│   └── UsbIds.cs          ← USB VID/PID table
├── Connection/
│   ├── DeviceHandler.cs   ← Device lifecycle management
│   ├── Port.cs            ← Port abstraction (USB+Serial)
│   ├── SerialLib.cs       ← Serial port implementation
│   ├── UsbLib.cs          ← LibUSB implementation
│   └── UsbScsi.cs         ← USB SCSI commands
├── DA/
│   ├── Legacy/            ← Legacy DA handler
│   ├── XFlash/            ← XFlash DA handler
│   ├── XmlFlash/          ← XmlFlash DA handler
│   ├── DaConfig.cs
│   ├── DaHandler.cs
│   ├── DaLoader.cs
│   └── IDAHandler.cs
├── Exploit/
│   ├── Amonet.cs          ← Amonet exploit
│   ├── ExploitHandler.cs  ← Auto-detect & run exploits
│   └── Kamakiri.cs        ← Kamakiri exploit
├── Flash/
│   └── FlashEngine.cs     ← Flash R/W with sparse image support
├── ...
├── MtkClass.cs            ← Core Mtk orchestrator
├── MtkMain.cs             ← High-level operations
├── MtkPreloader.cs        ← BROM protocol
└── MtkClient.Library.csproj

⚠️ Disclaimer

This library is intended for educational, research, and legitimate device recovery purposes only. Using it on devices you do not own, or in ways that violate terms of service, may be illegal. Use responsibly.


🙏 Credits & License

This project is a derivative work of mtkclient and is distributed under the same GPLv3 license.