Príklad: náhľad odkazu (bezpečný voči SSRF)
Chat alebo formulár komentárov premení vložené URL na karty náhľadu: titulok, popis, obrázok, názov webu. URL pochádza od používateľa, takže server nesmie sťahovať interné adresy, nesmie na ne nasledovať presmerovanie a musí escapovať všetko, čo o sebe stránka tvrdí. Súvislosti opisuje stránka Bezpečnosť.
Kontrola URL
php
<?php
declare(strict_types=1);
namespace App;
/**
* Decides whether the server may request a URL that came from a user (SSRF protection).
*
* Allows only http and https, resolves the host and rejects loopback, private, link-local and
* reserved addresses. check() returns the address it checked, so the request can be pinned to it
* (CURLOPT_RESOLVE) and a DNS change between the check and the request cannot bypass it.
*/
final readonly class UrlGuard
{
/**
* @param list<string> $trustedHosts "host:port" pairs allowed even on a private address. Empty in production;
* this example needs one for its fixture server on 127.0.0.1.
*/
public function __construct(private array $trustedHosts = []) {}
/**
* @return string the IP address the host resolves to
* @throws BlockedUrlException
*/
public function check(string $url): string
{
$parts = parse_url($url);
$scheme = strtolower($parts['scheme'] ?? '');
if (!in_array($scheme, ['http', 'https'], true)) {
throw new BlockedUrlException("scheme \"{$scheme}\" is not allowed");
}
$host = trim($parts['host'] ?? '', '[]');
if ($host === '') {
throw new BlockedUrlException('the URL has no host');
}
$port = $parts['port'] ?? ($scheme === 'https' ? 443 : 80);
$ip = filter_var($host, FILTER_VALIDATE_IP) !== false ? $host : gethostbyname($host);
if (filter_var($ip, FILTER_VALIDATE_IP) === false) {
throw new BlockedUrlException("cannot resolve {$host}");
}
if (in_array("{$host}:{$port}", $this->trustedHosts, true)) {
return $ip;
}
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
throw new BlockedUrlException("{$host} is a private or reserved address ({$ip})");
}
return $ip;
}
}Testovací server beží na 127.0.0.1, ktorú kontrola blokuje ako každú loopback adresu. run.php cez $trustedHosts dôveruje práve tomuto hostiteľovi a portu; kontrola v produkcii nemá žiadneho.
Náhľad
php
<?php
declare(strict_types=1);
namespace App;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Psr\Http\Message\UriInterface;
use Tomaj\Scraper\Exception\FetchException;
use Tomaj\Scraper\Parser\OgDomParser;
use Tomaj\Scraper\Parser\SchemaParser;
use Tomaj\Scraper\Scraper;
/**
* Builds a link preview card (title, description, image, site name) for a URL a user pasted.
*/
final readonly class LinkPreview
{
public function __construct(private UrlGuard $guard) {}
/**
* @return array{url: string, title: string, description: ?string, image: ?string, site: string}
* @throws BlockedUrlException when the URL or a redirect points somewhere the server must not go
* @throws FetchException when the page cannot be downloaded
*/
public function fetch(string $url): array
{
$ip = $this->guard->check($url);
$host = (string) parse_url($url, PHP_URL_HOST);
$port = parse_url($url, PHP_URL_PORT) ?? (parse_url($url, PHP_URL_SCHEME) === 'https' ? 443 : 80);
$client = new Client([
RequestOptions::CONNECT_TIMEOUT => 2,
RequestOptions::TIMEOUT => 5,
RequestOptions::HEADERS => ['User-Agent' => 'AcmePreview/1.0 (+https://acme.example/bot)'],
// follow at most 2 redirects, and check every target before it is requested
RequestOptions::ALLOW_REDIRECTS => [
'max' => 2,
'protocols' => ['http', 'https'],
'on_redirect' => fn($request, $response, UriInterface $target) => $this->guard->check((string) $target),
],
// connect to the address the guard checked, not to what DNS says a moment later
'curl' => [CURLOPT_RESOLVE => ["{$host}:{$port}:{$ip}"]],
]);
$meta = new Scraper([], $client)->parseUrl($url, [new OgDomParser(), new SchemaParser()]);
$description = $meta->getOgDescription() ?? $meta->getDescription();
if ($description !== null && mb_strlen($description) > 100) {
$description = rtrim(mb_substr($description, 0, 99)) . '…';
}
return [
'url' => $url,
'title' => $meta->getOgTitle() ?? $meta->getTitle() ?? $host,
'description' => $description,
'image' => $this->imageUrl($meta->getOgImage(), $url),
'site' => $meta->getOgSiteName() ?? $host,
];
}
/**
* og:image may be relative; anything but an http(s) URL (javascript:, data:, file:) is dropped.
*/
private function imageUrl(?string $image, string $pageUrl): ?string
{
if ($image === null) {
return null;
}
if (str_starts_with($image, '/') && !str_starts_with($image, '//')) {
$page = parse_url($pageUrl);
$image = $page['scheme'] . '://' . $page['host'] . (isset($page['port']) ? ':' . $page['port'] : '') . $image;
}
$scheme = strtolower((string) parse_url($image, PHP_URL_SCHEME));
return in_array($scheme, ['http', 'https'], true) ? $image : null;
}
/**
* Every value comes from the page author: escape it.
*
* @param array{url: string, title: string, description: ?string, image: ?string, site: string} $card
*/
public static function render(array $card): string
{
$e = static fn(string $value): string => htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
$html = '<a class="card" href="' . $e($card['url']) . '">';
if ($card['image'] !== null) {
$html .= '<img src="' . $e($card['image']) . '" alt="">';
}
$html .= '<strong>' . $e($card['title']) . '</strong>';
if ($card['description'] !== null) {
$html .= '<p>' . $e($card['description']) . '</p>';
}
return $html . '<small>' . $e($card['site']) . '</small></a>';
}
}CURLOPT_RESOLVEprinúti cURL pripojiť sa na IP adresu, ktorú kontrola overila, takže odpoveď DNS, ktorá sa po kontrole zmení (DNS rebinding), požiadavku nepresmeruje.on_redirectspustí kontrolu na každom cieli presmerovania. JejBlockedUrlExceptionnie je výnimka Guzzle, takže juparseUrl()prepustí nezabalenú a volajúci rozlíši „zablokované“ od „nepodarilo sa stiahnuť“.- URL obrázka sa prevedie na absolútnu a zahodí sa, ak nie je
httpanihttps;render()escapuje každú hodnotu.
Stránky
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bryndzové halušky: the recipe | Kitchen Notes</title>
<meta name="description" content="Potato dumplings with sheep cheese and bacon, the Slovak national dish.">
<meta property="og:title" content="Bryndzové halušky">
<meta property="og:site_name" content="Kitchen Notes">
<meta property="og:image" content="/img/halusky.jpg">
</head>
<body></body>
</html>html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Win a prize</title>
<meta property="og:title" content="<script>alert(document.cookie)</script>Free prize">
<meta property="og:description" content="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation.">
<meta property="og:image" content="javascript:alert(1)">
<meta property="og:site_name" content="" onmouseover="alert(1)">
</head>
<body></body>
</html>php
<?php
declare(strict_types=1);
// A redirect to the cloud metadata address: a classic SSRF trick that a URL check alone misses.
if (parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) === '/to-metadata') {
header('Location: http://169.254.169.254/latest/meta-data/', true, 302);
return true;
}
return false;Kód
php
<?php
declare(strict_types=1);
// Link previews for URLs that users paste into a chat or a comment.
require __DIR__ . '/vendor/autoload.php';
use App\BlockedUrlException;
use App\LinkPreview;
use App\UrlGuard;
use Tomaj\Scraper\Exception\FetchException;
$base = $argv[1] ?? 'http://127.0.0.1:8406';
// The fixture server runs on 127.0.0.1, which the guard blocks like any private address.
// Trust exactly that host and port here; a production guard has no trusted hosts.
$previews = new LinkPreview(new UrlGuard(trustedHosts: [parse_url($base, PHP_URL_HOST) . ':' . parse_url($base, PHP_URL_PORT)]));
$urls = [
$base . '/article.html',
$base . '/plain.html',
$base . '/hostile.html',
$base . '/to-metadata',
$base . '/gone.html',
'http://169.254.169.254/latest/meta-data/',
'http://localhost:6379/',
'http://10.0.0.5/admin',
'http://[::1]:8080/',
'file:///etc/passwd',
'gopher://127.0.0.1:25/',
];
foreach ($urls as $url) {
echo str_replace($base, '{fixture}', $url), "\n";
try {
$card = $previews->fetch($url);
echo ' ', LinkPreview::render($card), "\n";
} catch (BlockedUrlException $e) {
echo ' blocked: ', $e->getMessage(), "\n";
} catch (FetchException $e) {
echo ' no preview: the page cannot be downloaded', "\n";
}
}Výstup
text
{fixture}/article.html
<a class="card" href="http://127.0.0.1:8406/article.html"><img src="http://127.0.0.1:8406/img/halusky.jpg" alt=""><strong>Bryndzové halušky</strong><p>Potato dumplings with sheep cheese and bacon, the Slovak national dish.</p><small>Kitchen Notes</small></a>
{fixture}/plain.html
<a class="card" href="http://127.0.0.1:8406/plain.html"><strong>Opening hours</strong><small>127.0.0.1</small></a>
{fixture}/hostile.html
<a class="card" href="http://127.0.0.1:8406/hostile.html"><strong><script>alert(document.cookie)</script>Free prize</strong><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore…</p><small>" onmouseover="alert(1)</small></a>
{fixture}/to-metadata
blocked: 169.254.169.254 is a private or reserved address (169.254.169.254)
{fixture}/gone.html
no preview: the page cannot be downloaded
http://169.254.169.254/latest/meta-data/
blocked: 169.254.169.254 is a private or reserved address (169.254.169.254)
http://localhost:6379/
blocked: localhost is a private or reserved address (127.0.0.1)
http://10.0.0.5/admin
blocked: 10.0.0.5 is a private or reserved address (10.0.0.5)
http://[::1]:8080/
blocked: ::1 is a private or reserved address (::1)
file:///etc/passwd
blocked: scheme "file" is not allowed
gopher://127.0.0.1:25/
blocked: scheme "gopher" is not allowedČo si všimnúť
article.html: relatívnyog:imagesa prevedie na absolútnu URL; karta uprednostníog:titlepred<title>.plain.html: vôbec žiadny Open Graph, takže karta použije<title>a názov hostiteľa.hostile.html:<script>vog:titlea úvodzovka vog:site_namesa escapujú, obrázok sjavascript:sa zahodí a dlhý popis sa skráti./to-metadataje povolená URL, ktorá presmeruje na169.254.169.254: presmerovanie sa zablokuje skôr, než sa naň prejde./gone.htmlneexistuje:FetchException, zobrazená ako „bez náhľadu“.- Ostatné URL kontrola zablokuje ešte pred akoukoľvek požiadavkou: adresu metadát,
localhost, privátnu adresu, IPv6 loopback,file:agopher:.
Čo kontroluje CI
Vykreslené HTML troch kariet (escapovanie, spracovanie obrázka, náhradné hodnoty) a presný dôvod pri každej zablokovanej URL vrátane presmerovania.