browse files at this commit · zip
commit 7de266e2ac92eeafbc81d6c73a96992a4d5116cd
Author: no-body-in-particular <admin@coredump.ws>
Date: Fri Oct 30 11:49:28 2026 +0100
Stop password-reset mail being usable to mail anyone, and send it from an outbox
Found in the 2026-10-29 mail audit:
- Anyone could make the site send its DKIM-signed reset mail to any
address, as often as they liked. Resets are now limited to 10 requests
per client address per hour and 20 sent per hour site-wide,
registrations to 5 per address and 50 site-wide per day; only plain
addresses are accepted, looked up case-insensitively, and the reset
goes to the address on file.
- The PHP pool could submit mail itself (it was in group postdrop), which
bypassed Postfix's authorized_submit_users. recover.php now only writes a
{rcpt, key} job into /var/spool/tracker-outbox; tracker-mailer, run from
cron as its own user tracker-mail, checks each job and sends one fixed
message, at most 20 an hour, from a sender Postfix pins for that user.
mail() is disabled for the pool. README.md describes the setup.
- A reset requested while another request was writing the database could
silently lose its link (7 of 10 in a parallel test). Fixed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
README.md | 8 ++
etc/cron.d/tracker-mailer | 10 ++
usr/local/libexec/tracker-mailer | 239 +++++++++++++++++++++++++++++++++++++++
var/www/tracker/config.php | 18 +++
var/www/tracker/database.php | 123 +++++++++++++++++++-
var/www/tracker/lib.php | 12 ++
var/www/tracker/recover.php | 67 +++++------
var/www/tracker/registration.php | 42 +++----
8 files changed, 463 insertions(+), 56 deletions(-)
diff --git a/README.md b/README.md
index bc635bf..5ac809a 100644
--- a/README.md
+++ b/README.md
@@ -9,6 +9,14 @@
You don't *need* to run this for the server to work, however it's a really nice speedup to have.
The website that shows the data is contained in the /var/www folder. Both /var/www and /var/gps should be chown'd to your webserver's user.
+
+ Password-reset mail is not sent by the website itself (since 2026-10-29). `recover.php` writes one job per reset into `/var/spool/tracker-outbox` (`TRACKER_OUTBOX` in config.php), and `usr/local/libexec/tracker-mailer`, run every minute from `etc/cron.d/tracker-mailer`, sends a fixed message for each. To set it up:
+ - create a user and group `tracker-mail`, and the outbox `/var/spool/tracker-outbox` owned by `tracker-mail:tracker-mail` with mode 3770; add the webserver's (PHP) user to the group `tracker-mail`;
+ - keep the PHP user out of the `postdrop` group and disable `mail()` in its PHP configuration, so code running in the website can't submit mail of its own;
+ - in Postfix, allow `tracker-mail` in `authorized_submit_users` and pin its sender with `local_login_sender_maps` to a no-reply address (whose bounces go to /dev/null);
+ - change `SENDER` and the reset link in tracker-mailer to your own site.
+
+ Resets are limited to 10 requests per client address per hour and 20 sent per hour site-wide; registrations to 5 per address and 50 site-wide per day. Without these limits, anyone could make the site send its (DKIM-signed) reset mail to any address.
A default google API key is included for your (ab)use - and there are some sensible defaults set in "config.h" for file sizes on the device server - you should check yourself if these will work for you.
diff --git a/etc/cron.d/tracker-mailer b/etc/cron.d/tracker-mailer
new file mode 100644
index 0000000..efd5ec6
--- /dev/null
+++ b/etc/cron.d/tracker-mailer
@@ -0,0 +1,10 @@
+# /etc/cron.d/tracker-mailer - tracker-r12 (2026-10-29)
+# GPS tracker password-reset mail: tracker/recover.php leaves jobs in /var/spool/tracker-outbox
+# and tracker-mailer sends them as the user tracker-mail, whose envelope sender Postfix pins to
+# tracker-noreply@coredump.ws (local_login_sender_maps). At most 20 an hour.
+# It logs to syslog (mail facility, tag tracker-mailer). MAILTO is empty on purpose: cron would
+# submit its own mail as tracker-mail with a sender Postfix refuses for that user.
+SHELL=/bin/sh
+PATH=/usr/bin:/bin
+MAILTO=""
+* * * * * tracker-mail /usr/local/libexec/tracker-mailer
diff --git a/usr/local/libexec/tracker-mailer b/usr/local/libexec/tracker-mailer
new file mode 100755
index 0000000..3541821
--- /dev/null
+++ b/usr/local/libexec/tracker-mailer
@@ -0,0 +1,239 @@
+#!/usr/bin/python3 -I
+# /usr/local/libexec/tracker-mailer - sends the GPS tracker's password-reset mails.
+# tracker-r12 (2026-10-29), from mail-tooling's patches/02-tracker-mailer.py.
+#
+# The php-tracker pool no longer submits mail: it is out of group postdrop, mail() is disabled
+# in its profile, and Postfix's authorized_submit_users no longer lists it. Group postdrop let
+# any code running in that pool (ffmpeg on device-supplied audio included) write raw queue files
+# into maildrop with any sender and From:, which pickup accepts as local mail and OpenDKIM signs.
+#
+# recover.php drops one job per reset into OUTBOX: {"rcpt": "user@host.tld", "key": "<32 hex>"}
+# (tracker-mail:tracker-mail 3770; php-tracker writes it as a member of group tracker-mail).
+# This runs every minute from /etc/cron.d/tracker-mailer as the user tracker-mail, and
+# - accepts only a plain user@host.tld recipient (the tracker's own rule) and a 32-hex key;
+# - renders the one fixed message itself, so the pool chooses only (recipient, key);
+# - submits it with an explicit recipient (never -t) and the envelope sender Postfix pins for
+# this user (local_login_sender_maps: tracker-mail = tracker-noreply@coredump.ws);
+# - sends at most CAP_PER_HOUR an hour, whatever the pool queues: a job over the cap waits
+# for the next run, and a job older than the reset link (an hour) is dropped unsent.
+# A compromised pool can therefore at worst have CAP_PER_HOUR fixed reset mails an hour sent.
+#
+# Logs to syslog (facility mail, tag tracker-mailer). Never logs a key, only the recipient's
+# domain (Postfix logs the full address anyway).
+# Test hooks: TM_OUTBOX TM_STATE TM_SENDMAIL TM_LOG=stderr TM_NOW (fixed clock).
+import errno
+import fcntl
+import json
+import os
+import re
+import stat
+import subprocess
+import sys
+import time
+
+E = os.environ.get
+OUTBOX = E('TM_OUTBOX', '/var/spool/tracker-outbox')
+STATE = E('TM_STATE', '/var/lib/tracker-mail')
+SENDMAIL = E('TM_SENDMAIL', '/usr/sbin/sendmail')
+SENDER = 'tracker-noreply@coredump.ws'
+CAP_PER_HOUR = 20 # = MAIL_BUDGET['reset'] site-wide in tracker/database.php
+WINDOW = 3600
+JOB_TTL = 3600 # = RESET_KEY_TTL: an older link no longer works
+MAX_SCAN = 500 # directory entries looked at per run
+MAX_JOB = 4096
+JOB_NAME = re.compile(r'[0-9a-f]{16}\.json')
+TMP_NAME = re.compile(r'\.[0-9a-f]{16}\.tmp')
+# the same rule as TRACKER_MAIL_RE in tracker/config.php (fullmatch, so no trailing newline)
+RCPT = re.compile(r'[A-Za-z0-9._+-]{1,64}@(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}')
+KEY = re.compile(r'[0-9a-f]{32}')
+MESSAGE = ('From: GPS tracker <%(sender)s>\n'
+ 'To: %(rcpt)s\n'
+ 'Subject: GPS tracker password reset\n'
+ 'MIME-Version: 1.0\n'
+ 'Content-Type: text/plain; charset=UTF-8\n'
+ 'Content-Transfer-Encoding: 7bit\n'
+ 'Auto-Submitted: auto-generated\n'
+ '\n'
+ 'You can reset your password with the following link. It works once,\n'
+ 'and for one hour.\n'
+ 'https://coredump.ws/tracker/reset.php?key=%(key)s\n')
+
+if E('TM_LOG') == 'stderr':
+ def log(msg):
+ print('tracker-mailer: ' + msg, file=sys.stderr)
+else:
+ import syslog
+ syslog.openlog('tracker-mailer', syslog.LOG_PID, syslog.LOG_MAIL)
+
+ def log(msg):
+ syslog.syslog(syslog.LOG_INFO, msg)
+
+
+def now():
+ return float(E('TM_NOW')) if E('TM_NOW') else time.time()
+
+
+def load_sent(t):
+ try:
+ with open(os.path.join(STATE, 'sent.json')) as f:
+ data = json.load(f)
+ return [float(x) for x in data if isinstance(x, (int, float)) and t - WINDOW < x <= t + 60]
+ except (OSError, ValueError, TypeError):
+ return []
+
+
+def save_sent(sent):
+ path = os.path.join(STATE, 'sent.json')
+ tmp = path + '.tmp'
+ with open(tmp, 'w') as f:
+ json.dump(sent, f)
+ f.flush()
+ os.fsync(f.fileno())
+ os.replace(tmp, path)
+
+
+def remove(entry):
+ try:
+ if entry.is_dir(follow_symlinks=False):
+ os.rmdir(entry.path)
+ else:
+ os.unlink(entry.path)
+ return True
+ except OSError:
+ return False
+
+
+def read_job(entry, st):
+ """The job's bytes, or None. The pool's user owns what it writes here, so the file is opened
+ without following a symlink and without blocking on a FIFO, and must still be the regular,
+ single-link file that was listed."""
+ try:
+ fd = os.open(entry.path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC)
+ except OSError:
+ return None
+ try:
+ fst = os.fstat(fd)
+ if (not stat.S_ISREG(fst.st_mode) or fst.st_nlink != 1 or fst.st_ino != st.st_ino
+ or fst.st_dev != st.st_dev or fst.st_size > MAX_JOB):
+ return None
+ return os.read(fd, MAX_JOB + 1)
+ finally:
+ os.close(fd)
+
+
+def parse(data):
+ """(rcpt, key) from a job, or None."""
+ if data is None or len(data) > MAX_JOB:
+ return None
+ try:
+ job = json.loads(data.decode('ascii'))
+ except (UnicodeDecodeError, ValueError):
+ return None
+ if not isinstance(job, dict) or set(job) != {'rcpt', 'key'}:
+ return None
+ rcpt, key = job['rcpt'], job['key']
+ if not (isinstance(rcpt, str) and len(rcpt) <= 254 and RCPT.fullmatch(rcpt)
+ and isinstance(key, str) and KEY.fullmatch(key)):
+ return None
+ return rcpt, key
+
+
+def send(rcpt, key):
+ msg = MESSAGE % {'sender': SENDER, 'rcpt': rcpt, 'key': key}
+ try:
+ r = subprocess.run([SENDMAIL, '-i', '-f', SENDER, '--', rcpt], input=msg.encode('ascii'),
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, timeout=120,
+ env={'PATH': '/usr/sbin:/usr/bin:/bin', 'LANG': 'C'}, check=False)
+ except (OSError, subprocess.TimeoutExpired) as e:
+ return 'sendmail did not run: %s' % e.__class__.__name__
+ if r.returncode != 0:
+ err = r.stderr.decode('utf-8', 'replace').strip().splitlines()
+ return 'sendmail exit %d: %s' % (r.returncode, (err[0] if err else '')[:200])
+ return None
+
+
+def main():
+ if os.geteuid() == 0:
+ print('tracker-mailer: refusing to run as root (Postfix pins the sender for tracker-mail only)',
+ file=sys.stderr)
+ return 2
+ try:
+ # read-only is enough for flock, and works whoever created the file (verify.sh holds it as root)
+ lock = os.open(os.path.join(STATE, 'lock'), os.O_RDONLY | os.O_CREAT | os.O_CLOEXEC, 0o600)
+ except OSError as e:
+ log('cannot open the lock in %s: %s' % (STATE, e.strerror))
+ return 1
+ try:
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError as e:
+ if e.errno in (errno.EWOULDBLOCK, errno.EAGAIN):
+ return 0 # the previous run is still busy
+ raise
+
+ t = now()
+ sent = load_sent(t)
+ jobs, counts = [], {'malformed': 0, 'expired': 0, 'deferred': 0, 'not a file': 0}
+ try:
+ it = os.scandir(OUTBOX)
+ except OSError as e:
+ log('cannot read %s: %s' % (OUTBOX, e.strerror))
+ return 1
+ with it:
+ for i, entry in enumerate(it):
+ if i >= MAX_SCAN:
+ break
+ name = entry.name
+ try:
+ st = entry.stat(follow_symlinks=False)
+ except OSError:
+ continue
+ if TMP_NAME.fullmatch(name):
+ # a job recover.php never finished writing
+ if t - st.st_mtime > JOB_TTL:
+ remove(entry)
+ continue
+ if not JOB_NAME.fullmatch(name):
+ if remove(entry):
+ counts['malformed'] += 1
+ continue
+ if not stat.S_ISREG(st.st_mode):
+ if remove(entry):
+ counts['not a file'] += 1
+ continue
+ jobs.append((st.st_mtime, name, entry, st))
+
+ status = 0
+ for mtime, name, entry, st in sorted(jobs, key=lambda j: (j[0], j[1])):
+ if t - mtime > JOB_TTL:
+ if remove(entry):
+ counts['expired'] += 1
+ continue
+ job = parse(read_job(entry, st))
+ if job is None:
+ if remove(entry):
+ counts['malformed'] += 1
+ continue
+ if len(sent) >= CAP_PER_HOUR:
+ counts['deferred'] += 1 # stays queued for a later run, until it expires
+ continue
+ rcpt, key = job
+ err = send(rcpt, key)
+ if err:
+ log('job %s for *@%s not sent, kept for the next run: %s' % (name[:16], rcpt.split('@')[1], err))
+ status = 1
+ break
+ sent.append(now())
+ save_sent(sent)
+ if not remove(entry):
+ log('job %s sent but could not be removed' % name[:16])
+ log('job %s: reset mail submitted for *@%s (%d in the last hour)' % (name[:16], rcpt.split('@')[1], len(sent)))
+
+ left = {k: v for k, v in counts.items() if v}
+ if left:
+ log('%s; hourly cap %d, sent in the last hour %d' % (
+ ', '.join('%s %d' % kv for kv in sorted(left.items())), CAP_PER_HOUR, len(sent)))
+ return status
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/var/www/tracker/config.php b/var/www/tracker/config.php
index 463fb11..ae404cb 100644
--- a/var/www/tracker/config.php
+++ b/var/www/tracker/config.php
@@ -15,6 +15,24 @@ define('DEVPATH', '/var/gps/');
// place the path is written; everything opens DATABASE.
define('DATABASE', '/var/lib/tracker/database.db');
+/*
+ * Password-reset mail. This pool does not send mail itself: it is not in group postdrop, and
+ * mail() is disabled in its PHP profile, because any code running here (ffmpeg on device audio
+ * included) could otherwise submit mail of its own, DKIM-signed as coredump.ws. recover.php drops
+ * one job, {"rcpt": ..., "key": ...}, into TRACKER_OUTBOX; /usr/local/libexec/tracker-mailer, run
+ * every minute by cron as the user tracker-mail, checks it, renders the one fixed message and
+ * submits it with the envelope sender Postfix pins for that user (tracker-noreply@coredump.ws),
+ * at most 20 an hour. The directory is tracker-mail:tracker-mail 3770 (setgid, sticky); this
+ * pool's user writes it as a member of group tracker-mail.
+ */
+define('TRACKER_OUTBOX', '/var/spool/tracker-outbox/');
+
+/*
+ * The only shape of address an account may have and a reset may go to: letters, digits and
+ * . _ + - before the @, and a DNS name after it. tracker-mailer applies the same rule to every job.
+ */
+define('TRACKER_MAIL_RE', '/^[A-Za-z0-9._+-]{1,64}@(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}$/D');
+
/*
* Start a session only when there is not one already.
*
diff --git a/var/www/tracker/database.php b/var/www/tracker/database.php
index a628ade..cf8d31e 100644
--- a/var/www/tracker/database.php
+++ b/var/www/tracker/database.php
@@ -379,6 +379,9 @@ function findUser($username)
$filtered_username = SQLite3::escapeString($username);
$db = new SQLite3(DATABASE);
+ // the database is in rollback-journal mode: without a busy timeout a lookup that meets a
+ // writer's commit fails at once and reads as "no such user" (see findUserByEmail)
+ $db->busyTimeout(5000);
$sql = 'SELECT * from USERS where USERNAME=:username;';
$stmt = $db->prepare($sql);
$stmt->bindValue(':username', $filtered_username, SQLITE3_TEXT);
@@ -393,8 +396,14 @@ function findUserByEmail($email){
$filtered_email = SQLite3::escapeString($email);
$db = new SQLite3(DATABASE);
+ // every reset request now writes MAIL_BUDGET first; without a busy timeout this lookup failed
+ // at once when it met another request's commit and read as "no such account" (no link sent)
+ $db->busyTimeout(5000);
- $sql = 'SELECT * from USERS where MAIL=:email ;';
+ // case-insensitive: Victim@Example.org and victim@example.org are one mailbox, and an exact
+ // match let one person register both and have a reset mail sent to each. (Addresses are
+ // ASCII only - validateEmail - which is all sqlite's lower() folds.)
+ $sql = 'SELECT * from USERS where lower(MAIL)=lower(:email) ;';
$stmt = $db->prepare($sql);
$stmt->bindValue(':email', $filtered_email, SQLITE3_TEXT);
$ret = $stmt->execute();
@@ -419,17 +428,119 @@ function findUserByEmail($email){
*/
define('RESET_KEY_TTL', 3600);
+/*
+ * Budgets for what makes this site send mail to an address it was simply handed. A reset is one
+ * per account per hour, but accounts are free: a visitor with one account per address variant
+ * could have this server send DKIM-signed mail as coredump.ws to anyone, as fast as captchas can
+ * be solved. So:
+ * - reset: 10 requests per client address per hour, whatever they find, and 20 reset mails
+ * an hour for the whole site. A request that issues no link (unknown address, a
+ * link still pending) gives its site-wide unit back, so asking about addresses that
+ * have no account cannot use up everyone else's resets.
+ * - register: 5 attempts per client address per day that get past the form checks (so a typo
+ * in the password costs nothing, but every "is this address taken" answer counts),
+ * and 50 new accounts a day for the whole site.
+ * Counted in the database, so all pool workers share them. Running out answers exactly like
+ * success (reset) or like any other failure (register), so it tells a stranger nothing.
+ * tracker-mailer enforces the 20 an hour again on what it actually sends.
+ */
+define('MAIL_BUDGET', [
+ // kind => [per client address, whole site, window in seconds]
+ 'reset' => [10, 20, 3600],
+ 'register' => [5, 50, 86400],
+]);
+
+// The table also comes with the deploy (tracker-r12 deploy.sh); created here too so a fresh or
+// restored database works.
+function mailBudgetSchema($db): bool
+{
+ return $db->exec('CREATE TABLE IF NOT EXISTS MAIL_BUDGET (KIND TEXT NOT NULL, IP TEXT NOT NULL, '
+ .'TS INTEGER NOT NULL, SITE INTEGER NOT NULL DEFAULT 1);')
+ && $db->exec('CREATE INDEX IF NOT EXISTS MAIL_BUDGET_KIND_TS ON MAIL_BUDGET (KIND, TS);');
+}
+
+/*
+ * Takes one unit of $kind for $client. Returns the id of the row that records it, or 0 when the
+ * client has used up its budget, the site has, or the database cannot be locked (fails closed).
+ * A client over its own budget is not recorded again, so a flood adds no rows. Over only the
+ * site-wide budget, the attempt still counts against the client (a row with SITE = 0).
+ */
+function mailBudgetTake(string $kind, string $client): int
+{
+ [$perClient, $site, $window] = MAIL_BUDGET[$kind];
+ $db = new SQLite3(DATABASE);
+ $db->busyTimeout(5000);
+ $id = 0;
+
+ if (mailBudgetSchema($db) && $db->exec('BEGIN IMMEDIATE;')) {
+ $now = time();
+ $del = $db->prepare('DELETE FROM MAIL_BUDGET WHERE TS < :old;');
+ $del->bindValue(':old', $now - 2 * 86400, SQLITE3_INTEGER);
+ $del->execute();
+
+ $q = $db->prepare('SELECT coalesce(sum(IP = :ip), 0), coalesce(sum(SITE), 0) FROM MAIL_BUDGET'
+ .' WHERE KIND = :k AND TS > :since;');
+ $q->bindValue(':ip', $client, SQLITE3_TEXT);
+ $q->bindValue(':k', $kind, SQLITE3_TEXT);
+ $q->bindValue(':since', $now - $window, SQLITE3_INTEGER);
+ $res = $q->execute();
+ $row = $res ? $res->fetchArray(SQLITE3_NUM) : false;
+
+ if ($row && (int) $row[0] < $perClient) {
+ $siteOk = (int) $row[1] < $site;
+ $ins = $db->prepare('INSERT INTO MAIL_BUDGET (KIND, IP, TS, SITE) VALUES (:k, :ip, :now, :site);');
+ $ins->bindValue(':k', $kind, SQLITE3_TEXT);
+ $ins->bindValue(':ip', $client, SQLITE3_TEXT);
+ $ins->bindValue(':now', $now, SQLITE3_INTEGER);
+ $ins->bindValue(':site', $siteOk ? 1 : 0, SQLITE3_INTEGER);
+
+ if ($ins->execute() && $siteOk) {
+ $id = (int) $db->lastInsertRowID();
+ }
+ }
+
+ if (!$db->exec('COMMIT;')) {
+ $id = 0; // close() rolls the transaction back
+ }
+ }
+ $db->close();
+
+ return $id;
+}
+
+// Gives back the site-wide part of a unit from mailBudgetTake() that ended up sending nothing
+// (or creating no account). It still counts against the client.
+function mailBudgetRelease(int $id): void
+{
+ if ($id <= 0) {
+ return;
+ }
+ $db = new SQLite3(DATABASE);
+ $db->busyTimeout(5000);
+ $stmt = $db->prepare('UPDATE MAIL_BUDGET SET SITE = 0 WHERE rowid = :id;');
+ $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
+ $stmt->execute();
+ $db->close();
+}
+
function resetKeyDigest($key): string
{
return hash('sha256', 'tracker-reset:'.$key);
}
-// Returns a fresh key to mail, or null when there is no such account or one is still pending.
-function getResetKey($email)
+/*
+ * Returns a fresh key to mail, or null when there is no such account, one is still pending, or
+ * the address on file is not one a reset may be sent to (TRACKER_MAIL_RE) - no key is issued
+ * then, so it cannot block the account's resets for an hour with a link nobody gets.
+ * $rcpt is set to the address on file: the mail goes there, not to the spelling that was typed
+ * into the form, which since the lookup is case-insensitive may differ from it.
+ */
+function getResetKey($email, &$rcpt = null)
{
+ $rcpt = null;
$result = findUserByEmail($email);
- if (!$result) {
+ if (!$result || !is_string($result['MAIL'] ?? null) || !preg_match(TRACKER_MAIL_RE, $result['MAIL'])) {
return null;
}
@@ -451,6 +562,10 @@ function getResetKey($email)
$ok = $stmt->execute() && $db->changes() > 0;
$db->close();
+ if ($ok) {
+ $rcpt = $result['MAIL'];
+ }
+
return $ok ? $key : null;
}
diff --git a/var/www/tracker/lib.php b/var/www/tracker/lib.php
index d0796e4..8594341 100755
--- a/var/www/tracker/lib.php
+++ b/var/www/tracker/lib.php
@@ -449,6 +449,18 @@ function validateEmail($email)
return 0;
}
+ /*
+ * A reset mail goes to whatever is on file, so the address decides where mail signed as
+ * coredump.ws is delivered. Address literals ([127.0.0.1], [IPv6:...]) and the
+ * route/percent/bang/pipe forms are valid RFC 5321 but have no place in a tracker account:
+ * a literal of this server's own address is local delivery to any system account, and the
+ * others are relay or local-delivery tricks. Only letters, digits and . _ + - before the @,
+ * and a DNS domain after it (TRACKER_MAIL_RE, config.php).
+ */
+ if (!preg_match(TRACKER_MAIL_RE, $email)) {
+ return 0;
+ }
+
return preg_match_all('/^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}@)(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22))(?:\.(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\]))$/iD', $email);
}
diff --git a/var/www/tracker/recover.php b/var/www/tracker/recover.php
index 3854e53..c876b8e 100644
--- a/var/www/tracker/recover.php
+++ b/var/www/tracker/recover.php
@@ -19,14 +19,24 @@ if ('POST' === $_SERVER['REQUEST_METHOD'] ) {
http_response_code(403);
$message = 'Your session expired. Please try again.';
} 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
- // reachable today" is a property of the caller, not of this code.
+ // checked before the address goes anywhere near a mail: it used to be handed to mail(),
+ // where a newline in it would have become a header of the caller's choosing. The mail now
+ // goes to the address on file and tracker-mailer checks it again, but "not reachable
+ // today" is a property of the caller, not of this code.
$email = validateEmail($_POST['email'] ?? '') ? $_POST['email'] : '';
+ // the budget (database.php, MAIL_BUDGET) is taken before a key is issued, so running out
+ // of it neither mails nor replaces a pending link: 10 requests per client address an hour,
+ // 20 reset mails an hour for the whole site
+ $slot = $email ? mailBudgetTake('reset', loginClientIp()) : 0;
// null for an unknown address, and also while a link sent less than an hour ago is still
- // unused - asking again neither sends a second mail nor cancels the first link
- $key = $email ? getResetKey($email) : null;
+ // unused - asking again neither sends a second mail nor cancels the first link. $rcpt is
+ // the address on file, which is where the mail goes.
+ $rcpt = null;
+ $key = $slot ? getResetKey($email, $rcpt) : null;
+ if ($slot && !$key) {
+ // nothing will be sent: the site-wide unit goes back, the request still counts for the client
+ mailBudgetRelease($slot);
+ }
// said whether or not an account was found, and whether or not the mail got out. The
// first is deliberate - a different answer here tells a stranger which addresses are
@@ -34,35 +44,26 @@ if ('POST' === $_SERVER['REQUEST_METHOD'] ) {
// the queue, and delivery happens later.
$message='If an account uses this address, a password reset link has been sent to it. The link works once, for one hour.';
if($key){
- // Wrap the sentence, never the URL: wordwrap() with cut=true will
- // break a long link mid-token, and a base64 key with enough
- // +, / or = in it pushes the URL past 70 characters (76 at worst).
- // That silently mailed an unclickable link about 1 time in 500.
- $link = "https://coredump.ws/tracker/reset.php?key=" . urlencode($key);
- $msg = wordwrap("You can reset your password with the following link. It works once, and for one hour.", 70, "\n", true)
- . "\n" . $link;
-
/*
- * It used to go out with no headers at all, so both the From and the envelope
- * sender were whatever user the web server runs as - hiawatha@coredump.ws, which
- * is a system account and not a mailbox. Mail from an address that cannot be
- * replied to and cannot take a bounce is exactly the shape receivers score
- * against, and a bounce had nowhere to go, so a failure was invisible at both
- * ends.
- *
- * The -f sets the envelope sender, which is the address SPF is checked against -
- * not the From header - so it has to be a real one on this domain.
+ * This pool no longer sends mail itself (config.php, TRACKER_OUTBOX): it hands
+ * (recipient, key) to the outbox, and tracker-mailer - its own user, from cron -
+ * renders the fixed message (the link, wrapped text, From: GPS tracker
+ * <tracker-noreply@coredump.ws>, Auto-Submitted) and submits it with the envelope
+ * sender Postfix pins for it. Written under a dot name and renamed, so the mailer
+ * never reads half a job; 0640 so it can read it through group tracker-mail.
*/
- $from = 'admin@coredump.ws';
- $headers = implode("\r\n", [
- 'From: GPS tracker <'.$from.'>',
- 'Reply-To: '.$from,
- 'Content-Type: text/plain; charset=UTF-8',
- //so an out of office reply does not answer a robot
- 'Auto-Submitted: auto-generated',
- ]);
-
- mail($email, "GPS tracker password reset", $msg, $headers, '-f'.$from);
+ $job = json_encode(['rcpt' => $rcpt, 'key' => $key]);
+ $name = bin2hex(random_bytes(8));
+ $tmp = TRACKER_OUTBOX.'.'.$name.'.tmp';
+ $queued = false !== $job
+ && false !== @file_put_contents($tmp, $job)
+ && @chmod($tmp, 0640)
+ && @rename($tmp, TRACKER_OUTBOX.$name.'.json');
+ if (!$queued) {
+ @unlink($tmp);
+ mailBudgetRelease($slot);
+ error_log('tracker: could not queue a password reset mail in '.TRACKER_OUTBOX);
+ }
}
}else{
// $message= $_SESSION['phrase'] . ' ' . $_POST['phrase'];
diff --git a/var/www/tracker/registration.php b/var/www/tracker/registration.php
index 031bd5d..bcb99d9 100644
--- a/var/www/tracker/registration.php
+++ b/var/www/tracker/registration.php
@@ -15,28 +15,32 @@ if (isset($_GET['add']) && 'POST' === $_SERVER['REQUEST_METHOD']) {
} elseif (isset($_SESSION['phrase']) && is_string($_POST['phrase'] ?? null) && compareCaptcha($_SESSION['phrase'], $_POST['phrase'])) {
if (!validateEmail($_POST['email'] ?? '')) {
$message = 'Invalid email address.';
- } elseif (findUserByEmail($_POST['email'])) {
- // the same answer as for a taken username, so registering is not a way to find out
- // which addresses have accounts here
- $message = 'That username or email address is not available.';
- } else {
+ } elseif (!validateUsername($_POST['username']) || !validateName($_POST['name'])) {
// registration never checked these, so a username could contain markup - which
// then came straight back out in the "already exists" message below. these are
// the same rules modify.php already enforces on the profile form.
- if (!validateUsername($_POST['username']) || !validateName($_POST['name'])) {
- $message = 'Invalid name or username. Letters, numbers, dash and underscore only, up to 32 characters.';
- } elseif (findUser($_POST['username'])) {
- $message = 'That username or email address is not available.';
- } else {
- if(validatePassword($_POST["pwd"])){
- // the row id used to come from $_GET['add'], which the form puts in the
- // query string. updateUser() does INSERT OR REPLACE on that id, so posting
- // an existing user's id here overwrote their account - username, email and
- // password. generate it here instead; the request can no longer choose it.
- $ret = updateUser(uniqid(), $_POST['username'], $_POST['name'], $_POST['email'], $_POST['pwd']);
- }else{
- $message = "Invalid password. Must be 8 to 72 characters with at least 1 uppercase letter, 1 lowercase letter and 1 number. Spaces are allowed inside it, but not at either end.";
- }
+ $message = 'Invalid name or username. Letters, numbers, dash and underscore only, up to 32 characters.';
+ } elseif (!validatePassword($_POST["pwd"])) {
+ $message = "Invalid password. Must be 8 to 72 characters with at least 1 uppercase letter, 1 lowercase letter and 1 number. Spaces are allowed inside it, but not at either end.";
+ } elseif (!($slot = mailBudgetTake('register', loginClientIp()))) {
+ // accounts are what the reset budget is counted against, so they are budgeted too
+ // (database.php, MAIL_BUDGET): 5 attempts per client address a day, 50 new accounts
+ // a day for the site. Taken after the form checks, so a typo costs nothing, and
+ // before the lookups, so every "not available" answer counts.
+ $message = 'Registration failed';
+ } elseif (findUserByEmail($_POST['email']) || findUser($_POST['username'])) {
+ // the same answer for a taken address and a taken username, so registering is not
+ // a way to find out which addresses have accounts here - only a budgeted one
+ mailBudgetRelease($slot);
+ $message = 'That username or email address is not available.';
+ } else {
+ // the row id used to come from $_GET['add'], which the form puts in the
+ // query string. updateUser() does INSERT OR REPLACE on that id, so posting
+ // an existing user's id here overwrote their account - username, email and
+ // password. generate it here instead; the request can no longer choose it.
+ $ret = updateUser(uniqid(), $_POST['username'], $_POST['name'], $_POST['email'], $_POST['pwd']);
+ if (!$ret) {
+ mailBudgetRelease($slot);
}
}
} else {