36 Commits
Author SHA1 Message Date
Isaac ConnorandClaude Opus 5 712994b196 fix: only store sessions for clients that carry them
Every request through index.php starts a session and always dirties it:
zm_session_set_remote_addr() writes remoteAddr, and index.php stores skin,
css and navbar_type. ZMSessionHandler::write() then persisted that session
unconditionally, so any request arriving without a ZMSESSID cookie left a
Sessions row behind that nothing would ever load again.

Viewing an event polls the event's server every ZM_WEB_REFRESH_STATUS
seconds via monitorUrl, which is absolute when the monitor has a Server
row. Those cross-origin ajax polls carry auth in the URL and no cookie, so
each one added a Sessions row every few seconds. Bot scans of the login
page did the same.

Persist a session only when the client presented our cookie, or when
zm_session_persist() marks it as one we are issuing: login, and the
postLoginQuery stashed before redirecting to the login page.

Verified on a live install by logging row counts from the save handler:
three cookieless requests skipped the write and left the count unchanged,
while a cookie-jar run wrote on the request that returned the cookie.
php -l clean on both files.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GAFKf86P78WqniPEP2b45J
2026-08-25 17:36:31 -04:00
Isaac ConnorandClaude Opus 5 9c06eb6ba2 refactor: connect to the database on first use, not on include
database.php called dbConnect() at file scope, so including it opened a socket,
and on failure rendered views/no_database_connection.php and exit()ed from
inside a library include. Every model in web/includes requires this file, so
merely loading a class did both.

Connect on first use instead. $dbConn becomes tri-state - false for "not
attempted", null for "attempt failed", a PDO for connected - and two accessors
sit on top of it:

  zmDbConn()        opens if needed; on failure renders the error view and
                    stops, which is what the include used to do, just at the
                    point a query is actually attempted.
  zmDbConnOrNull()  opens if needed but returns null instead of ending the
                    request, for callers with a fallback.

dbQuery() is the funnel every fetch helper goes through, so routing it plus
dbEscape(), dbError() and dbInsertId() through the accessors covers the library.
The five callers that reached for the raw global are updated: config.php.in,
Event.php and ajax/console.php need a connection and take zmDbConn(); logger.php
takes zmDbConnOrNull() and falls through to its error_log target, so a logging
call can no longer end the request or open a connection by itself.

ZMSessionHandler captured $dbConn in its constructor. It is constructed while
session.php is being included, before anything has needed the database, so with
a lazy connection that captured false. It now resolves per call and its methods
return "no session" rather than dereferencing a bool.

Two smaller fixes fall out. The error view was included by a relative path that
only resolved when the cwd was web/, so it never worked for requests served out
of web/api/; it is now anchored with __DIR__. And dbDisconnect() set $dbConn to
null, which in the new tri-state means "connecting failed" and would send the
next query to the error page; it sets false so a later query can reconnect.
Nothing calls dbDisconnect() today.

This does NOT make database.php includable without a database. It requires
logger.php, which requires config.php, which reads ZoneMinder's configuration
out of the Config table at include time. Until that cycle is broken the
connection still happens during bootstrap, just from config.php rather than from
here.

Tests: tests/php/test_database_lazy_connect.php, 7 assertions, all pass. It
tokenises database.php and asserts nothing runs at include time, that dbQuery()
goes through the accessor, and that only the connection plumbing touches the
global. Verified it reports the pre-refactor file's `if ( !dbConnect() )` - an
earlier version of the check skipped tokens inside parentheses and so passed on
exactly the code it exists to reject.

Not covered by tests: behaviour when the database is genuinely unreachable, and
the session handler against a live database. Needs manual testing on an
installed tree, including stopping mysql to confirm the error view still renders
for both a web request and an API request.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01477mR97vfnK6zczbHgzq6T
2026-08-17 20:52:10 -04:00
Isaac ConnorandClaude Opus 5 935d0cf385 fix: keep an auth hash valid when the client address changes refs #4921
ZM_AUTH_HASH_IPS binds the auth hash to the client address. When that address
changes mid-session - a phone moving between wifi and cellular is the common
case - the hash the browser is still holding no longer matches the address we
now see, and the user is bounced to the login page. The usual workaround is to
turn ZM_AUTH_HASH_IPS off entirely.

Accept the address the request arrives from plus the one it arrived from
immediately before, so an in-flight hash validates once and generateAuthHash()
then reissues against the new address. Addresses are matched exactly. A netmask
was considered and rejected: accepting a whole subnet would let any other host
on the client's network replay a stolen hash, which on a home LAN includes the
cameras themselves.

The previous address is only accepted for as long as a hash issued to it would
itself still be valid (ZM_AUTH_HASH_TTL), so this widens which address is
accepted without extending how long any hash lives. A login clears it, since
nothing from before a privilege boundary should stay acceptable, and only one
previous address is ever retained.

userFromSession() needed the same treatment: it looks the cached hash up by the
live address, so after a change the slot does not exist yet and the user was
reported as not logged in regardless of what getAuthUser() would have accepted.

Also centralises the X-Forwarded-For/REMOTE_ADDR handling in getRemoteAddr(),
replacing four duplicated copies across session.php and auth.php. Those copies
sat on both the generation and validation sides, so any drift between them broke
authentication outright behind a reverse proxy. Network.php holds only that
address parsing; which addresses an auth hash is accepted from is auth policy
and lives in auth.php.

This is web-side only; zms has no session, so a stream request still fails once
on an address change and recovers through the existing auth-refresh path in
MonitorStream.js.

Tests: tests/php/test_remote_addr.php covers getRemoteAddr() parsing and the
session address rotation, and needs no config or database - 18 assertions, all
pass. tests/php/test_auth_hash_candidate_addrs.php covers the acceptance window
including both sides of the TTL boundary; it bootstraps config.php as the other
tests in that directory do and so needs an installed tree to run.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01477mR97vfnK6zczbHgzq6T
2026-08-17 20:52:10 -04:00
Isaac ConnorandCopilot Autofix powered by AI a2d6319b0b Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-06-12 19:46:57 -04:00
SteveGilvarryandClaude Opus 4.8 5ae582b1a1 fix: emit a single session cookie on login refs #2471
On successful login auth.php called zm_session_clear() followed by
zm_session_regenerate_id(), which together emitted three Set-Cookie
ZMSESSID headers: a deletion, a throwaway intermediate id, and the final
authenticated id. This is the multiple-cookie behaviour reported in #2471.

Add zm_session_regenerate_id_login(), which clears the pre-auth session
data and calls session_regenerate_id(true) to issue one new id while
deleting the old session server-side. Same anti-session-fixation
guarantee in a single Set-Cookie. Logout (zm_session_clear) and the
periodic mid-session regeneration are left unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-12 20:25:49 +10:00
Isaac ConnorandClaude Opus 4.7 8fd17a4b91 perf: index Sessions.access and rework session gc to two-phase delete
The session garbage collector ran DELETE FROM Sessions WHERE access < ?
against an unindexed column, forcing a full table scan and taking gap
locks across the access range. With REPLACE INTO Sessions happening on
every authenticated request, this is a deadlock hotspot.

- Add Sessions_access_idx on Sessions(access) in both fresh-install
  schema (zm_create.sql.in) and a migration (zm_update-1.39.10.sql).
- Rewrite ZMSessionHandler::gc to a two-phase delete: SELECT up to 100
  expired ids via the new index (consistent read, no locks), then
  DELETE WHERE id IN (...) by primary key. InnoDB takes record locks
  only on the matched rows, not gap locks on the access range.
- Bump version to 1.39.10 so zmupdate.pl picks up the new migration.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 07:38:18 -04:00
copilot-swe-agent[bot]andconnortechnology 5b51d086e1 fix: use HTTP_X_FORWARDED_FOR in auth hash validation to fix AUTH_HASH_IPS with reverse proxy
When AUTH_HASH_IPS is enabled and ZoneMinder is behind a reverse proxy
(e.g. Nginx in front of Apache), the hash is generated using
HTTP_X_FORWARDED_FOR (the real client IP) but was validated using only
REMOTE_ADDR (the proxy's IP), causing all authentication to fail.

Fix by consistently using HTTP_X_FORWARDED_FOR (first IP only, to guard
against spoofed multi-value headers) with REMOTE_ADDR as fallback in
all three places:
- web/includes/session.php: where remoteAddr is stored for hash generation
- web/includes/auth.php: getAuthUser() validation (PHP, also used by zms CGI)
- src/zm_user.cpp: zmLoadAuthUser() validation (C++ zms binary)

refs #4758

Agent-Logs-Url: https://github.com/ZoneMinder/zoneminder/sessions/959dfe9d-edea-4de5-a3a0-f90b758e5628

Co-authored-by: connortechnology <925519+connortechnology@users.noreply.github.com>
2026-05-04 14:53:38 +00:00
Isaac ConnorandClaude Opus 4.6 8044c80f9d feat: make Remember Me a tri-state option (None/Yes/No)
Change ZM_OPT_USE_REMEMBER_ME from a boolean to a tri-state string:
- None: checkbox hidden, sessions persist for ZM_COOKIE_LIFETIME (old disabled)
- Yes: checkbox shown and pre-checked by default
- No: checkbox shown and unchecked by default (old enabled behavior)

Update ConfigData.pm.in with new type definition, login.php to honor the
checked state, and session/action handlers to recognize the new values.
Migration in zm_update-1.39.4.sql maps old '1' to 'No' and '0' to 'None'.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 16:35:41 -04:00
Isaac ConnorandClaude Opus 4.6 3432e39c45 feat: add Remember Me checkbox to login page
Add ZM_OPT_USE_REMEMBER_ME config option (auth section, requires
ZM_OPT_USE_AUTH) that controls whether a Remember Me checkbox appears
on the login form. When enabled and unchecked, the session cookie
lifetime is set to 0 so the browser discards it on close, logging the
user out. When checked, the session persists for ZM_COOKIE_LIFETIME.
When the option is disabled, behavior is unchanged.

- ConfigData.pm.in: new ZM_OPT_USE_REMEMBER_ME boolean option
- login.php: checkbox between password field and reCAPTCHA/submit
- session.php: use lifetime=0 when remember me is off
- actions/login.php: set/clear ZM_REMEMBER_ME cookie on login, also
  update $_COOKIE so zm_session_start sees it in the same request
- auth.php: clear ZM_REMEMBER_ME cookie on logout
- en_gb.php: add RememberMe translation string

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 15:41:25 -05:00
IgorA100 bd93a8e329 When setting cookies via PHP, add handling of the "path" value in the options (session.php)
Otherwise, cookies set via PHP will not be able to be changed in JS.
Because JS saves cookies with path="/"
Closed: #4024
2024-05-22 10:32:10 +03:00
Isaac Connor e1c3584462 Add support for HTTP_X_FORWARDED_FOR instead of REMOTE_ADDR. Comment out debugging 2023-05-12 12:53:26 -04:00
Isaac Connor c40d251009 Add setting remoteAddr in session after regenerating 2022-10-17 19:09:24 -04:00
Isaac Connor 22a059d3bc Remove debug 2022-10-17 17:25:46 -04:00
Isaac Connor 9e257def8a Add debug, add validateId function to session handler. Change it to be a a subclass of SessionHandlerInterface so that we don't have to provide createId. Fixes session breakage in php8.2 2022-10-17 17:24:52 -04:00
Isaac Connor e26aa6d0ae Set samesite for session ZMSESSID cookie for php < 7.3 2022-05-10 20:22:44 -04:00
Isaac Connor 531793276f Fix auth'd user information being saved to session before switching session id's leaving bogus authenticated user in previous session. 2022-03-21 15:31:44 -04:00
Isaac Connor db866fa668 Implement zm_setcookie to simplify setting cookies, set samesite, deal with older php etc. Use it. 2022-01-20 09:46:38 -05:00
Isaac Connor 90c5f63d6d Fix session.gc SQL issue. Don't need a * when deleting 2020-10-24 09:05:39 -04:00
Isaac Connor 8f8526c2f1 add some debug to session garbage collection 2020-10-21 10:38:42 -04:00
Isaac Connor 10c0a6617c Return Debug to a regular function to match other logging functions. Since we switched to using namespaces we no longer clash with cake_php. 2020-10-14 10:39:25 -04:00
Isaac Connor e9d120f032 remove debug 2020-10-02 15:56:56 -04:00
Isaac Connor 5d20dde85c Implement a Session class that takes over session functions and stores in the database 2020-10-02 14:50:22 -04:00
Isaac Connor 6c831be61f remove extra , 2020-08-08 14:27:37 -04:00
Isaac Connor bf7aa3f5c2 this version of set_cookie_params was introduced in 7.3. So put back code for previous versions of php which unfortunately do not support the samesite parameter. Fixes #3009 2020-08-08 09:58:18 -04:00
Isaac Connor 56bf181dc4 set SameSite on session cookie. 2020-08-03 10:55:54 -04:00
Isaac Connor cfa2d13948 set samesite=Strict in session cookie 2020-08-02 12:06:13 -04:00
Isaac Connor e0074692d1 Remove debug 2019-09-17 12:07:30 -04:00
Isaac Connor 2993e52652 Fix auth timing out due to cookie timing out and getting deleted. 2019-09-04 12:14:32 -04:00
Isaac Connor 84492f29b1 Fix token auth sessions (#2676)
* If token is present do token based auth and do not do anything with session

* update HostController.  Use config constants, don't use sessions

* Remove Session from the components list

* spacing

* Remove Session from App Components list.

* Move APIEnabled check to the api from auth.php

* Rework auth.  login using username and password only occurs on login action now.  Including auth.php should not touch the session.  auth_hash logins no longer touch the session.  replace userLogin with a function called validateUser which matches the semantics of validateToken.

* remove debugging

* Add session storage if stateful query param is on, but only for LEGACY_API_AUTH

* fix mUser to username, etc.

* shuffle lines

* use  instead of session when generating auth hash.

* Add docs regarding the use of cookies and stateful query param

* Only open/close session if we are clearing a session var

* Use zm_session_start instead of session_start

* Should use zm_session_start instead of session_start

* document that zm_session_start should be called previously to session_regenerate_id

* Don't actually write out the session when generating auth hashes.  Means they should never actually persist.

* More backticking of SQL

* add .. to fix #2686

* Use material icons for sort because they look nicer

* fix typo

* have to add authhash to session on login

* restore username&password login for all urls

* fix

* fixes
2019-08-20 09:46:53 -04:00
Isaac Connor fd310c0f0a Merge branch 'master' into storageareas 2019-02-22 11:33:47 -05:00
Isaac Connor 2b90bf15a6 Improve session (#2487)
* Introduce ZM_COOKIE_LIFETIME which sets the life of the SESSION cookie, instead of using what is in php.ini

* Use zm specific session functions, which are now located in includes/session.php.  Be more agressive about clearing session on logout.

* Move session code to includes/session.php

* remove duplicate line

* Move is_session_open to session.php.  Move code to clear a session into session.php

* improve debug line when there is a problem updating config entry

* split description into description and help text for COOKIE_LIFETIME

* Remove redirect on line.  We do it in javascript on postlogin view so that we can say logging in before switching to console

* If there is a username in the session, then we are logged in, but we need to load the user object from the db.  We can't just trust it from the session. The user may have been deleted and having that data in the session can be a security risk. So load the user object on every request.

* Use session_regenerate_id instead of our broken code to do the same

* Move auth code to includes/auth.php

* add autocomplete tags to username and password inputs

* Don't redirect to login if we are already viewing login.  Put auth before including skin includes

* need to include session.php in auth.php

* update to php namespace
2019-02-22 09:43:38 -05:00
Isaac Connor d121ecab75 Merge branch 'improve_session' into storageareas 2019-02-05 15:48:42 -05:00
Isaac Connor cb0d9325e6 Use session_regenerate_id instead of our broken code to do the same 2019-02-05 11:45:09 -05:00
Isaac Connor 97e3a8178a use session_regenerate_id instead of other strange code 2019-01-30 16:08:09 -05:00
Isaac Connor cc0b5e0f1f Move is_session_open to session.php. Move code to clear a session into session.php 2019-01-30 12:52:01 -05:00
Isaac Connor 0eba430932 remove duplicate line 2019-01-30 11:05:43 -05:00