IPIDB

Detect VPN and proxy logins

Check a login against VPN, proxy, Tor, hosting and blacklist flags with the IPIDB API in PHP, score the risk and ask for a second factor instead of blocking.

Most account takeovers come from automated logins: password lists tried from cheap servers, open proxies and anonymising networks. This guide checks every login against the security flags of the IPIDB API in PHP, turns them into a simple risk score, and asks risky logins for a second factor instead of blocking them outright. Real people use VPNs too, so a VPN alone should never lock anyone out.

What the API tells you

On paid plans the response to GET /v1/ip/{ip} has a security object:

FieldMeaning
is_vpn, vpn_providerThe address belongs to a commercial VPN service, and which one
is_proxyAn open proxy
is_torA Tor exit node
is_hostingA datacenter or hosting range, where ordinary users rarely sit
is_threat, threat_confidenceThe address was reported for abuse, with a confidence from 0 to 100

The free plan returns location and network data only; the Starter plan and above add these flags. The full list is in the field reference.

Ask only for what you need

A login check needs the security flags and the country, nothing else. ?fields= keeps the answer small:

Request
https://api.ipidb.com/v1/ip/203.0.113.7?fields=security,location.country_code

The check

The function below returns a score from 0 to 100 and the reasons behind it. The weights are a starting point; adjust them to what you see in your own logs. If the API cannot be reached the function returns a score of 0, so an outage never blocks your users.

login-risk.php
<?php
/**
 * Risk of a login from $ip, 0 to 100, with the reasons.
 * Needs a paid IPIDB key in the environment variable IPIDB_KEY.
 */
function login_risk(string $ip): array
{
    $ch = curl_init('https://api.ipidb.com/v1/ip/' . rawurlencode($ip) . '?fields=security,location.country_code');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 2,
        CURLOPT_TIMEOUT        => 3,
        CURLOPT_HTTPHEADER     => ['X-API-Key: ' . getenv('IPIDB_KEY')],
    ]);
    $data = json_decode((string)curl_exec($ch), true);
    curl_close($ch);

    if (empty($data['success']) || !isset($data['security'])) {
        return ['score' => 0, 'reasons' => ['lookup unavailable'], 'country' => null];
    }
    $s = $data['security'];
    $score = 0;
    $reasons = [];
    if (!empty($s['is_tor']))     { $score += 60; $reasons[] = 'Tor exit node'; }
    if (!empty($s['is_proxy']))   { $score += 50; $reasons[] = 'open proxy'; }
    if (!empty($s['is_hosting'])) { $score += 30; $reasons[] = 'datacenter address'; }
    if (!empty($s['is_vpn']))     { $score += 20; $reasons[] = 'VPN' . (!empty($s['vpn_provider']) ? ' (' . $s['vpn_provider'] . ')' : ''); }
    if (!empty($s['is_threat'])) {
        $score += (int)round(0.5 * (int)($s['threat_confidence'] ?? 0));
        $reasons[] = 'reported for abuse';
    }
    return [
        'score'   => min(100, $score),
        'reasons' => $reasons,
        'country' => $data['location']['country_code'] ?? null,
    ];
}

Using it in the login form

Run the check after the password is verified, not before: there is no point in spending a lookup on a wrong password, and attackers learn nothing from the response time. Then decide in three steps.

login.php
<?php
require __DIR__ . '/login-risk.php';

session_start();
$user = verify_password($_POST['email'] ?? '', $_POST['password'] ?? '');   // your own function
if (!$user) {
    http_response_code(401);
    exit('Wrong e-mail or password.');
}

$risk = login_risk($_SERVER['REMOTE_ADDR']);
log_login($user['id'], $_SERVER['REMOTE_ADDR'], $risk);                      // keep a record

if ($risk['score'] >= 80) {
    // Tor plus a bad reputation, or several flags together
    $_SESSION['pending_user'] = $user['id'];
    send_login_code($user);                                                   // e-mail or app code
    header('Location: /login/verify');
    exit;
}
if ($risk['score'] >= 30 || $risk['country'] !== $user['last_country']) {
    notify_user($user, 'New sign-in from ' . ($risk['country'] ?? 'an unknown place') . ': ' . implode(', ', $risk['reasons']));
}
$_SESSION['user'] = $user['id'];
header('Location: /account');

verify_password, log_login, send_login_code and notify_user stand for the functions your application already has. If your site runs behind a proxy, use the real client address instead of REMOTE_ADDR; the PHP geolocation tutorial shows how.

Why not block outright

  • Many companies route all staff traffic through a VPN, and privacy-minded users do the same at home.
  • Mobile carriers and some providers put thousands of users behind one address; a report against that address does not mean every user is hostile.
  • A second factor stops an attacker who has only the password, while a real user gets through in seconds.

Hard blocks make sense in a few places only, for example a sign-up form that is abused from Tor, or an admin panel that should only be reached from known addresses.

Rate limits and cost

Each login uses one lookup from your plan's quota. Cache the result per address for an hour so that a user who mistypes the second factor does not cost extra lookups. If you also want to stop password spraying before it reaches the password check, look at the blacklist endpoint, which has its own daily quota and is available on the free plan.

Related