简体   繁体   中英

Tor request detection with PHP does not work with domain, but with IP

I use this library: https://stackoverflow.com/a/37973763/1579327

If I request the page directly with the serverip it works but if I call the page via the domain it does not work. :/

I have installed mod_remoteip, so the server recognizes the real IP. I also have a PHP script, which gives me the "real" IP as a log (via $_SERVER['REMOTE_ADDR']). The IP that the server recognizes matches the exitnode IP, but why are Tor sessions not recognized by the domain? (The traffic goes through CLoudflare)

<?php

use Dapphp\TorUtils\TorDNSEL;

require_once 'src/TorDNSEL.php';

try {
    $isTor = TorDNSEL::IpPort(
        $_SERVER['SERVER_ADDR'],
        $_SERVER['SERVER_PORT'],
        $_SERVER['REMOTE_ADDR']
    );
    if ($isTor) {
        echo '<script>window.sessionStorage.setItem("torsession", true)</script>';
    }
} catch (\Exception $ex) {
    echo $ex->getMessage() . "\n";
}

?>

The configuration for mod_remoteip may not be set up correctly for Cloudflare. Since it works fine when you bypass CF, $_SERVER['REMOTE_ADDR'] is correct, but appears to be wrong when accessed by the domain.

Here's PHP code you can use that is specific to Cloudflare for detecting the real IP. DO NOT use this code unless your site uses Cloudflare (or set $usingCloudflare = false ), otherwise someone can spoof the headers and falsify their IP.

If you use this, you won't need mod_remoteip, but may still want it for other places.

// detect the user's IP from Cloudflare headers, or $_SERVER globals
$usingCloudflare = true; // set to false if not using, otherwise IP can be spoofed
$isCfRequest     = $usingCloudflare
                   && !empty($_SERVER['HTTP_CF_CONNECTING_IP']);

if ($isCfRequest) {
    $remote_addr = $_SERVER['HTTP_CF_CONNECTING_IP'];
} else {
    $remote_addr = $_SERVER['REMOTE_ADDR'];
}

// $remote_addr is the Cloudflare-aware client IP

// Practical TorDNSEL usage on a web server:
try {
    if (TorDNSEL::isTor($remote_addr)) {
       // do something special for Tor users
    } else {
        // not using Tor, educate them! :-D
    }
} catch (\Exception $ex) {
    error_log("Tor DNSEL query failed: " . $ex->getMessage());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM