626 lines
34 KiB
PHP
626 lines
34 KiB
PHP
<?php
|
|
|
|
namespace JumPHP\Ide\Tests;
|
|
|
|
use JumPHP\Ide\Async\Deferred;
|
|
use JumPHP\Ide\Audit\AiReviewer;
|
|
use JumPHP\Ide\Audit\AuditCommands;
|
|
use JumPHP\Ide\Audit\Auditor;
|
|
use JumPHP\Ide\Audit\AuditStore;
|
|
use JumPHP\Ide\Audit\Checks\ConfigCheck;
|
|
use JumPHP\Ide\Audit\Checks\DependencyCheck;
|
|
use JumPHP\Ide\Audit\Checks\DockerCheck;
|
|
use JumPHP\Ide\Audit\Checks\HeadersCheck;
|
|
use JumPHP\Ide\Audit\Checks\PhpCodeCheck;
|
|
use JumPHP\Ide\Audit\Checks\SecretsCheck;
|
|
use JumPHP\Ide\Audit\Checks\TwigCheck;
|
|
use JumPHP\Ide\Audit\LocalGuard;
|
|
use JumPHP\Ide\Audit\Patches;
|
|
use JumPHP\Ide\Audit\Probes;
|
|
use JumPHP\Ide\Audit\ProjectFiles;
|
|
use JumPHP\Ide\Audit\Redactor;
|
|
use JumPHP\Ide\HttpClient\HttpSender;
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
/** A web server that answers from a table (url path => [status, headers, body]) and remembers what it was sent. */
|
|
final class FakeLocalSite implements HttpSender
|
|
{
|
|
/** @var list<array<string, mixed>> */
|
|
public array $sent = [];
|
|
|
|
/** @var list<array{0: Deferred, 1: array<string, mixed>}> answers waiting for poll() (a real network: frames later) */
|
|
private array $pending = [];
|
|
|
|
/** @param \Closure(array): array $answer */
|
|
public function __construct(private \Closure $answer, private bool $later = false)
|
|
{
|
|
}
|
|
|
|
public function send(array $request): Deferred
|
|
{
|
|
$this->sent[] = $request;
|
|
[$status, $headers, $body] = ($this->answer)($request);
|
|
$answer = ['status' => $status, 'headers' => $headers, 'body' => $body, 'time' => 3];
|
|
if (!$this->later) {
|
|
return Deferred::resolved($answer);
|
|
}
|
|
$d = new Deferred();
|
|
$this->pending[] = [$d, $answer];
|
|
return $d;
|
|
}
|
|
|
|
public function poll(): void
|
|
{
|
|
$pending = $this->pending;
|
|
$this->pending = [];
|
|
foreach ($pending as [$d, $answer]) {
|
|
$d->resolve($answer);
|
|
}
|
|
}
|
|
|
|
public function busy(): bool
|
|
{
|
|
return $this->pending !== [];
|
|
}
|
|
}
|
|
|
|
final class SecurityAuditTest extends TestCase
|
|
{
|
|
private string $dir;
|
|
|
|
protected function setUp(): void
|
|
{
|
|
$this->dir = sys_get_temp_dir() . '/jumphp-audit-' . bin2hex(random_bytes(4));
|
|
mkdir($this->dir);
|
|
}
|
|
|
|
protected function tearDown(): void
|
|
{
|
|
exec('rm -rf ' . escapeshellarg($this->dir));
|
|
}
|
|
|
|
private function put(string $file, string $text): void
|
|
{
|
|
$path = "$this->dir/$file";
|
|
if (!is_dir(dirname($path))) {
|
|
mkdir(dirname($path), 0777, true);
|
|
}
|
|
file_put_contents($path, $text);
|
|
}
|
|
|
|
/** @return list<array<string, mixed>> */
|
|
private function php(string $code, array $accessControl = [], ?PhpCodeCheck &$check = null): array
|
|
{
|
|
$check = new PhpCodeCheck(new ProjectFiles($this->dir), $accessControl);
|
|
return $check->file('src/Controller/X.php', $code);
|
|
}
|
|
|
|
private static function rules(array $findings): array
|
|
{
|
|
return array_map(fn ($f) => $f['rule'] . ':' . $f['severity'], $findings);
|
|
}
|
|
|
|
private const CONTROLLER = <<<'PHP'
|
|
<?php
|
|
namespace App\Controller;
|
|
|
|
use App\Entity\Invoice;
|
|
use Doctrine\DBAL\Connection;
|
|
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
|
use Symfony\Component\HttpFoundation\Request;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
use Symfony\Component\HttpFoundation\RedirectResponse;
|
|
use Symfony\Component\Routing\Attribute\Route;
|
|
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
|
|
|
#[Route('/shop')]
|
|
final class ShopController extends AbstractController
|
|
{
|
|
#[Route('/search', name: 'search')]
|
|
public function search(Request $request, Connection $db): Response
|
|
{
|
|
$q = $request->query->get('q', '');
|
|
$sql = "SELECT * FROM product WHERE name LIKE '%" . $q . "%'";
|
|
$rows = $db->fetchAllAssociative($sql);
|
|
$safe = $db->fetchAllAssociative('SELECT * FROM product WHERE name LIKE :q', ['q' => "%$q%"]);
|
|
return $this->render('shop/search.html.twig', ['q' => $q, 'rows' => $rows]);
|
|
}
|
|
|
|
#[Route('/sort')]
|
|
public function sort(Request $request, \Doctrine\ORM\EntityManagerInterface $em): Response
|
|
{
|
|
$order = $request->get('order');
|
|
$em->createQuery("SELECT p FROM App\Entity\Product p ORDER BY p.$order");
|
|
$em->createQuery('SELECT p FROM App\Entity\Product p WHERE p.id = :id')->setParameter('id', $request->query->getInt('id'));
|
|
return new Response('Sorted by ' . $order);
|
|
}
|
|
|
|
#[Route('/go')]
|
|
public function go(Request $request): RedirectResponse
|
|
{
|
|
return $this->redirect($request->query->get('next'));
|
|
}
|
|
|
|
#[Route('/home')]
|
|
public function home(): RedirectResponse
|
|
{
|
|
return $this->redirect($this->generateUrl('search'));
|
|
}
|
|
|
|
#[Route('/ping')]
|
|
public function ping(Request $request): Response
|
|
{
|
|
$host = $request->query->get('host');
|
|
$out = shell_exec('ping -c 1 ' . $host);
|
|
$ok = shell_exec('ping -c 1 ' . escapeshellarg($host));
|
|
$cart = unserialize($request->cookies->get('cart'));
|
|
$fine = unserialize($request->cookies->get('cart'), ['allowed_classes' => false]);
|
|
return new Response('ok');
|
|
}
|
|
|
|
#[Route('/invoice/{id}')]
|
|
public function invoice(Invoice $invoice): Response
|
|
{
|
|
return $this->render('shop/invoice.html.twig', ['invoice' => $invoice]);
|
|
}
|
|
|
|
#[Route('/mine/{id}')]
|
|
#[IsGranted('VIEW', 'invoice')]
|
|
public function mine(Invoice $invoice): Response
|
|
{
|
|
return $this->render('shop/invoice.html.twig', ['invoice' => $invoice]);
|
|
}
|
|
|
|
#[Route('/profile/save', methods: ['POST'])]
|
|
public function save(Request $request): Response
|
|
{
|
|
$user = new \App\Entity\User();
|
|
foreach ($request->request->all() as $field => $value) {
|
|
$user->{'set' . ucfirst($field)}($value);
|
|
}
|
|
return new Response('saved');
|
|
}
|
|
|
|
#[Route('/upload', methods: ['POST'])]
|
|
public function upload(Request $request): Response
|
|
{
|
|
$file = $request->files->get('doc');
|
|
$file->move('uploads', $file->getClientOriginalName());
|
|
return new Response('ok');
|
|
}
|
|
}
|
|
PHP;
|
|
|
|
public function testRequestDataFollowedToSqlCommandsRedirectsAndUnserialize(): void
|
|
{
|
|
$f = $this->php(self::CONTROLLER, [], $check);
|
|
$byRule = [];
|
|
foreach ($f as $x) {
|
|
$byRule[$x['rule']][] = $x;
|
|
}
|
|
// SQL: the concatenated LIKE (critical, the query parameter q) and the DQL interpolated ORDER BY; the bound ones are fine
|
|
self::assertCount(2, $byRule['sql_injection']);
|
|
self::assertSame('critical', $byRule['sql_injection'][0]['severity']);
|
|
self::assertSame(['kind' => 'query', 'name' => 'q'], $byRule['sql_injection'][0]['input']);
|
|
self::assertSame('/shop/search', $byRule['sql_injection'][0]['route']['path']);
|
|
self::assertStringContainsString('fetchAllAssociative($sql)', $byRule['sql_injection'][0]['snippet']);
|
|
self::assertStringContainsString('ORDER BY p.$order', $byRule['sql_injection'][1]['snippet']);
|
|
// one shell command (the escaped one is fine), one unserialize (the one with allowed_classes is fine)
|
|
self::assertCount(1, $byRule['command_injection']);
|
|
self::assertSame('critical', $byRule['command_injection'][0]['severity']);
|
|
self::assertCount(1, $byRule['unserialize_input']);
|
|
self::assertSame('cookie', $byRule['unserialize_input'][0]['input']['kind']);
|
|
// the redirect to ?next (not the generated URL), the response written with the request's text
|
|
self::assertCount(1, $byRule['open_redirect']);
|
|
self::assertSame('next', $byRule['open_redirect'][0]['input']['name']);
|
|
self::assertCount(1, $byRule['xss_response']);
|
|
// the template rendered with q, for the Twig check
|
|
self::assertSame('q', $check->templates['shop/search.html.twig']['q']['input']['name']);
|
|
}
|
|
|
|
public function testIdorMassAssignmentAndUploadsAreFound(): void
|
|
{
|
|
$f = $this->php(self::CONTROLLER);
|
|
$idor = array_values(array_filter($f, fn ($x) => $x['rule'] === 'idor_candidate'));
|
|
self::assertCount(1, $idor, 'the route with #[IsGranted] is not a candidate');
|
|
self::assertSame('/shop/invoice/{id}', $idor[0]['route']['path']);
|
|
self::assertSame('medium', $idor[0]['severity']);
|
|
// behind access_control: still a candidate (another user's invoice), lower
|
|
$covered = array_values(array_filter($this->php(self::CONTROLLER, [['path' => '^/shop/invoice', 'roles' => ['ROLE_USER']]]), fn ($x) => $x['rule'] === 'idor_candidate'));
|
|
self::assertSame('low', $covered[0]['severity']);
|
|
self::assertSame(['mass_assignment'], array_values(array_unique(array_column(array_filter($f, fn ($x) => $x['rule'] === 'mass_assignment'), 'rule'))));
|
|
$upload = array_values(array_filter($f, fn ($x) => $x['rule'] === 'unrestricted_upload'));
|
|
self::assertCount(1, $upload);
|
|
self::assertTrue($upload[0]['clientName']);
|
|
// with a MIME check, no finding
|
|
$checked = str_replace("\$file->move('uploads'", "if (!in_array(\$file->getMimeType(), ['application/pdf'], true)) { throw new \\Exception(); }\n \$file->move('uploads'", self::CONTROLLER);
|
|
self::assertSame([], array_values(array_filter($this->php($checked), fn ($x) => $x['rule'] === 'unrestricted_upload')));
|
|
}
|
|
|
|
public function testRoutesUnderAdminWithoutAnyProtectionAreAccessControlGaps(): void
|
|
{
|
|
$code = <<<'PHP'
|
|
<?php
|
|
namespace App\Controller;
|
|
use Symfony\Component\Routing\Attribute\Route;
|
|
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
|
class AdminController {
|
|
#[Route('/admin/users')] public function users() {}
|
|
#[Route('/admin/stats')] #[IsGranted('ROLE_ADMIN')] public function stats() {}
|
|
#[Route('/about')] public function about() {}
|
|
#[Route('/api/orders')] public function orders() { $this->denyAccessUnlessGranted('ROLE_USER'); }
|
|
}
|
|
PHP;
|
|
$gaps = array_values(array_filter($this->php($code), fn ($x) => $x['rule'] === 'access_control_gap'));
|
|
self::assertSame(['/admin/users'], array_map(fn ($x) => $x['route']['path'], $gaps));
|
|
self::assertSame([], array_values(array_filter($this->php($code, [['path' => '^/admin', 'roles' => ['ROLE_ADMIN']]]), fn ($x) => $x['rule'] === 'access_control_gap')));
|
|
// PUBLIC_ACCESS protects nothing
|
|
self::assertCount(1, array_filter($this->php($code, [['path' => '^/admin', 'roles' => ['PUBLIC_ACCESS']]]), fn ($x) => $x['rule'] === 'access_control_gap'));
|
|
}
|
|
|
|
public function testCleanCodeGivesNoFinding(): void
|
|
{
|
|
$code = <<<'PHP'
|
|
<?php
|
|
namespace App\Controller;
|
|
use Symfony\Component\HttpFoundation\Request;
|
|
use Symfony\Component\Routing\Attribute\Route;
|
|
class CleanController {
|
|
#[Route('/list')]
|
|
public function list(Request $request, $repo, $conn) {
|
|
$page = $request->query->getInt('page', 1);
|
|
$conn->executeQuery('SELECT * FROM t LIMIT 10 OFFSET ' . (($page - 1) * 10));
|
|
$conn->executeQuery('SELECT * FROM t WHERE id = ?', [$request->query->get('id')]);
|
|
$repo->createQueryBuilder('t')->where('t.name = :n')->setParameter('n', $request->query->get('n'));
|
|
return $this->render('list.html.twig', ['items' => $repo->findAll()]);
|
|
}
|
|
}
|
|
PHP;
|
|
self::assertSame([], self::rules($this->php($code)));
|
|
}
|
|
|
|
public function testTwigRawOnRequestDataIsAProvableXssAndGetsItsFix(): void
|
|
{
|
|
$this->put('templates/shop/search.html.twig', "<h1>Results for {{ q|raw }}</h1>\n{{ '<br>'|raw }}\n{{ form_widget(form)|raw }}\n{{ page.body|raw }}\n{% autoescape false %}{{ x }}{% endautoescape %}\n");
|
|
$templates = ['shop/search.html.twig' => ['q' => ['input' => ['kind' => 'query', 'name' => 'q'], 'route' => ['path' => '/shop/search', 'methods' => ['GET']], 'file' => 'src/Controller/ShopController.php', 'line' => 20]]];
|
|
$f = (new TwigCheck(new ProjectFiles($this->dir), $templates))->run();
|
|
self::assertSame(['xss_raw:high', 'xss_raw:medium', 'xss_autoescape_off:medium'], self::rules($f));
|
|
self::assertSame(['kind' => 'query', 'name' => 'q'], $f[0]['input']);
|
|
self::assertSame(['file' => 'templates/shop/search.html.twig', 'search' => '{{ q|raw }}', 'replace' => '{{ q }}', 'source' => 'rule'], $f[0]['patch']);
|
|
}
|
|
|
|
public function testSymfonyConfigurationChecks(): void
|
|
{
|
|
$this->put('config/packages/security.yaml', <<<'YAML'
|
|
security:
|
|
firewalls:
|
|
dev:
|
|
pattern: ^/(_profiler|_wdt|css|images|js)/
|
|
security: false
|
|
admin:
|
|
pattern: ^/admin
|
|
security: false
|
|
access_control:
|
|
- { path: ^/account, roles: ROLE_USER }
|
|
YAML);
|
|
$this->put('config/packages/framework.yaml', "framework:\n csrf_protection: false\n trusted_proxies: '0.0.0.0/0'\n");
|
|
$this->put('config/packages/nelmio_cors.yaml', "nelmio_cors:\n defaults:\n allow_origin: ['*']\n allow_credentials: true\n");
|
|
$this->put('.env', "APP_ENV=dev\nAPP_SECRET=\n");
|
|
$this->put('.env.prod', "APP_DEBUG=1\nAPP_SECRET=changeme\n");
|
|
$check = new ConfigCheck(new ProjectFiles($this->dir));
|
|
$f = $check->run();
|
|
$rules = self::rules($f);
|
|
sort($rules);
|
|
self::assertSame(['app_secret_weak:medium', 'cors_wildcard:high', 'csrf_disabled_global:medium', 'debug_in_prod:high', 'firewall_unsecured:high', 'trusted_proxies_all:medium'], $rules);
|
|
self::assertSame([['path' => '^/account', 'roles' => ['ROLE_USER']]], $check->accessControl);
|
|
$secret = array_values(array_filter($f, fn ($x) => $x['rule'] === 'app_secret_weak'))[0];
|
|
self::assertStringNotContainsString('changeme', $secret['snippet']);
|
|
// the one-line fixes
|
|
$debug = Auditor::autoPatch($this->dir, array_values(array_filter($f, fn ($x) => $x['rule'] === 'debug_in_prod'))[0]);
|
|
self::assertSame('APP_DEBUG=0', $debug['patch']['replace']);
|
|
}
|
|
|
|
public function testSecretsInTrackedFilesAreFoundAndNeverShown(): void
|
|
{
|
|
$this->put('.env', "APP_SECRET=4f8a9c2e7b1d3f6a5c8e9b2d4f7a1c3e\nDATABASE_URL=postgresql://app:!ChangeMe!@db/app\n");
|
|
$this->put('.env.local', "MAILER_PASSWORD=x\n");
|
|
$this->put('config/services.yaml', "parameters:\n aws_key: AKIAABCDEFGHIJKLMNOP\n stripe_api_key: Xk29sLq8Zm3Np7Rt5Vw2Yb6\n admin_password: '%env(ADMIN_PASSWORD)%'\n");
|
|
$this->put('config/jwt/private.pem', "-----BEGIN RSA PRIVATE KEY-----\nMIIabc\n-----END RSA PRIVATE KEY-----\n");
|
|
$this->put('config/jwt/public.pem', "-----BEGIN PUBLIC KEY-----\nMIIabc\n-----END PUBLIC KEY-----\n");
|
|
$tracked = ['.env', '.env.local', 'config/services.yaml', 'config/jwt/private.pem', 'config/jwt/public.pem'];
|
|
$f = (new SecretsCheck(new ProjectFiles($this->dir), $tracked))->run();
|
|
$rules = self::rules($f);
|
|
sort($rules);
|
|
self::assertSame(['env_local_committed:high', 'private_key_committed:critical', 'secret_committed:critical', 'secret_committed:high'], $rules);
|
|
$all = json_encode($f);
|
|
self::assertStringNotContainsString('AKIAABCDEFGHIJKLMNOP', $all);
|
|
self::assertStringNotContainsString('Xk29sLq8Zm3Np7Rt5Vw2Yb6', $all);
|
|
// not tracked by git: nothing
|
|
self::assertSame([], (new SecretsCheck(new ProjectFiles($this->dir), ['.env']))->run());
|
|
}
|
|
|
|
public function testDockerChecks(): void
|
|
{
|
|
$compose = <<<'YAML'
|
|
services:
|
|
app:
|
|
image: php
|
|
privileged: true
|
|
volumes: ["/var/run/docker.sock:/var/run/docker.sock"]
|
|
user: root
|
|
database:
|
|
image: postgres:16-alpine
|
|
ports:
|
|
- "5432"
|
|
cache:
|
|
image: redis:7
|
|
ports:
|
|
- "127.0.0.1:6379:6379"
|
|
YAML;
|
|
$this->put('compose.yaml', $compose);
|
|
$this->put('Dockerfile', "FROM php:8.4-fpm\nRUN echo hi\n");
|
|
$f = (new DockerCheck(new ProjectFiles($this->dir)))->run();
|
|
$rules = self::rules($f);
|
|
sort($rules);
|
|
self::assertSame(['docker_db_port_exposed:medium', 'docker_latest_tag:low', 'docker_privileged:high', 'docker_root_user:low', 'docker_root_user:low', 'docker_socket_mounted:high'], $rules);
|
|
$port = Auditor::autoPatch($this->dir, array_values(array_filter($f, fn ($x) => $x['rule'] === 'docker_db_port_exposed'))[0]);
|
|
self::assertSame(' - "127.0.0.1::5432"', $port['patch']['replace']);
|
|
self::assertFalse(DockerCheck::publicPort('127.0.0.1:5432:5432'));
|
|
self::assertTrue(DockerCheck::publicPort('0.0.0.0:5432:5432'));
|
|
}
|
|
|
|
public function testComposerAndNpmAuditAnswersBecomeFindings(): void
|
|
{
|
|
$composer = "Warning: something\n" . json_encode(['advisories' => ['symfony/http-kernel' => [['advisoryId' => 'PKSA-1', 'packageName' => 'symfony/http-kernel', 'affectedVersions' => '>=6.0,<6.4.1',
|
|
'title' => 'Request smuggling', 'cve' => 'CVE-2099-0001', 'link' => 'https://example.test/a', 'severity' => 'medium']]], 'abandoned' => []]);
|
|
$f = DependencyCheck::composer($composer, "{\n \"packages\": [\n {\n \"name\": \"symfony/http-kernel\",\n");
|
|
self::assertSame(['dependency_vulnerable:medium'], self::rules($f));
|
|
self::assertSame(4, $f[0]['line']);
|
|
self::assertSame('CVE-2099-0001', $f[0]['advisory']['cve']);
|
|
$npm = json_encode(['vulnerabilities' => ['lodash' => ['name' => 'lodash', 'severity' => 'moderate', 'via' => [['title' => 'Prototype pollution', 'url' => 'https://example.test/b']], 'range' => '<4.17.21', 'fixAvailable' => true]]]);
|
|
self::assertSame(['dependency_vulnerable:medium'], self::rules(DependencyCheck::npm($npm)));
|
|
$this->expectException(\UnexpectedValueException::class);
|
|
DependencyCheck::composer('composer: command not found');
|
|
}
|
|
|
|
public function testMissingSecurityHeaders(): void
|
|
{
|
|
$f = HeadersCheck::check('http://localhost:8000', [['Content-Type', 'text/html'], ['X-Content-Type-Options', 'nosniff'], ['X-Powered-By', 'PHP/8.4.1'],
|
|
['Content-Security-Policy', "default-src 'self'; frame-ancestors 'none'"]]);
|
|
self::assertSame(['referrer-policy', 'x-powered-by'], array_column($f, 'header'));
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------- local-only guard
|
|
|
|
public function testTheGuardOnlyLetsTheLocalSiteThrough(): void
|
|
{
|
|
$dns = ['localhost' => ['127.0.0.1'], 'shop.localhost' => ['127.0.0.1'], 'evil.localhost' => ['93.184.216.34'], 'app' => ['172.18.0.3'], 'db' => ['8.8.8.8'],
|
|
'127.0.0.1.nip.io' => ['127.0.0.1'], 'mixed.localhost' => ['127.0.0.1', '10.1.2.3']];
|
|
$guard = new LocalGuard(['app', 'db'], fn (string $h) => $dns[$h] ?? []);
|
|
foreach (['http://localhost:9217/x?a=1', 'https://shop.localhost/', 'http://127.0.0.1:8000', 'http://127.8.9.10/', 'http://[::1]:8080/', 'http://app:8080/'] as $ok) {
|
|
self::assertNotEmpty($guard->check($ok)['ip'], $ok);
|
|
}
|
|
$g = $guard->check('http://localhost:9217/search?q=1');
|
|
self::assertSame('http://127.0.0.1:9217/search?q=1', $g['target'], 'the request goes to the address that was checked');
|
|
self::assertSame('localhost:9217', $g['hostHeader']);
|
|
foreach (['http://127.0.0.1.nip.io/', 'http://example.com/', 'http://10.0.0.5/', 'http://192.168.1.10/', 'http://0.0.0.0/', 'http://2130706433/', 'http://0x7f.1/',
|
|
'http://evil.localhost/', 'http://mixed.localhost/', 'http://db:5432/', 'http://[email protected]/', 'http://user:pw@localhost/', 'ftp://localhost/',
|
|
'http://[::ffff:8.8.8.8]/', 'http://unknown/', 'http://localhost.example.com/'] as $bad) {
|
|
try {
|
|
$guard->check($bad);
|
|
self::fail("$bad was let through");
|
|
} catch (\DomainException) {
|
|
self::assertTrue(true);
|
|
}
|
|
}
|
|
// the real resolver: localhost is this computer
|
|
self::assertTrue(LocalGuard::loopback((new LocalGuard())->check('http://localhost/')['ip']));
|
|
}
|
|
|
|
public function testProbesAreRefusedBeforeAnythingIsSentToAnotherHost(): void
|
|
{
|
|
$site = new FakeLocalSite(fn () => [200, [], 'ok']);
|
|
$probes = new Probes(new LocalGuard([], fn ($h) => $h === 'localhost' ? ['127.0.0.1'] : ['93.184.216.34']), $site);
|
|
$error = null;
|
|
$probes->run(['kind' => 'xss', 'marker' => 'x', 'steps' => [['label' => 'a', 'url' => 'http://localhost/a'], ['label' => 'b', 'url' => 'https://example.com/b']]])
|
|
->then(null, function (\Throwable $e) use (&$error) {
|
|
$error = $e;
|
|
});
|
|
self::assertInstanceOf(\DomainException::class, $error);
|
|
self::assertSame([], $site->sent, 'nothing sent, not even the local step');
|
|
}
|
|
|
|
public function testExploitProofsShowTheFlawThenItsFix(): void
|
|
{
|
|
$vulnerable = true;
|
|
$site = new FakeLocalSite(function (array $r) use (&$vulnerable) {
|
|
$q = [];
|
|
parse_str((string)parse_url($r['url'], PHP_URL_QUERY), $q);
|
|
$path = (string)parse_url($r['url'], PHP_URL_PATH);
|
|
if ($path === '/search') {
|
|
$v = (string)($q['q'] ?? '');
|
|
if (str_contains($v, "'") && $vulnerable) {
|
|
return [500, [], 'An exception occurred while executing a query: SQLSTATE[42000]: Syntax error near "\'"'];
|
|
}
|
|
return [200, [['Content-Type', 'text/html']], '<h1>' . ($vulnerable ? $v : htmlspecialchars($v)) . '</h1>'];
|
|
}
|
|
if ($path === '/go') {
|
|
return [302, [['Location', (string)($q['next'] ?? '/')]], ''];
|
|
}
|
|
if (str_starts_with($path, '/invoice/')) {
|
|
return $vulnerable ? [200, [], 'Invoice'] : [302, [['Location', '/login']], ''];
|
|
}
|
|
return [404, [], ''];
|
|
});
|
|
$probes = new Probes(new LocalGuard([], fn () => ['127.0.0.1']), $site);
|
|
$route = ['path' => '/search', 'methods' => ['GET']];
|
|
$result = function (array $f) use ($probes) {
|
|
$out = null;
|
|
$probes->run(Probes::plan($f, 'http://localhost:9217'))->then(function ($r) use (&$out) {
|
|
$out = $r;
|
|
});
|
|
return $out;
|
|
};
|
|
$sql = ['id' => 'a1', 'rule' => 'sql_injection', 'route' => $route, 'input' => ['kind' => 'query', 'name' => 'q']];
|
|
$xss = ['id' => 'a2', 'rule' => 'xss_raw', 'route' => $route, 'input' => ['kind' => 'query', 'name' => 'q']];
|
|
$redirect = ['id' => 'a3', 'rule' => 'open_redirect', 'route' => ['path' => '/go', 'methods' => ['GET']], 'input' => ['kind' => 'query', 'name' => 'next']];
|
|
$idor = ['id' => 'a4', 'rule' => 'idor_candidate', 'route' => ['path' => '/invoice/{id}', 'methods' => ['GET']], 'input' => ['kind' => 'route', 'name' => 'id']];
|
|
self::assertSame('vulnerable', $result($sql)['verdict']);
|
|
self::assertStringContainsString('SQLSTATE', $result($sql)['evidence']);
|
|
$x = $result($xss);
|
|
self::assertSame('vulnerable', $x['verdict']);
|
|
self::assertStringContainsString('<b data-jumphp-probe=', $x['steps'][0]['excerpt']);
|
|
self::assertSame('vulnerable', $result($redirect)['verdict']);
|
|
self::assertSame('vulnerable', $result($idor)['verdict']);
|
|
// every request: GET, to the checked address, no redirect followed, no cookie
|
|
foreach ($site->sent as $r) {
|
|
self::assertSame('GET', $r['method']);
|
|
self::assertStringStartsWith('http://127.0.0.1:9217/', $r['url']);
|
|
self::assertFalse($r['redirects']);
|
|
self::assertContains(['Host', 'localhost:9217'], $r['headers']);
|
|
}
|
|
$vulnerable = false;
|
|
self::assertSame('not_reproduced', $result($sql)['verdict']);
|
|
self::assertSame('not_reproduced', $result($xss)['verdict']);
|
|
self::assertSame('the tag came back escaped (HTTP 200)', $result($xss)['evidence']);
|
|
self::assertSame('not_reproduced', $result($idor)['verdict']);
|
|
// no safe automatic proof for a shell command or a POST-only route
|
|
self::assertNull(Probes::plan(['id' => 'b', 'rule' => 'command_injection', 'route' => $route, 'input' => ['kind' => 'query', 'name' => 'h']], 'http://localhost'));
|
|
self::assertNull(Probes::plan(['id' => 'b', 'rule' => 'sql_injection', 'route' => ['path' => '/s', 'methods' => ['POST']], 'input' => ['kind' => 'post', 'name' => 'h']], 'http://localhost'));
|
|
}
|
|
|
|
public function testAnswersThatArriveFramesLaterAreJudgedAndTheHeadersAudited(): void
|
|
{
|
|
$site = new FakeLocalSite(fn (array $r) => [200, [['X-Powered-By', 'PHP/8.5.1']], '<p>' . urldecode((string)parse_url($r['url'], PHP_URL_QUERY)) . '</p>'], true);
|
|
$commands = new AuditCommands($this->dir, fn () => Deferred::resolved(['code' => 0, 'stdout' => '', 'stderr' => '']), $site, new LocalGuard([], fn () => ['127.0.0.1']));
|
|
$commands->setSite('http://localhost:9000');
|
|
$state = null;
|
|
$d = $commands->audit(false, true)->then(function ($s) use (&$state) {
|
|
$state = $s;
|
|
});
|
|
for ($i = 0; $i < 5 && !$d->isDone(); $i++) {
|
|
$commands->poll();
|
|
}
|
|
self::assertContains('header_leak', array_column($state['audit']['findings'], 'rule'));
|
|
$result = null;
|
|
$probes = new Probes(new LocalGuard([], fn () => ['127.0.0.1']), $site);
|
|
$d = $probes->run(Probes::plan(['id' => 'z', 'rule' => 'xss_raw', 'route' => ['path' => '/s', 'methods' => ['GET']], 'input' => ['kind' => 'query', 'name' => 'q']], 'http://localhost'))
|
|
->then(function ($r) use (&$result) {
|
|
$result = $r;
|
|
});
|
|
for ($i = 0; $i < 5 && !$d->isDone(); $i++) {
|
|
$site->poll();
|
|
}
|
|
self::assertSame('vulnerable', $result['verdict']);
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------- storage, patches, AI
|
|
|
|
public function testTheStoreNeverHoldsASecretValue(): void
|
|
{
|
|
$store = new AuditStore($this->dir);
|
|
$store->saveAudit(['id' => '20261116-120000', 'at' => 'now', 'findings' => [
|
|
['id' => 'x', 'rule' => 'secret_committed', 'snippet' => 'STRIPE_API_KEY=sk_live_abcdefghijklmnop1234', 'note' => 'DATABASE_URL=mysql://root:hunter2hunter2@db/app'],
|
|
['id' => 'y', 'rule' => 'sql_injection', 'snippet' => '$db->query("SELECT * FROM u WHERE token = \'$token\'")'],
|
|
], 'counts' => []]);
|
|
$store->setStatus('x', 'accepted', 'rotated, api_key: Zq81mXk2LpW9vT4rN7sB was the old one');
|
|
$text = '';
|
|
foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator("$this->dir/.jumphp/security", \FilesystemIterator::SKIP_DOTS)) as $file) {
|
|
$text .= file_get_contents((string)$file);
|
|
}
|
|
foreach (['sk_live_abcdefghijklmnop1234', 'hunter2hunter2', 'Zq81mXk2LpW9vT4rN7sB'] as $secret) {
|
|
self::assertStringNotContainsString($secret, $text);
|
|
}
|
|
self::assertStringContainsString('$token', $text, 'code that names a variable is kept');
|
|
self::assertSame('accepted', $store->state()['statuses']['x']['status']);
|
|
self::assertSame(1, count($store->history()));
|
|
$this->expectException(\InvalidArgumentException::class);
|
|
$store->setStatus('x', 'whatever');
|
|
}
|
|
|
|
public function testAPatchIsAppliedNearItsFindingThenTheRecheckSeesItFixed(): void
|
|
{
|
|
$this->put('templates/a.html.twig', "{{ q|raw }}\n<p>x</p>\n{{ q|raw }}\n");
|
|
$change = Patches::change($this->dir, ['file' => 'templates/a.html.twig', 'line' => 3, 'patch' => ['search' => '{{ q|raw }}', 'replace' => '{{ q }}']]);
|
|
self::assertSame("{{ q|raw }}\n<p>x</p>\n{{ q }}\n", $change['after']);
|
|
self::assertSame("--- a/x\n+++ b/x\n@@ -1,4 +1,4 @@\n {{ q|raw }}\n <p>x</p>\n-{{ q|raw }}\n+{{ q }}\n \n", Patches::unified($change['before'], $change['after'], 'x'));
|
|
|
|
$commands = new AuditCommands($this->dir, fn () => Deferred::resolved(['code' => 0, 'stdout' => '', 'stderr' => '']), new FakeLocalSite(fn () => [200, [], '']),
|
|
new LocalGuard([], fn () => ['127.0.0.1']));
|
|
$state = null;
|
|
$commands->audit(false, false)->then(function ($s) use (&$state) {
|
|
$state = $s;
|
|
});
|
|
$raw = array_values(array_filter($state['audit']['findings'], fn ($f) => $f['rule'] === 'xss_raw'));
|
|
self::assertCount(2, $raw);
|
|
$p = $commands->patch($raw[1]['id']);
|
|
self::assertStringContainsString("-{{ q|raw }}\n+{{ q }}", $p['diff']);
|
|
$r = $commands->apply($p['changes'], $raw[1]['id']);
|
|
self::assertTrue($r['isFixed']);
|
|
self::assertCount(1, array_filter($r['audit']['findings'], fn ($f) => $f['rule'] === 'xss_raw' && $f['status'] === 'open'));
|
|
self::assertSame('fixed', (new AuditStore($this->dir))->state()['statuses'][$raw[1]['id']]['status']);
|
|
}
|
|
|
|
public function testTheAiReviewsInSmallBatchesWithSecretsMaskedAndItsPatchesChecked(): void
|
|
{
|
|
$this->put('src/A.php', "<?php\n\$q = \$_GET['q'];\n\$db->query(\"SELECT * FROM t WHERE a = '\$q'\");\n\$password = 'Zq81mXk2LpW9vT4rN7sB';\n");
|
|
$findings = [];
|
|
foreach (range(1, 14) as $i) {
|
|
$findings[] = ['id' => "f$i", 'rule' => 'sql_injection', 'severity' => 'critical', 'owasp' => 'A03', 'file' => $i <= 13 ? 'src/A.php' : "src/B$i.php", 'line' => 3, 'snippet' => 'x'];
|
|
}
|
|
$batches = AiReviewer::batches($findings, ['src/C.php']);
|
|
self::assertSame([12], array_map(fn ($b) => count($b['src/A.php'] ?? []), [$batches[0]]));
|
|
self::assertLessThanOrEqual(AiReviewer::FILES_PER_BATCH, max(array_map('count', $batches)));
|
|
self::assertContains('src/C.php', array_merge(...array_map('array_keys', $batches)), 'a chosen file without finding is sent too');
|
|
|
|
$prompts = [];
|
|
$answers = ['not json at all', json_encode(['reviews' => [
|
|
['id' => 'f1', 'verdict' => 'confirmed', 'severity' => 'critical', 'explanation' => 'q goes into SQL', 'fix' => 'bind it',
|
|
'patch' => ['search' => "\$db->query(\"SELECT * FROM t WHERE a = '\$q'\");", 'replace' => "\$db->prepare('SELECT * FROM t WHERE a = ?')->execute([\$q]);"]],
|
|
['id' => 'f2', 'verdict' => 'false_positive', 'explanation' => 'same', 'patch' => ['search' => 'text that is not there', 'replace' => 'x']],
|
|
['id' => 'zzz', 'verdict' => 'confirmed'],
|
|
], 'new' => [['file' => 'src/A.php', 'line' => 4, 'title' => 'Hard-coded password', 'severity' => 'high', 'owasp' => 'A07', 'explanation' => 'e', 'fix' => 'f'],
|
|
['file' => '/etc/passwd', 'line' => 1, 'title' => 'outside']]])];
|
|
$run = function (array $command) use (&$prompts, &$answers) {
|
|
$prompts[] = $command[2];
|
|
return Deferred::resolved(['code' => 0, 'stdout' => (string)json_encode(['result' => array_shift($answers)]), 'stderr' => '']);
|
|
};
|
|
$out = null;
|
|
(new AiReviewer($run, $this->dir))->review(array_slice($findings, 0, 2), [], ['provider' => 'opencode-like-claude', 'language' => 'fr'])
|
|
->then(function ($r) use (&$out) {
|
|
$out = $r;
|
|
}, function ($e) use (&$out) {
|
|
$out = $e;
|
|
});
|
|
self::assertInstanceOf(\RuntimeException::class, $out, 'an unknown provider is refused');
|
|
self::assertStringContainsString('unknown AI', $out->getMessage());
|
|
|
|
$run2 = function (array $command) use (&$prompts, &$answers) {
|
|
$prompts[] = $command[2];
|
|
return Deferred::resolved(['code' => 0, 'stdout' => (string)array_shift($answers), 'stderr' => '']);
|
|
};
|
|
(new AiReviewer($run2, $this->dir))->review(array_slice($findings, 0, 2), [], ['provider' => 'opencode', 'language' => 'fr'])->then(function ($r) use (&$out) {
|
|
$out = $r;
|
|
});
|
|
self::assertCount(2, $prompts, 'asked again once after an answer without JSON');
|
|
self::assertStringContainsString('"fr"', $prompts[0]);
|
|
self::assertStringNotContainsString('Zq81mXk2LpW9vT4rN7sB', $prompts[0], 'secrets never reach the AI');
|
|
self::assertSame(['f1', 'f2'], array_keys($out['reviews']));
|
|
self::assertSame('ai', $out['reviews']['f1']['patch']['source']);
|
|
self::assertArrayNotHasKey('patch', $out['reviews']['f2']);
|
|
self::assertTrue($out['reviews']['f2']['patchRejected']);
|
|
self::assertCount(1, $out['new']);
|
|
self::assertSame(['logic_flaw', 'high', 'A07', 'src/A.php', 4], [$out['new'][0]['rule'], $out['new'][0]['severity'], $out['new'][0]['owasp'], $out['new'][0]['file'], $out['new'][0]['line']]);
|
|
}
|
|
|
|
public function testRedactorMasksSecretsButNotPlaceholders(): void
|
|
{
|
|
self::assertSame('APP_SECRET=****', Redactor::mask('APP_SECRET=4f8a9c2e7b1d3f6a5c8e9b2d4f7a1c3e'));
|
|
self::assertSame("ADMIN_PASSWORD='%env(X)%'", Redactor::mask("ADMIN_PASSWORD='%env(X)%'"));
|
|
self::assertSame('DATABASE_URL=mysql://app:****@db/app', Redactor::mask('DATABASE_URL=mysql://app:s3cretValue@db/app'));
|
|
self::assertSame('key ****', Redactor::mask('key AKIAABCDEFGHIJKLMNOP'));
|
|
self::assertTrue(Redactor::looksRandom('Xk29sLq8Zm3Np7Rt5Vw2Yb6'));
|
|
self::assertFalse(Redactor::looksRandom('!ChangeMe!'));
|
|
self::assertFalse(Redactor::looksRandom('my_database_name'));
|
|
}
|
|
}
|