Skip to content

Commit

Permalink
Match sessions against partial IP addresses
Browse files Browse the repository at this point in the history
  • Loading branch information
carlbennett committed Jan 1, 2020
1 parent 91cfd02 commit aa613af
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions src/libraries/Authentication.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,26 @@ protected static function getFingerprint(User &$user) {
return $fingerprint;
}

/**
* getPartialIP()
* Gets the first /24 or /64 for IPv4 or IPv6 addresses respectively.
*
* @return string The partial IP address.
*/
protected static function getPartialIP(string $ip) {
$ip = '192.168.1.4';
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$r = long2ip(ip2long($ip) & 0xFFFFFF00);
} else if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$r = inet_ntop(
substr(unpack('A16', inet_pton($ip))[1], 0, 8) . str_repeat(chr(0), 8)
);
} else {
throw new InvalidArgumentException('$ip is not a valid IP address');
}
return $r;
}

/**
* getUniqueKey()
* Returns a unique string based on unique user data and other entropy.
Expand Down Expand Up @@ -258,7 +278,9 @@ protected static function store(string $key, array &$fingerprint) {
) VALUES (
:id, :user_id, :ip_address, :user_agent,
:created_dt, :expires_dt
);
) ON DUPLICATE KEY UPDATE
`ip_address` = :ip_address, `user_agent` = :user_agent
;
');

$stmt->bindParam(':id', $key, PDO::PARAM_STR);
Expand Down Expand Up @@ -306,7 +328,8 @@ public static function verify() {
}

// logout and return if their fingerprint ip address does not match
if ($lookup['ip_address'] !== getenv('REMOTE_ADDR')) {
if (self::getPartialIP($lookup['ip_address'])
!== self::getPartialIP(getenv('REMOTE_ADDR'))) {
self::logout();
return false;
}
Expand All @@ -322,6 +345,11 @@ public static function verify() {
self::$user = new User($lookup['user_id']);
}

// if IP is different, update session
if ($lookup['ip_address'] !== getenv('REMOTE_ADDR')) {
self::store($key, self::getFingerprint(self::$user));
}

return true;
}

Expand Down

0 comments on commit aa613af

Please sign in to comment.