From 2949ec7270257766ffc40fa9169e3b67107ebfd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oskar=20Sch=C3=B6ldstr=C3=B6m?= Date: Mon, 16 Nov 2026 12:42:57 -0300 Subject: [PATCH] Quieter audits: linked documents, plugins' own caps, hooks and caches - Exposed: a downloadable document under uploads that a published post or its fields link to is public on purpose: counted, not flagged, unless its name suggests people's data. The collector lists those links (linked_uploads). - Capabilities an active plugin gives its users itself (WPML's translate, manage_translations, wpml_*) aren't flagged as injection; the rest of a user's extra capabilities still are. - A new scheduled hook with an active plugin's prefix (Yoast's wpseo, WPML, WooCommerce, Gravity Forms, Redirection) is counted, not flagged. - WPML's compiled Twig cache under uploads is counted while WPML is active, only in its exact shape (cache/wpml/twig//.php). Each with the plugin inactive is flagged as before. Co-Authored-By: Claude Opus 5.5 --- check_accounts.go | 19 +++++++- check_exposed.go | 11 +++++ check_files.go | 10 ++++ check_options.go | 13 +++++- collector.php | 32 +++++++++++++ facts.go | 23 +++++++-- owned.go | 115 +++++++++++++++++++++++++++++++++++++++++++++ owned_test.go | 116 ++++++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 333 insertions(+), 6 deletions(-) create mode 100644 owned.go create mode 100644 owned_test.go diff --git a/check_accounts.go b/check_accounts.go index f0442d4..e182296 100644 --- a/check_accounts.go +++ b/check_accounts.go @@ -32,6 +32,7 @@ func (c *checker) accounts() { } else if len(c.p.AllowedCountries) == 0 { c.info("no allowed countries configured: session countries not checked") } + active, pluginCaps := c.activeFolders(""), 0 for _, u := range s.Users { who := fmt.Sprintf("user %d %q <%s> roles %s", u.ID, u.Login, u.Email, strings.Join(u.Roles, ",")) if u.Privileged { @@ -51,8 +52,19 @@ func (c *checker) accounts() { c.dormant(u, who, s.WPVersion) c.leaver(u, who) } - if len(u.ExtraCaps) > 0 { - caps := slices.Sorted(slices.Values(u.ExtraCaps)) + // Capabilities an active plugin gives its users itself (WPML's + // translator ones) aren't injection: only the rest is flagged. + var caps []string + for _, cp := range u.ExtraCaps { + if !ownedCap(active, cp) { + caps = append(caps, cp) + } + } + if len(caps) < len(u.ExtraCaps) { + pluginCaps++ + } + if len(caps) > 0 { + slices.Sort(caps) c.flag(Flag{ID: fmt.Sprintf("caps:%d:%s", u.ID, short(caps...)), Severity: Urgent, Kind: KindCapabilities, Message: "user holds capabilities outside their roles (role injection?)", Untrusted: who + "; extra: " + strings.Join(caps, ", ")}) @@ -63,6 +75,9 @@ func (c *checker) accounts() { Untrusted: fmt.Sprintf("%s; name %q, created %s, last used %s from %s", who, p.Name, ts(p.Created), ts(p.LastUsed), p.LastIP)}) } } + if pluginCaps > 0 { + c.info("%d users hold capabilities that active plugins give their users themselves (such as WPML's translate): not flagged", pluginCaps) + } for _, k := range s.WooKeys { isNew := prev != nil && !prev.hasWooKey(k) c.flag(Flag{ID: fmt.Sprintf("woo-key:%d:%d:%s", k.Blog, k.ID, idPart(k.TruncatedKey)), Severity: sev(isNew && k.Permissions != "read"), Kind: KindWooKey, diff --git a/check_exposed.go b/check_exposed.go index 44564c9..2168bca 100644 --- a/check_exposed.go +++ b/check_exposed.go @@ -207,6 +207,7 @@ func (c *checker) exposed() { uploads := f.Content + "/uploads/" blocked := map[string]int{} owned := map[string]int{} + linked := 0 folders := map[string][]Candidate{} for _, cd := range cands { if p := c.uploadsOwner(cd.Path, uploads); p != "" && (cd.Type == "document" || cd.Type == "archive") { @@ -214,6 +215,13 @@ func (c *checker) exposed() { continue } a, asked := w.Files[cd.Path] + // A document a published page or its fields link to is public on + // purpose: counted, unless its name suggests people's data. + if rest, ok := strings.CutPrefix(cd.Path, uploads); ok && asked && a.Served() && (cd.Type == "document" || cd.Type == "archive") && + !personal(path.Base(cd.Path)) && c.linkedDoc(rest) { + linked++ + continue + } at := fmt.Sprintf("%s (%d bytes, %s)", cd.Path, cd.Size, day(cd.Mtime)) id := "exposed:" + idPart(cd.Path) + ":" + short(fmt.Sprint(cd.Size), fmt.Sprint(cd.Mtime)) switch { @@ -266,6 +274,9 @@ func (c *checker) exposed() { for _, t := range slices.Sorted(maps.Keys(blocked)) { c.info("%d %ss on the server that the public URL doesn't serve", blocked[t], t) } + if linked > 0 { + c.info("%d downloadable documents under uploads that published pages link to: public on purpose, not flagged", linked) + } for _, p := range slices.Sorted(maps.Keys(owned)) { c.info("%d files in %s's own uploads folder not checked: the plugin is active", owned[p], p) } diff --git a/check_files.go b/check_files.go index 4eb334f..e65e4e7 100644 --- a/check_files.go +++ b/check_files.go @@ -24,13 +24,23 @@ func (c *checker) files() { f, repo := c.in.Facts.Files, c.in.Repo uploads := f.Content + "/uploads/" paths := slices.Sorted(maps.Keys(f.Files)) + active, cached := c.activeFolders(""), map[string]int{} for _, p := range paths { if rest, ok := strings.CutPrefix(p, uploads); ok && !f.Silence[p] { + // An active plugin's compiled cache, in exactly its shape (WPML's + // Twig templates): counted, not flagged. + if pl := ownedPHP(active, rest); pl != "" { + cached[pl]++ + continue + } v := f.Files[p] c.flag(Flag{ID: "upload-php:" + idPart(rest) + ":" + firstN(v, 16), Severity: Urgent, Kind: KindFile, Message: "executable file under uploads", Untrusted: rest + " (sha256 " + v + ")"}) } } + for _, pl := range slices.Sorted(maps.Keys(cached)) { + c.info("%d PHP files under uploads are %s's compiled cache, in its own shape: not flagged", cached[pl], pl) + } switch { case repo == nil: c.problem("no repo to compare with: plugins and PHP files not checked") diff --git a/check_options.go b/check_options.go index edfb8c3..fc6a3a5 100644 --- a/check_options.go +++ b/check_options.go @@ -78,21 +78,32 @@ func (c *checker) sensitive() { } // cron: a scheduled hook on a site that the last audit didn't see, flagged -// until accepted. Backdoors often schedule themselves to come back. +// until accepted. Backdoors often schedule themselves to come back. A hook +// with the prefix of a plugin active on that site is the plugin's own (an +// update adds them), so it's only counted. func (c *checker) cron() { prev := c.in.Prev if prev == nil || prev.Cron == nil { return } + plugins := 0 for _, blog := range slices.Sorted(maps.Keys(c.in.Facts.Site.Cron)) { was, ok := prev.Cron[blog] + active := c.activeFolders(blog) for _, hook := range c.in.Facts.Site.Cron[blog] { id := "cron:" + blog + ":" + idPart(hook) if (!ok || slices.Contains(was, hook)) && c.p.Pending[id] == "" { continue // a site the last audit didn't have: its hooks aren't news } + if ownedHook(active, hook) { + plugins++ + continue + } c.flag(Flag{ID: id, Severity: Review, Kind: KindCron, Message: "scheduled hook new since the last audit", Untrusted: hook + " (site " + blog + ")"}) } } + if plugins > 0 { + c.info("%d new scheduled hooks belong to active plugins (by their prefix, such as Yoast's wpseo_): not flagged", plugins) + } } diff --git a/collector.php b/collector.php index 87264ce..9110e45 100644 --- a/collector.php +++ b/collector.php @@ -639,6 +639,38 @@ function_exists('proc_nice') && @proc_nice(19); } $wpda_timed('content'); +// Documents below uploads that published posts and their fields link to (by +// URL, as page builders and ACF link fields store them): linked on purpose, +// so the exposed check only counts them. Paths are below uploads, a network +// site's with its sites//. Up to $wpda_rows rows a table. +$wpda_linked = []; +empty($wpda_skip['content']) && $wpda_each(function (int $blog) use ($wpdb, $wpda_stream, $wpda_rows, &$wpda_linked, &$wpda_errors) { + $find = function ($v) use (&$wpda_linked) { + if (preg_match_all('~/uploads/((?:sites/\d+/)?[^"\'\s<>?#\\\\]+\.(?:pdf|docx?|xlsx?|pptx?|odt|ods|odp|rtf|csv|txt|zip|rar|7z))~i', (string) $v, $m)) { + foreach ($m[1] as $p) { + $wpda_linked[rawurldecode($p)] = true; + } + } + }; + foreach ([ + 'ID' => "SELECT ID AS wpda_k, post_content FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_type <> 'revision' AND post_content LIKE '%/uploads/%'", + 'm.meta_id' => "SELECT m.meta_id AS wpda_k, m.meta_value FROM {$wpdb->postmeta} m JOIN {$wpdb->posts} p ON p.ID = m.post_id AND p.post_status = 'publish' AND p.post_type <> 'revision' WHERE m.meta_value LIKE '%/uploads/%'", + ] as $key => $sql) { + $err = $wpda_stream($sql, $key, function ($r) use ($find) { + foreach ((array) $r as $k => $v) { + if ($k !== 'wpda_k') { + $find($v); + } + } + }, $wpda_rows); + if ($err !== null && $err !== 'truncated') { + $wpda_errors[] = 'linked uploads: ' . $err; + } + } +}); +$wpda['linked_uploads'] = array_keys($wpda_linked); +$wpda_timed('linked'); + // Files are the hasher's (hasher.php), which runs without WordPress. // Checksums against wordpress.org, for sites whose files can't be compared diff --git a/facts.go b/facts.go index f642208..ab30bb6 100644 --- a/facts.go +++ b/facts.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "io" + "path" "regexp" "strconv" "strings" @@ -107,9 +108,25 @@ type SiteFacts struct { ActivePlugins map[string][]string `json:"active_plugins"` // blog id (or "network") → plugin files ("akismet/akismet.php") Cron map[string][]string `json:"cron"` // blog id → scheduled hook names Sensitive map[string]string `json:"sensitive"` // option (blog-tagged) → its value's hash - Timings map[string]float64 `json:"timings"` // seconds per collector section - PeakMB float64 `json:"peak_mb"` // the PHP process's peak memory, WordPress included - Errors []string `json:"errors"` + // LinkedUploads are the files below uploads that published posts and their + // fields link to (every blog's), as paths below uploads: linked on purpose. + LinkedUploads []string `json:"linked_uploads"` + Timings map[string]float64 `json:"timings"` // seconds per collector section + PeakMB float64 `json:"peak_mb"` // the PHP process's peak memory, WordPress included + Errors []string `json:"errors"` + + linkedSet map[string]bool +} + +// linked is LinkedUploads as a set. +func (s *SiteFacts) linked() map[string]bool { + if s.linkedSet == nil { + s.linkedSet = map[string]bool{} + for _, p := range s.LinkedUploads { + s.linkedSet[path.Clean(p)] = true + } + } + return s.linkedSet } type Registration struct { diff --git a/owned.go b/owned.go new file mode 100644 index 0000000..e8a4c5a --- /dev/null +++ b/owned.go @@ -0,0 +1,115 @@ +package audit + +import ( + "path" + "regexp" + "strings" +) + +// pluginOwn is what a plugin adds of its own while it is active, which the +// checks would otherwise take for tampering: capabilities it gives users +// (a trailing * is a prefix), the prefixes of its scheduled hooks, and the +// compiled PHP it writes under uploads (a pattern of the path below uploads). +type pluginOwn struct { + caps, hooks []string + uploadsPHP *regexp.Regexp +} + +// wpmlTwig is WPML's Twig template cache: cache/wpml/twig//.php, +// the file named by its sha256, its folder by the name's first two digits +// (checked in ownedPHP). +var wpmlTwig = regexp.MustCompile(`^cache/wpml/twig/([0-9a-f]{2})/([0-9a-f]{64})\.php$`) + +// pluginsOwn are the plugins whose own additions are known, by folder. +var pluginsOwn = map[string]pluginOwn{ + "sitepress-multilingual-cms": {caps: []string{"translate", "manage_translations", "wpml_*"}, hooks: []string{"wpml_", "icl_"}, uploadsPHP: wpmlTwig}, + "wpml-string-translation": {caps: []string{"wpml_*"}, hooks: []string{"wpml_"}}, + "wordpress-seo": {hooks: []string{"wpseo"}}, + "wordpress-seo-premium": {hooks: []string{"wpseo"}}, + "woocommerce": {hooks: []string{"woocommerce_", "wc_"}}, + "gravityforms": {hooks: []string{"gravityforms_", "gform_"}}, + "redirection": {hooks: []string{"redirection_"}}, +} + +// activeFolders are the folders of the plugins active on blog ("" for any +// blog), network-activated ones included. +func (c *checker) activeFolders(blog string) map[string]bool { + out := map[string]bool{} + s := c.in.Facts.Site + if s == nil { + return out + } + for b, files := range s.ActivePlugins { + if blog != "" && b != blog && b != "network" { + continue + } + for _, f := range files { + out[strings.SplitN(f, "/", 2)[0]] = true + } + } + return out +} + +// blogTag is a multisite's ":" before a capability from another site. +var blogTag = regexp.MustCompile(`^[0-9]+:`) + +// ownedCap reports whether an active plugin gives cap to users itself. +func ownedCap(active map[string]bool, cap string) bool { + cap = blogTag.ReplaceAllString(cap, "") + for folder, o := range pluginsOwn { + if !active[folder] { + continue + } + for _, p := range o.caps { + if cap == p || strings.HasSuffix(p, "*") && strings.HasPrefix(cap, strings.TrimSuffix(p, "*")) { + return true + } + } + } + return false +} + +// ownedHook reports whether an active plugin schedules hook itself: its +// prefix is the plugin's. The same hook with the plugin inactive is flagged. +func ownedHook(active map[string]bool, hook string) bool { + for folder, o := range pluginsOwn { + if !active[folder] { + continue + } + for _, p := range o.hooks { + if strings.HasPrefix(hook, p) { + return true + } + } + } + return false +} + +// ownedPHP is the active plugin whose compiled cache rest (below uploads) is, +// "" for none: only the exact shape of that cache counts. +func ownedPHP(active map[string]bool, rest string) string { + for folder, o := range pluginsOwn { + if !active[folder] || o.uploadsPHP == nil { + continue + } + m := o.uploadsPHP.FindStringSubmatch(rest) + if m == nil { + continue + } + if o.uploadsPHP == wpmlTwig && !strings.HasPrefix(m[2], m[1]) { + continue + } + return folder + } + return "" +} + +// linkedDoc reports whether rest (below uploads) is a file the site links to +// from published content or post fields (the collector's linked_uploads). +func (c *checker) linkedDoc(rest string) bool { + s := c.in.Facts.Site + if s == nil || len(s.LinkedUploads) == 0 { + return false + } + return s.linked()[path.Clean(rest)] +} diff --git a/owned_test.go b/owned_test.go new file mode 100644 index 0000000..68699e9 --- /dev/null +++ b/owned_test.go @@ -0,0 +1,116 @@ +package audit + +import ( + "strings" + "testing" +) + +const wpmlFile = "sitepress-multilingual-cms/sitepress.php" + +// WPML's translator capabilities aren't injection while WPML is active; the +// rest of a user's extra capabilities still are, and so are WPML's names with +// WPML inactive. +func TestPluginOwnedCaps(t *testing.T) { + s := site0() + s.ActivePlugins = map[string][]string{"1": {wpmlFile}} + s.Users = append(s.Users, + User{ID: 20, Login: "tr", Roles: []string{"editor"}, ExtraCaps: []string{"translate", "manage_translations", "wpml_manage_languages"}}, + User{ID: 21, Login: "mixed", Roles: []string{"editor"}, ExtraCaps: []string{"translate", "manage_options"}}) + r := Check(Input{Facts: Facts{At: now, Site: s}}).Report + caps := kind(r, KindCapabilities) + if len(caps) != 1 || !strings.HasPrefix(caps[0].ID, "caps:21:") || strings.Contains(caps[0].Untrusted, "translate") { + t.Fatalf("capability flags %+v", caps) + } + if !strings.Contains(noteTexts(r), "2 users hold capabilities that active plugins give") { + t.Errorf("notes %s", noteTexts(r)) + } + s.ActivePlugins = nil + if n := len(kind(Check(Input{Facts: Facts{At: now, Site: s}}).Report, KindCapabilities)); n != 2 { + t.Errorf("WPML inactive: %d capability flags, want 2", n) + } +} + +// A new hook with an active plugin's prefix is the plugin's own; the same +// hook without the plugin active is flagged. +func TestPluginOwnedCron(t *testing.T) { + s := site0() + s.ActivePlugins = map[string][]string{"1": {"wordpress-seo/wp-seo.php"}} + s.Cron = map[string][]string{"1": {"wpseo_indexable_index_batch", "evil_hook"}} + prev := &Baseline{Options: s.Options, Cron: map[string][]string{"1": {}}} + r := Check(Input{Facts: Facts{At: now, Site: s}, Prev: prev}).Report + got := ids(r) + if got["cron:1:evil_hook"] != Review || got["cron:1:wpseo_indexable_index_batch"] != "" { + t.Fatalf("cron flags %v", got) + } + if !strings.Contains(noteTexts(r), "1 new scheduled hooks belong to active plugins") { + t.Errorf("notes %s", noteTexts(r)) + } + s.ActivePlugins = nil + if ids(Check(Input{Facts: Facts{At: now, Site: s}, Prev: prev}).Report)["cron:1:wpseo_indexable_index_batch"] != Review { + t.Error("a wpseo_ hook with Yoast inactive went unflagged") + } +} + +// WPML's Twig cache under uploads is counted while WPML is active, only in +// its exact shape; anything else there stays urgent. +func TestPluginOwnedUploadsPHP(t *testing.T) { + hash := strings.Repeat("6a", 32) + f := files("", map[string]string{ + "web/app/uploads/cache/wpml/twig/6a/" + hash + ".php": "aaaa", + "web/app/uploads/cache/wpml/twig/00/" + hash + ".php": "bbbb", // folder isn't its name's start + "web/app/uploads/cache/wpml/twig/6a/shell.php": "cccc", + }) + s := site0() + s.ActivePlugins = map[string][]string{"1": {wpmlFile}} + r := Check(Input{Facts: Facts{At: now, Site: s, Files: f}, Repo: &Repo{LocalWhy: "no install"}}).Report + var flagged []string + for _, fl := range kind(r, KindFile) { + if strings.HasPrefix(fl.ID, "upload-php:") { + flagged = append(flagged, fl.Untrusted) + } + } + if len(flagged) != 2 || strings.Contains(strings.Join(flagged, " "), "/6a/"+hash) { + t.Fatalf("upload-php flags %v", flagged) + } + if !strings.Contains(noteTexts(r), "1 PHP files under uploads are sitepress-multilingual-cms's compiled cache") { + t.Errorf("notes %s", noteTexts(r)) + } + s.ActivePlugins = nil + n := 0 + for _, fl := range kind(Check(Input{Facts: Facts{At: now, Site: s, Files: f}, Repo: &Repo{LocalWhy: "no install"}}).Report, KindFile) { + if strings.HasPrefix(fl.ID, "upload-php:") { + n++ + } + } + if n != 3 { + t.Errorf("WPML inactive: %d upload-php flags, want 3", n) + } +} + +// A downloadable document a published page links to is counted; unlinked, or +// linked with a name that suggests people's data, it's still flagged. +func TestExposedLinkedDocuments(t *testing.T) { + f := &FileFacts{Content: "web/app", Data: []DataFile{ + {Path: "web/app/uploads/brochure.pdf", Size: 1, Mtime: 1}, + {Path: "web/app/uploads/sites/2/price list.pdf", Size: 2, Mtime: 2}, + {Path: "web/app/uploads/stray.pdf", Size: 3, Mtime: 3}, + {Path: "web/app/uploads/customers-2019.pdf", Size: 4, Mtime: 4}, + }} + served := map[string]Answer{} + for _, d := range f.Data { + served[d.Path] = Answer{Status: 200, Type: "application/pdf"} + } + s := site0() + s.LinkedUploads = []string{"brochure.pdf", "sites/2/price list.pdf", "customers-2019.pdf"} + r := Check(Input{Facts: Facts{At: now, Site: s, Files: f, Web: &WebFacts{Base: "https://site.example", Files: served}}}).Report + got := map[string]bool{} + for _, fl := range kind(r, KindExposed) { + got[strings.SplitN(fl.Untrusted, " (", 2)[0]] = true + } + if !got["web/app/uploads/stray.pdf"] || !got["web/app/uploads/customers-2019.pdf"] || got["web/app/uploads/brochure.pdf"] || got["web/app/uploads/sites/2/price list.pdf"] { + t.Fatalf("exposed flags %v", got) + } + if !strings.Contains(noteTexts(r), "2 downloadable documents under uploads that published pages link to") { + t.Errorf("notes %s", noteTexts(r)) + } +}