Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions check_accounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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, ", ")})
Expand All @@ -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,
Expand Down
11 changes: 11 additions & 0 deletions check_exposed.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,13 +207,21 @@ 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") {
owned[p]++
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 {
Expand Down Expand Up @@ -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)
}
Expand Down
10 changes: 10 additions & 0 deletions check_files.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
13 changes: 12 additions & 1 deletion check_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
32 changes: 32 additions & 0 deletions collector.php
Original file line number Diff line number Diff line change
Expand Up @@ -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/<id>/. 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
Expand Down
23 changes: 20 additions & 3 deletions facts.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
"path"
"regexp"
"strconv"
"strings"
Expand Down Expand Up @@ -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 {
Expand Down
115 changes: 115 additions & 0 deletions owned.go
Original file line number Diff line number Diff line change
@@ -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/<ab>/<ab…>.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 "<blog id>:" 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)]
}
Loading
Loading