exportEvents() copies each event file with exec($cmd, $output, $return)
and only put $return into a ZM\Debug line, so a failed cp never reached
the user and the export still handed back an archive missing files - the
"fails silently" half of #5074. $output was also never reset between
iterations, and exec() appends to a non-empty array, so that Debug line
accumulated every line of output from every file in the export.
Reset $output before each copy, and on a non-zero return log a ZM\Error
and mark the export failed; after the loop, return false when any copy
failed so ajax/event.php reports "Export Failed" instead of serving an
incomplete archive, matching how the tar/zip step already handles its
own exec() status.
tests/php/test_export_copy_failure.php extracts the exportEvents() body
from the real source and checks the reset and the failure handling are
present; it fails against the pre-fix source.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The export-generation path sanitized the user-supplied export directory name with
preg_replace('/[^\w\-.]/', '', ...), a whitelist that keeps dots, so a bare '..'
survived and $export_root became the parent of the export root. exportEvents()
then chmod'd, wrote into, and tarred that parent, and the archive was downloadable
through the safeExportComponent() read guard because it genuinely sat in the
exports dir. downloadEvents() had the same shape via DIR_EXPORTS_DOWNLOAD
(refs GHSA-72h2-rvhv-wr5g).
These are residual siblings of GHSA-fvx4-86xp-9v22, which hardened the download/
read views but left the write path. Refuse a '.'/'..' component in exportEvents(),
and route downloadEvents()'s name through the existing safeExportComponent().
Add tests/php/test_export_path_traversal.php.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Follow-up to the numeric field-name guard. FilterComponent::buildFilter() takes
an optional $validFields allow-list, but only EventsController's search index
and MonitorsController (via qualifyFields) used it; the other index/search/
consoleEvents call sites passed none, so a field name was checked only by the
character class, not against a known column set.
Pass array_keys($this->Model->schema()) - the pattern EventsController already
uses - at the remaining sites across Configs, EventData, Events (three), Frames,
Groups, ServerStats, Snapshots, Storage, Tags and UserPreference, so a field
must be a real column of the queried model and an unknown field is a 400 rather
than a MySQL 500. The injection itself is already closed by the numeric
field-name guard; this is defense in depth and consistent error handling.
ServerStatsController's commented-out permission check is left as-is (clients
need the data to render monitors); only the allow-list is added there.
Add tests/php/test_api_filter_fields_enforced.php.
Reported by arpitjain099.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A named parameter written `0:<payload>` reaches FilterComponent::buildFilter()
as an integer array key, and the field regex `[a-z0-9.]+` matched the all-digit
name, so `$conditions["0"] = $value` cast the key to an int. CakePHP 2.x renders
an integer-keyed condition as a raw, unescaped SQL fragment, so the value went
into the WHERE clause verbatim (UNION exfiltration, ACL bypass via a trailing
comment, blind boolean oracle) at the index() call sites that pass no
$validFields allow-list.
Refuse an all-digit field name in buildFilter(), so every key that reaches
$conditions contains a letter or a dot and stays a string key that CakePHP
quotes. Add tests/php/test_api_filter_numeric_field.php.
Reported by arpitjain099.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
stream.php checked the target event's permission using the request
string and then packed intval() of it. On 32-bit PHP intval('2147483648')
is 2147483647, so the check and zms could see different events, and a
non-numeric or array value was cast to whatever intval() made of it.
The ids now have to be digit strings that fit in this PHP's int, or the
request is refused. The checked int is what gets packed. The packing
moved to includes/stream_set_event.php so tests/php can check the bytes
against EventStream::DecodeSetEvent's layout.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Changing a user's password rewrote only the password hash and left the
user's JWT API tokens valid: a pre-change access token kept working and a
pre-change refresh token kept minting new access tokens for up to its 24
hour lifetime, so a leaked token survived the password change meant to
cut it off.
Set TokenMinExpiry to the change time in the same step that rewrites the
hash, so validateToken() rejects every token issued before the change,
matching the options page's existing revoke action. Covered paths: the
REST API User model (beforeSave), with the self-edit controller whitelist
widened to persist the field, and the classic web UI user action for both
the administrator edit and the self edit. The login-time upgrade of a
legacy hash to bcrypt rewrites the same password and is left untouched so
it does not revoke tokens.
refs GHSA-5w6w-qp25-2qqh
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
With fast deletes on, deleting an event in the web interface removed only
its Events row and left its Frames and Stats rows and its files for
zmaudit, and deleting a monitor left all of its events. zmaudit only runs
when ZM_RUN_AUDIT is on, and both options default to off independently,
so with fast deletes on and the audit off nothing ever removed them and
the Frames table grew without bound. In the Perl Event::delete the option
also kept zmfilter from removing the files of the events it purged.
Remove the option. ZM\Event::delete() always removes the Stats and Frames
rows and the files in one transaction with the Events row,
ZM\Monitor::destroy() always deletes the monitor's events, and the Perl
Event::delete deletes the files unless the storage area has DoDelete off.
zmupdate.pl rebuilds the Config table from ConfigData, so the option's row
goes away on upgrade without a migration. Drop the option from the docs,
from the zmaudit option help, and from the es_la, ro_ro and ru_ru
translations.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ajax/frames.php task=query checked the global canView('Events') and then
built the Frames query from the request event id alone, without the
per-event check its siblings make. A user with Events=View but a monitor
permission of None on an event's monitor could read that event's frame
records -- frame number, Normal/Alarm type, timestamp, delta and score --
for any event on a denied monitor, learning when activity happened and how
strong the alarm scores were across monitor boundaries. This is the web
copy of the disclosure GHSA-mg2g-jmfc-3w8g fixed in the Frames API;
frame images stay protected by views/image.php.
Construct the event in the sanity block and refuse the request unless
ZM\Event::canView() passes, which enforces the per-monitor permission
through Monitor()->canView(), matching ajax/event.php and the API.
Test tests/php/test_frames_query_requires_view.php includes the real file
with the web helpers stubbed (one child php process per case, as the file
declares queryRequest() at file scope) and asserts the Frames table is
never read for a denied or missing event. 11 checks; 6 fail before the fix.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
views/download.php and views/archive.php sanitized the user-controlled
`file` and `export_root` request parameters with str_replace('/', '')
only, which strips slashes but leaves `..` intact. export_root=.. made the
resolved path climb out of DIR_EXPORTS_DOWNLOAD into ZM_DIR_EXPORTS (and,
with file=.. as well, higher), and download.php then readfile()s it and,
from its shutdown handler, @unlink()s it. Any user with Events or Snapshots
view permission could read and delete files the web user can reach outside
the downloads directory.
Add safeExportComponent() and pathWithinExportDir() in
download_functions.php. The export file and directory names these views
handle are always single path components (zmExport_<connkey>.zip, a merged
'<Monitor> <start> to <end>.mp4'), so safeExportComponent() rejects any
value with a directory separator, a null byte, or a '.'/'..' traversal and
falls back to the generated default. pathWithinExportDir() resolves the
final path with realpath() and is checked in front of readfile() and
unlink(), so a path that still escapes the export directory - including
through a symlink - is refused.
Tests: tests/php/test_download_path_traversal.php
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
FilterTerm::sql_attr() returned 'weekday(NOW()' without its closing
parenthesis, so any filter with a Current Weekday term failed with
"Database query failed". FilterTerm::valid() treated the value 0 (Monday) as
missing, so a Monday term was dropped and the filter matched every event.
ZoneMinder::Filter had no CurrentWeekday case at all and emitted
E.CurrentWeekday, a column Events does not have, so zmfilter.pl could not run
such a filter either. Emit weekday(NOW()) there as well.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CORSHeaders() (web UI) and AppController::beforeFilter() (API) send
Access-Control-Allow-Origin with Access-Control-Allow-Credentials: true.
With no Servers rows and ZM_MIN_STREAMING_PORT set they reflected any
Origin, and with Servers rows they matched the Origin against each
server's Hostname and Name with a regex anchored only at the start, so
https://zm.example.com.evil.net was accepted for zm.example.com.
Both now call corsAllowedOrigin() in Network.php, which accepts an
Origin of the form scheme://host[:port] whose host equals a server's
Hostname or Name, or, without Servers rows and with streaming ports,
the host this request was made to. Any port is accepted, so multi-port
streaming keeps working. Same-origin and unlisted origins get no CORS
headers, as before; the web UI still warns about unlisted origins only
when Servers rows exist.
Tests: tests/php/test_cors_allowed_origin.php
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With the search or advanced search box in use, the total was counted after
the rows were cut down to the requested page, so it equalled the page size
and the table could not page through the results. Count them first.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Events list hid events of soft-deleted monitors (Monitors.Deleted) while
building the rows, after the filter limit, the page slice and the totals. Pages
came up short, the footer counted and summed events that were never listed,
and a filter limit counted hidden events too.
Exclude M.Deleted in both SELECTs of queryRequest() so the limit, paging and
totals only see listed events, and drop the per-row skip. The new test runs
queryRequest() against the database inside a rolled-back transaction.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
qualifyFields() required a bare field to be a Monitors column, so names
only a joined table has, such as Status, CaptureFPS and AnalysisFPS from
Monitor_Status, answered 400 where they used to filter:
GET /api/monitors/index/Status:Connected.json -> 400 Unknown filter field
A bare field that Monitors has is still written Monitor.Field. Otherwise
it must be a column of exactly one joined table and is left bare, as
before, for MySQL to resolve; buildFilter() does not accept an alias with
an underscore such as Monitor_Status, so it cannot be qualified. A bare
field no table has stays a 400, and one two joined tables have and
Monitors does not (MonitorId, in Monitor_Status and Event_Summaries) is a
400 "Ambiguous filter field" instead of a 500 from MySQL.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MonitorsController::index() passed its named parameters to
FilterComponent::buildFilter() without a field list, so any name made
of letters, digits and dots reached MySQL as a column:
GET /api/monitors/index/Nope:1.json -> 500, PDOException 42S22
and the bare names Id and Name, which the joined Manufacturers and
Models tables have too, failed as ambiguous columns (also 500).
FilterComponent::qualifyFields() checks each field against the columns
of the queried model and of the models find() joins, and writes it
Model.Field: a bare field is a Monitors column. GroupId stays bare for
the Groups_Monitors join. Anything else is a 400 "Unknown filter field",
as events/index answers since 028ccecb5. Column names match without
regard to case and are written as the schema spells them.
The web UI's map (Deleted:0) keeps working;
Name:x, Id >:0, Name LIKE:x and Id IN:1,2 now return monitors instead
of a 500.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With debug 0, Cake replaces a 500's message with a generic one, but
Crud's exception renderer adds data.exception.message from the raw
exception. A PDOException (e.g. monitors/index/<unknown column>:1.json)
returned the SQL error and its fragment of the query to the client.
data.url also echoed the request URL with its token or password.
ZmExceptionRenderer extends Crud's renderer: with debug 0 a 5xx body
carries the generic message in data.exception.message (class and code
are kept), and data.url has credential values redacted.
AppController::beforeFilter() swaps it in for the renderer Crud's
ApiListener registers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
getAuthUser() logs a fingerprint of the auth hash instead of the hash
(ZM\logFingerprint() from log_redact.php). The test evaluates
getAuthUser() in its own namespace with stub loggers, so it needs that
function stubbed too.
ZM_Object::apply_defaults() logged every property of each object it
loaded at Debug level, so loading a Monitor wrote its Pass,
ONVIF_Password and the user:password@ in Path and ControlAddress, and
loading a User its password hash (found by the camera probe, after the
monitor-save fix). A statement that failed logged its bound values at
Error level, which reaches the Logs table: for a monitor or user save,
the camera password or the password hash. dbFetchOne()'s missing-column
warning printed the whole row.
Properties and rows go through redactForLog() (by field name). Bound
values of a failed statement are logged only with ZM_DB_DEBUG, the
setting that already logs every statement's values; otherwise their
count.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When the other server of a multi-server install did not answer,
file_get_contents() raised a PHP warning whose text is the call and its
URL, ?auth=<hash> or user=/pass= included, and PHP wrote it to the web
server's error log (Event.php, Filter.php). The same happened with the
image proxy's digest retry (camera user:password@) and the X-Frame
check of a website monitor (get_headers()), which also took the false
it returns on failure for an array.
Fetch with @ and log lastErrorForLog(), the reason without the call
and its URL, next to urlForLog() of the URL. Server::SendToApi()
already used @ and now logs the reason too.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The network probe logged the camera password it was about to try and
camera URLs with user:password@ (monitor_probe.php), saving a monitor
dumped the changed fields with Pass, ONVIF_Password and the Path and
ControlAddress credentials (actions/monitor.php), the ONVIF probe logged
the failing zmonvif-probe command line, password included, at Error
level, which reaches the Logs table by default (onvifprobe.php), the CSV
camera import logged each URL at Info level (add_monitors.php), and the
image proxy logged its Digest Authorization header and the camera URL
(views/image.php).
Log user names without passwords, URLs through urlForLog() and dumps
through redactForLog(). removeUserinfo(), used by both, now also strips
a ControlAddress's scheme-less user:password@host, and ends the userinfo
at the last @ before the path: a camera password with a raw @ in it
works with cameras and ffmpeg, and its tail was left in the log.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
urlForLog() dropped the whole query string, which also hid the
parameters that say what the call was (view=, action=, user=). Run the
query through redactQueryString() instead: the auth relay's password is
replaced, auth= and token= become fingerprints, the rest is kept.
redactQueryString() now also ends a value at '?', since Event.php
builds the plain relay as ?user=..?pass=...
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An unauthenticated request is redirected to the login view with its
query string in postLoginQuery, and index.php logged that redirect at
debug level: an expired or refused auth= hash, a token= JWT or a
password= sent in the URL went into the log twice, once in the
"Redirecting to" line and once in the next request's parameter dump.
redactForLog() now also redacts query strings found inside values, and
the redirect line goes through the new redactQueryString().
Found by the web probe on the fix branch.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Event.php, Server.php and Filter.php call the API or index.php of
another server with the auth relay appended (?auth=<hash>, or with
ZM_AUTH_RELAY=plain the user's username and password) and logged that
URL, at debug level before the call and at Error level when the other
server did not answer. Error reaches the Logs table at the default
database log level. Log it through urlForLog(), without the query.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
getAuthUser() logged the presented auth hash at debug level on every
check and at Info level whenever a check failed. Info reaches the Logs
table at the default database log level, which System=View users read.
A hash refused here can still be valid: bound to another client address
(ZM_AUTH_HASH_IPS) or meant for another server. Log its fingerprint,
the same tag zms and zm_rtsp_server log for it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
index.php logged print_r($_REQUEST) at debug level on every request:
the login form's password in clear, auth= hashes, token= JWTs, a new
user's password from the user form and camera passwords from the
monitor form. The API's AppController logged print_r($_SESSION) on
every cookie-authenticated call: the session's auth hashes and, with
ZM_AUTH_RELAY=plain, the user's password.
Add web/includes/log_redact.php (loaded by logger.php) with
redactForLog(), which keeps the dump's shape but replaces passwords and
secrets, fingerprints tokens, auth hashes and CSRF tokens, and strips
user:password@ from URL values; urlForLog(); and logFingerprint(), the
web side of zm::crypto::LogFingerprint().
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
For a user whose hash zmupdate.pl overlaid with bcrypt ("-ZM-" prefix),
validateUser() logged the MySQL-encoded form of the typed password next
to the stored bcrypt hash at debug level, on every login attempt, right
or wrong. The MySQL-encoded form is SHA1(SHA1(password)), unsalted, so
it falls to an offline dictionary attack. The line above it already
says which comparison runs.
Adds tests/php/test_auth_log_redaction.php, which records every log line
validateUser() writes for each stored hash type and searches them for
the password, its encoded form and the stored hash.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
buildMenuItem() renders every left-sidebar menu entry and put $id,
$href and the link class into HTML attributes as given, so each caller
had to escape them; the Montage Review link did not. Escape them in
buildMenuItem() itself. Entities already in a value are kept, so the
callers that escape first (the Cycle link's &, custom menu links,
the Montage Review link) render as before.
The links from ZM_WEB_NAVBAR_LINKS, which the sidebar reads back
through DOMDocument (decoded), are now re-encoded too.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
getMontageReviewHTML() copied the StartDateTime >= / <= values of
filter[Query][terms] into the link's href as they came in the request.
A value with a double quote closed the attribute, so a crafted link put
arbitrary markup into the navbar of any page it opened; an & added or
overrode query parameters of the link.
URL-encode minTime and maxTime, HTML-escape the whole href, and skip
terms that are not arrays or have a non-string value instead of
failing with a TypeError.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Update and Revoke All Tokens buttons are disabled for users without
System edit since the handlers refuse them; the Revoke Token and API
Enabled checkboxes next to each user stayed clickable and did nothing.
Disable them the same way.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit f096e919c2)
The API tab of Options renders for any user with System view, and the
view itself handled its two POST buttons: updateSelected sets
Users.APIEnabled for every user and revokeAllTokens bumps every user's
TokenMinExpiry. includes/actions/options.php refuses a System=View user,
but returns before the view is rendered, so the view went on and ran
the UPDATEs. A System=View user could turn off API access for every
account, admins included, and invalidate every issued token.
Run both handlers only when canEdit('System'), log a warning otherwise,
and disable the two buttons for users who cannot use them.
tests/php/test_options_api_requires_system_edit.php includes the view
with System=View and System=Edit and checks which SQL it sends.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 6e64739e84)
Event::canView() and canEdit() may ask the user for the permission
($u->canView('Events')) instead of reading the field, which counts a
role as well. The test's stub user only had the field getters, so such
an Event.php ends in a fatal error. The stub answers as User::canView()
and canEdit() do for a user without a role; the field getters stay for
the current Event.php.
(cherry picked from commit ea741802dd)
ZM\Event::canView() and canEdit() asked the event's Monitor, and an
Event with no MonitorId (built from an empty or failed lookup) gets an
empty Monitor, whose canView() falls back to the user's global Monitors
permission. So an Event with no Id passed both checks for any user with
Events access, whatever monitors they were denied. A caller that built
an Event from a lookup that could come back empty and trusted canView()
without checking Id() first failed open; the API's events/view did.
Return false from both when the Event has no Id. Every caller in the
web UI, ajax and API either checks Id() first or builds the Event from
a database row, so none relied on the empty Event passing; callers that
did not check (the frame view, export and download lists) now refuse a
missing event id instead of working on an empty one.
Test: tests/php/test_event_can_view_no_id.php drives the real ZM\Event
with a stub Monitor (8 of 13 checks fail before this change).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 054d4f0fa6)
EventsController::view() looks the event up with the per-monitor
condition and then asks ZM\Event::canView(). For an event on a denied
monitor the restricted find() is empty, the empty ZM\Event has no
monitor, and canView() falls back to the user's global Monitors
permission, so it passes. The action then answered 200 with a stub
built from the id alone: the hidden event's Next/Prev ids, its max
score and alarm frame ids, fileSize and a FileSystemPath.
The event is known to exist at that point, so an empty result means
the monitor condition removed it: answer 401 as edit, delete and
archive do.
Test: tests/php/test_api_event_view_acl.php (2 of 6 checks fail
without the fix).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit cf62c05576)
An edit replaces all of a snapshot's or tag's event links, but only the
new list was checked, so {"Event": []} from a user denied a monitor
unlinked that monitor's events, and any list without them dropped them.
The API's view of a snapshot or tag leaves those events out, so a client
that reads the list, changes it and saves it dropped them too.
The new list still needs view on every event it links. The links to
events the user may not view are now added back to the list before the
save (eventLinksToSave()), so the user can change the links they see and
the others stay. A link to an event that no longer exists is dropped.
Test: tests/php/test_api_associated_ids.php
(cherry picked from commit 6b1d0eaf8d)
Groups, Snapshots and Tags add/edit checked the ids from MonitorIds or
EventIds when the request had them, but Model::save() links the HABTM
entry (Monitor, Event) and ignores those fields on edit. A Groups=Edit
user could send {"Group":{"MonitorIds":"<current members>"},"Monitor":[]}:
the membership check saw no monitor moved, the save emptied the group and
lifted the Groups_Permissions deny on its monitors. On add, an empty
MonitorIds or EventIds next to a Monitor/Event list let monitors the user
may not edit into a new group, and events the user may not view into a
snapshot.
requestAssociatedIds() now reads the list the way save() does and
rewrites the request's entry to that plain list of ids, so a row given as
a join record links only its MonitorId/EventId. add() copies MonitorIds
or EventIds into the entry before the check, as it did before the save.
Test: tests/php/test_api_associated_ids.php
(cherry picked from commit 6bf015530e)
ajax/event.php action=video appended monitorLimitSql() after GROUP BY,
where "GROUP BY E.Id AND MonitorId IN (...)" only changes the grouping
and filters nothing. A user denied a monitor could still have
zmvideo.pl encode that monitor's events and learn the file's path.
Put the limit in the WHERE clause and also check the loaded event with
Event::canView(), which applies the monitor's permission and the
Snapshots rule. monitorLimitSql() has no other caller.
tests/php/test_event_video_requires_view.php covers a denied monitor, a
missing event, a Snapshots-only user and a user without Events or
Snapshots view; 5 of its 11 checks fail before this change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c95d4decbc)