[code] [blog] [Repos] [GPS Tracker] [Music] [VNC] [Restart VNC] [E-Mail me]

browse files at this commit · zip

commit 4662ca25a1c734b7964c6863f72bce3f3eb44524
Author: no-body-in-particular <admin@coredump.ws>
Date:   Thu Oct 22 09:47:28 2026 +0200

    Stop device claiming from revealing and handing out IMEIs
    
    A device was claimed by its IMEI alone, and the three answers ("belongs
    to another user", "has not connected yet", success) said which IMEIs
    exist and which are free, with no limit on tries. Any account could walk
    the IMEI space and take over unclaimed devices, including the 30 days of
    history a removed device keeps.
    
    - Every failed claim now gets one message, and failures are throttled
      per user and per address (5 in 15 minutes blocks both for an hour),
      in the existing LOGIN_ATTEMPTS table.
    - The name is validated before the claim checks: answered after them,
      "Invalid name" told which IMEIs exist and are unclaimed.
    - recover.php: a captcha gets one guess, right or wrong. It was only
      cleared when solved, so a wrong answer could be retried forever.
    - A failed password update logs SQLite's error instead of printing it.
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---
 var/www/tracker/database.php   | 74 +++++++++++++++++++++++++++++++++++++++++-
 var/www/tracker/devicelist.php | 32 ++++++++++++------
 var/www/tracker/recover.php    |  8 +++--
 3 files changed, 101 insertions(+), 13 deletions(-)

diff --git a/var/www/tracker/database.php b/var/www/tracker/database.php
index 7bf9ade..a628ade 100644
--- a/var/www/tracker/database.php
+++ b/var/www/tracker/database.php
@@ -679,7 +679,8 @@ function updatePassword($id,$pwd){
 
     if($ret==FALSE)
     {
-        echo "Error in update ".$db->lastErrorMsg();
+        // to the log, not the page: SQLite's message names tables and columns
+        error_log('tracker: password update failed: '.$db->lastErrorMsg());
     }
 
     $db->close();
@@ -1011,4 +1012,75 @@ function clearLoginFailures($username = null): void
     $db->close();
 }
 
+/*
+ * Device-claim throttling (devicelist.php write). Claiming needs only the IMEI, so failed
+ * claims are counted like failed logins, in the same LOGIN_ATTEMPTS table, keyed
+ * "claim-uid:<user id>" and "claim-ip:<address>": CLAIM_MAX_FAILURES inside LOGIN_WINDOW
+ * block both for CLAIM_LOCKOUT. The per-address key stops a run of throwaway accounts; the
+ * per-user key stops one account spread over many addresses. The window is LOGIN_WINDOW
+ * because loginBlockedSeconds() tidies up rows older than that.
+ */
+define('CLAIM_MAX_FAILURES', 5);    // failed claims allowed inside the window, per user and per address
+define('CLAIM_LOCKOUT', 3600);      // how long both stay blocked, seconds
+
+function claimThrottleKeys(): array
+{
+    start_session();
+
+    return ['claim-uid:'.($_SESSION['uid'] ?? ''), 'claim-ip:'.loginClientIp()];
+}
+
+function claimBlocked(): bool
+{
+    $db = loginThrottleDb();
+    $now = time();
+    $blocked = false;
+
+    foreach (claimThrottleKeys() as $key) {
+        $stmt = $db->prepare('SELECT BLOCKED_UNTIL FROM LOGIN_ATTEMPTS WHERE IP=:k;');
+        $stmt->bindValue(':k', $key, SQLITE3_TEXT);
+        $row = $stmt->execute()->fetchArray();
+
+        if ($row && ((int) $row['BLOCKED_UNTIL']) > $now) {
+            $blocked = true;
+        }
+    }
+
+    $db->close();
+
+    return $blocked;
+}
+
+function recordClaimFailure(): void
+{
+    $db = loginThrottleDb();
+    $now = time();
+
+    foreach (claimThrottleKeys() as $key) {
+        $stmt = $db->prepare('SELECT FAILURES, FIRST_FAILURE FROM LOGIN_ATTEMPTS WHERE IP=:k;');
+        $stmt->bindValue(':k', $key, SQLITE3_TEXT);
+        $row = $stmt->execute()->fetchArray();
+
+        $failures = 1;
+        $first = $now;
+
+        if ($row && ((int) $row['FIRST_FAILURE']) > ($now - LOGIN_WINDOW)) {
+            $failures = ((int) $row['FAILURES']) + 1;
+            $first = (int) $row['FIRST_FAILURE'];
+        }
+
+        $blocked_until = $failures >= CLAIM_MAX_FAILURES ? $now + CLAIM_LOCKOUT : 0;
+
+        $stmt = $db->prepare('INSERT OR REPLACE INTO LOGIN_ATTEMPTS (IP,FAILURES,FIRST_FAILURE,BLOCKED_UNTIL) '
+            .'VALUES (:k,:failures,:first,:blocked);');
+        $stmt->bindValue(':k', $key, SQLITE3_TEXT);
+        $stmt->bindValue(':failures', $failures, SQLITE3_INTEGER);
+        $stmt->bindValue(':first', $first, SQLITE3_INTEGER);
+        $stmt->bindValue(':blocked', $blocked_until, SQLITE3_INTEGER);
+        $stmt->execute();
+    }
+
+    $db->close();
+}
+
 ?>
diff --git a/var/www/tracker/devicelist.php b/var/www/tracker/devicelist.php
index 1b1f724..efdcf72 100644
--- a/var/www/tracker/devicelist.php
+++ b/var/www/tracker/devicelist.php
@@ -29,24 +29,36 @@ if ('write' === $ACTION || 'remove' === $ACTION || 'regenerate' === $ACTION) {
 
 switch ($ACTION) {
     case 'write':
-        if (deviceClaimed($IMEI)) {
-            exit('This device belongs to another user');
+        $NAME = $_POST['name'] ?? '';
+
+        // checked first: answered after the claim checks below, 'Invalid name' told which
+        // IMEIs exist and are not claimed yet
+        if (!is_string($NAME) || !validateName($NAME)) {
+            exit('Invalid name');
+        }
+
+        /*
+         * A device is claimed by its IMEI alone, so every way this can fail gets the same
+         * answer - claimed by someone, never connected, or too many failed tries - and failed
+         * tries are throttled per user and per address (see claimBlocked()). It used to say
+         * which, and had no limit: any account could walk the IMEI space and take over
+         * unclaimed devices, including the history of removed ones.
+         */
+        $CLAIM_FAILED = 'This device cannot be added. Check the IMEI, make sure the device has connected to our server, and try again later.';
+
+        if (claimBlocked()) {
+            exit($CLAIM_FAILED);
         }
 
-        $fp = devfile_open($IMEI.'.log.txt', 'r');
+        $fp = deviceClaimed($IMEI) ? false : devfile_open($IMEI.'.log.txt', 'r');
 
         if (false === $fp) {
-            exit('This device has not connected to our server yet');
+            recordClaimFailure();
+            exit($CLAIM_FAILED);
         }
 
         fclose($fp);
 
-        $NAME = $_POST['name'] ?? '';
-
-        if (!is_string($NAME) || !validateName($NAME)) {
-            exit('Invalid name');
-        }
-
         addDevice($IMEI, $NAME);
 
         break;
diff --git a/var/www/tracker/recover.php b/var/www/tracker/recover.php
index 77556ea..3854e53 100644
--- a/var/www/tracker/recover.php
+++ b/var/www/tracker/recover.php
@@ -10,11 +10,15 @@ $message = '';
 if ('POST' === $_SERVER['REQUEST_METHOD'] ) {
    // Checking that the posted phrase match the phrase stored in the session
 
+   // One guess per captcha, right or wrong. It was only cleared when solved, so a wrong
+   // answer could be followed by as many more as the caller liked against the same image.
+   $phrase = $_SESSION['phrase'] ?? null;
+   unset($_SESSION['phrase']);
+
    if (!csrfValid()) {
       http_response_code(403);
       $message = 'Your session expired. Please try again.';
-   } elseif (isset($_SESSION['phrase']) && is_string($_POST['phrase'] ?? null) && compareCaptcha($_SESSION['phrase'], $_POST['phrase'])) {
-      unset($_SESSION['phrase']); // one solved captcha must not be replayable
+   } elseif (is_string($phrase) && is_string($_POST['phrase'] ?? null) && compareCaptcha($phrase, $_POST['phrase'])) {
       // checked before the address is handed to mail(), which is the one place a newline in
       // it would become a header of the caller's choosing. getResetKey() only answers for an
       // address already on file, so this was never reachable from outside - but "not