audit

package module
v0.0.0-...-23de231 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 1, 2026 License: MIT Imports: 29 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

wp-data-audit

A light, read-only security audit of a WordPress site's data, meant to run during monthly maintenance. Two scripts are piped over SSH (nothing is installed or written on the site): a PHP collector through the site's own vendor/bin/wp eval-file -, reading the database with plugins and themes unloaded, and a shell hasher (hasher.sh) that lists the release's PHP files with the server's own find and sha256sum in an empty environment, so no code from the release runs for it. Go compares their facts with a composer install of the deployed commit, the previous run and the flags a person has accepted. No model is involved: a clean site costs nothing to check.

What it can't see past: the collector loads core, mu-plugins, drop-ins and the site's wp-cli, so the report says when any of those differ from the release (its other findings could then be forged); and the site user's shell startup files run before the hasher, so an attacker who has that user's home and targets this tool specifically could still interfere.

It flags:

  • a role anyone can get whose definition grants more than reading
  • accounts with a role the public can't get: new ones or changed roles urgently, email domains outside the staff and client domains. Only customer on WooCommerce sites and the roles a repo's data-audit.json declares are public, so a subscriber on a site without sign-ups is flagged too
  • listed accounts not used in over a year. WordPress keeps no last login, so this is the newest of: a session's login, WooCommerce's or a plugin's last-activity meta, an application password's or WooCommerce REST key's last use, and every earlier audit's (a login seen once is remembered). With none on record, a phpass password hash counts: since WordPress 6.8 (April 2025) a password login rehashes it, so a phpass hash means no password login since then
  • staff-domain accounts whose address isn't on the config's staff_emails (people who left, aliases, shared addresses); a +tag is ignored, so dev@ covers dev+site@
  • capabilities granted outside a user's roles (role injection)
  • open registration, urgently when the default role can do more than read
  • application passwords and WooCommerce REST API keys
  • login sessions of listed accounts from countries outside the allowed list, except allowed IPs (local DB-IP Lite lookup, no IP leaves the machine)
  • changes to siteurl, home and admin_email
  • PHP files under uploads, each urgent; when the server answers 403 for a .php under uploads that doesn't exist (it refuses to run PHP there), one review flag lists them all instead. Plugins, mu-plugins and drop-ins the repo doesn't deploy
  • every PHP file of the release (core, vendor/, plugins including premium ones, mu-plugins, themes, drop-ins) that differs from a composer install of the deployed commit, one flag per package or theme. A file the checkout's install has edited (a formatter run over web/app) is compared with composer.lock's git ref or wordpress.org zip instead. The deployed commit is GitHub's last successful deploy_production.yml run, else Deployer's REVISION file; a checkout a few commits ahead still counts when nothing deployed changed in between. Without a local install it falls back to wordpress.org's checksums for core and wp.org plugins, and checks plugins from a public GitHub package (Packagist's GitHub dist, or a git source on GitHub) against that repo's archive at composer.lock's ref: the zip Composer installs, export-ignore honoured. A changed, added or missing PHP file is flagged like a wordpress.org checksum failure. Each repo and ref is downloaded once, without credentials; its hashes are kept in the user cache folder (wp-data-audit/github/). Not checked, only listed in a note: a package that isn't on GitHub (Satis, premium vendors), one that isn't a public download (private repo), or one that's patched on install (extra.patches, patches.json). Built asset manifests (*.asset.php) are judged by shape on the server instead: pure data (return array(...) of quoted strings) is only counted, anything else is urgent. Wordfence's wflogs/ data files are judged by their first line (exit and __halt_compiler(), so nothing after it runs); its compiled wflogs/rules.php can't be judged and is only counted. vendor/autoload.php is compared with its per-install class suffix masked. Compiled caches, other built build/ files and WordPress's own translation updates can't be compared and are only counted
  • scripts, iframes, javascript: and data: URLs, PHP calls and hidden links in posts, meta, options, terms and approved comments, plain, HTML-escaped (as the classic editor stores an embed; judged as if plain) or hidden in base64 (always urgent)
  • files anyone can download that shouldn't be public: database dumps, backups, archives, logs, keys, .git, and documents and exports (csv, xls*, pdf, doc*, …) in plugin folders under uploads or outside the media library, or anywhere under a name that suggests people's data (customers, members, orders, applications, in English, Finnish and Swedish). The hasher lists only size, date and path; the audit then asks each file's public URL with a HEAD request, so a file a plugin's .htaccess was meant to protect (which nginx ignores) shows as served. Served files and listed folders are urgent, one flag per plugin folder (uploads/wpallexport/exports); risky files the URL doesn't serve are for review, and a media library upload with a telling name only for review. Gravity Forms' debug logs are one review flag per folder, served or not (logging on, or old logs left); their random file names keep a served one from urgent, and a log without that token is judged like any other file. Media library uploads, Gravity Forms entry uploads (not its export/), plugin JSON, code-checker configs (phpcs.xml, phpunit.xml, …), the exact files an active plugin serves on purpose (Complianz's assets and consent PDFs, Product Feed Pro's and CTX Feed's feeds, Rank Math's sitemap cache, WP All Export's scheduled exports; never under a name suggesting people's data, and flagged once the plugin is gone; WP All Import's folder never counts) and the repo's public_uploads are only counted. On a multisite each site's uploads are asked for on that site's own domain
  • what each site's public URL gives away: the REST API listing users, ?author=1 redirecting to a login slug, XML-RPC answering, the uploads folder listed, missing security headers (HSTS, framing, nosniff), a TLS certificate expiring within two weeks. Documentation and test domains (example.com, .test, …) are never asked
  • cookies before consent: the home page is loaded in a headless Chrome with an empty profile, nothing clicked, and every cookie the browser holds 5 s later (any domain's) is flagged unless the repo's necessary_cookies lists it. Tracker cookies (_ga, _fbp, _hj, …) are flagged even when listed. Needs Chrome where the audit runs; without it the check is a problem note
  • personal data kept with no end: Gravity Forms forms with entries over two years old and no retention period, and shops with orders over two years old that never anonymise completed orders. Only counts and dates are collected
  • Gravity Forms forms whose honeypot throws caught submissions away instead of keeping them as spam, and CleanTalk deleting the Gravity Forms entries it judges spam: a real person either catches is lost without a trace

On a multisite every site is covered; facts from sites other than the main one are tagged with their blog id, and network admins show as super_admin.

Users with only public roles are only counted. Content is never copied, only the match (a script's host, an iframe's host, an inline script cut short), so one accepted value is accepted wherever it appears. accept --only-here accepts it only where it appears now (old content nobody adds to): the flag comes back when the value turns up in a new place. Revisions and trashed posts, and their meta, aren't scanned.

Use

From a Bedrock site's checkout at the deployed commit, after composer install (for the file comparison; gh finds the deployed commit):

wp-data-audit geoip-update        # once a month
wp-data-audit                     # audits @production; exit 1 when there are flags
wp-data-audit accept <id>...      # an expected flag stays quiet until what it describes changes
wp-data-audit accepted            # what's been accepted, by whom, when and why
wp-data-audit --env local --wp "ddev wp" --sh "ddev exec sh -s"   # try it on the local copy

The first run lists everything there is (all admins, every embed): accept the expected ones once, and later runs show only what's new or changed.

Choosing what runs, piping, and timing:

wp-data-audit --only exposed,public      # no wp-cli, no hasher for public: nothing on the server runs
wp-data-audit --skip content -v          # -v: each phase's seconds on stderr
wp-data-audit script collector | ssh host 'cd /site && wp eval-file - --skip-plugins --skip-themes' > collected.txt
wp-data-audit --collector collected.txt --hasher hashed.txt   # judge saved outputs (- for stdin)
wp-data-audit --json | jq '.flags[] | select(.severity == "urgent")'

Checks are accounts, options, files, exposed, public, retention and content; skipping one skips its collector section, the hasher or the probes too. A run that skips accounts or options saves no baseline (the next full run must still see what changed since the last one), and its report keeps the skipped checks' flags from the last full run.

A run is a pipeline of what depends on what: the collector, then the public probes (they only need its URLs); the hasher, then the exposed-file probes; and the checkout's install hashed meanwhile. wordpress.org's checksums and GitHub package archives are only fetched when there's no local install to compare with. A site takes about as long as its hasher plus the file probes (a large multisite: about 15 s); -v prints every phase and script section. SIGINT, SIGTERM and SIGHUP stop both scripts (ssh then ends the remote side) and save nothing; state files are written atomically and the state lock is a flock, so a killed run leaves no damage.

Most sites need no settings of their own: the site's own domain counts as the client's email domain (www.client.example → client.example), customer is public where WooCommerce runs, and with registration open so is the default role, while it can do no more than read. The exceptions go in the repo's data-audit.json at the root (not composer.json: Composer's lock hash covers extra): a client email domain that isn't the site's, or a role people get outside core registration (an SSO paywall), a folder or file under uploads that's public on purpose (a product viewer), or a plugin installed but never activated on purpose (another plugin loads it as a library), or an account that logs in from a country outside allowed_countries on purpose (a freelancer abroad), or a strictly necessary cookie the home page sets before consent (a language choice). public_roles keys are a site's host, or its blog id on a multisite; public_uploads are paths below uploads; inactive_plugins are plugin folders; login_countries keys are WordPress user ids (the number in a session:<id>:<country> flag; an id, unlike an email, can't be changed from the site), each with the ISO codes that account may log in from, on top of the allowed ones. Another account from that country is still flagged. necessary_cookies maps a cookie name, or a prefix ending in *, to why it's needed before consent. client_manages_network_sites is for a multisite whose client creates, renames and staffs the network's sites themselves: a site the last audit didn't have brings no option flags, a home or siteurl moving between domains the network already used and an admin_email moving to one of them (or to client_domains) aren't flagged, and neither is a super admin gaining or losing a site's role. A URL moved to any other domain and a new privileged account still are:

{
  "public_roles": { "members.example": ["subscriber"] },
  "client_domains": ["client.example"],
  "public_uploads": ["models/product-3d", "price-list.pdf"],
  "inactive_plugins": ["library-plugin"],
  "login_countries": { "12": ["PK"] },
  "necessary_cookies": { "pll_language": "Polylang's language choice" },
  "client_manages_network_sites": true
}

What's true for every site lives in ~/.config/wp-data-audit/config.json:

{
  "allowed_countries": ["FI", "SE"],
  "allowed_ips": ["198.51.100.7", "203.0.113.0/24"],
  "staff_domains": ["agency.example"]
}

State lives in ~/.local/state/wp-data-audit/<site>/<env>/, owner-only (it holds staff emails and login IPs): the last 12 baselines (only what the next comparison needs: accounts, options, last-seen dates, the site's URLs), the last report, and the accepted flags with who accepted them and why.

As a library

  • runner.Run is one audit, the same for every caller. Give it a runner.Transport: how to pipe a script to the site's wp-cli (with audit.WPArgs) and to a shell in its release (audit.HasherCommand), writing the output to the io.Writer it's handed as it arrives. The runner parses while it's written and fails writes past runner.MaxOutput. Set Target.Deployed (runner.DeployedCommit) when the server has no REVISION file.
  • store is the state the CLI and foreman share: Report, Decisions, Accepted and Accept.
  • Underneath, audit holds the facts (ReadSite, ReadFiles), the checkout (ReadRepo, HashInstall) and the rules (Check, one file per check group); web asks the public URLs.

Flag.Untrusted is text from the site, possibly written by an attacker: show it as data, and keep accepting flags a person's decision.

Licence

MIT. IP geolocation by DB-IP, CC BY 4.0.

Documentation

Overview

Package audit is a light, read-only security audit of a WordPress site: who holds privileged accounts and credentials and where they log in from, PHP files that differ from the deployed release, files anyone can download that shouldn't be public, what the public site gives away, personal data kept with no end, and scripts or iframes in content.

Three sources observe a site (Facts): a PHP collector run through the site's wp-cli (Script), a shell hasher run with the server's own tools (Hasher), and HTTP probes from outside (package web). Check judges them against the last run's Baseline, the site's repo (ReadRepo) and a Policy, and returns a Report and the next Baseline. Nothing here touches the network or calls a model: a clean site costs no tokens.

Index

Constants

View Source
const ContentDir = "web/app"

ContentDir is where a Bedrock repo keeps plugins, mu-plugins and drop-ins.

View Source
const DormantAfter = 365 * 24 * time.Hour

DormantAfter is how long a listed account may go without any sign of use.

View Source
const HasherCommand = "exec /usr/bin/env -i PATH=/usr/bin:/bin /bin/sh -s"

HasherCommand is the remote command to pipe Hasher to, after a `cd` into the release: an empty environment and the system's PATH, so a tool the site user put in ~/bin or exported doesn't stand in for find or sha256sum. (Their shell startup files still run before it over SSH: a determined attacker with the site user's home can still interfere.)

View Source
const MaxCandidates = 300

MaxCandidates caps the files whose public URL is asked about.

View Source
const RetentionAfter = 2 * 365 * 24 * time.Hour

RetentionAfter is how old kept personal data may get before a site without a retention setting is flagged.

View Source
const SettingsFile = "data-audit.json"

SettingsFile is the repo's own audit settings, at its root:

{
    "public_roles": {"members.example": ["subscriber"]},
    "client_domains": ["client.example"],
    "public_uploads": ["models/product-3d", "price-list.pdf"],
    "inactive_plugins": ["library-plugin"],
    "login_countries": {"12": ["PK"]},
    "necessary_cookies": {"pll_language": "Polylang's language choice"}
}

public_roles keys are a site's host or, on a multisite, its blog id. public_uploads are folders or files under uploads served on purpose; inactive_plugins are plugin folders installed but never activated on purpose (another plugin loads them as a library); login_countries are countries beyond the allowed ones that an account, by user id, logs in from on purpose; necessary_cookies are the strictly necessary cookies the home page sets before consent, by name (or a prefix ending in *), each with why; client_manages_network_sites is true on a multisite whose client creates, renames and staffs its network's sites themselves. A file of its own, not composer.json: Composer's lock hash covers `extra`.

View Source
const StateLifespanMin = 366 * 24 * time.Hour

StateLifespanMin is the shortest Gravity Forms state token lifespan that outlives any page cache: a year and a day.

Variables

Groups are every group, in report order.

View Source
var Hasher string

Hasher is the shell script to pipe to HasherCommand in the release: its PHP files and their hashes, and risky data files by name, from the server's own find and sha256sum, so nothing in the release runs (ParseFiles reads its output).

View Source
var WPArgs = []string{"eval-file", "-", "--skip-plugins", "--skip-themes"}

WPArgs are the wp-cli arguments to pipe the collector script to: plugins and themes stay unloaded, so they can't interfere with what it reports.

Functions

func HasUploadsPHP

func HasUploadsPHP(f *FileFacts) bool

HasUploadsPHP reports whether the hasher found PHP under uploads that isn't a silence file: then the probes ask whether the server runs it.

func SameFiles

func SameFiles(dir, rev string) bool

SameFiles reports whether the checkout at dir would install the same PHP files as commit rev: nothing between them touched Composer's files, the patches or web/. Then a production a few commits behind (README or workflow changes since its deploy) is still compared.

func Script

func Script(publicRoles map[string][]string, skip ...Section) (string, error)

Script is the collector: PHP to pipe to `wp` with WPArgs. publicRoles are the roles anyone can get, by site host (or blog id on a multisite): their users are only counted. `customer` is public wherever WooCommerce runs; every other role is listed, so a subscriber on a site without sign-ups is flagged. skip are sections not to run.

func UploadsBlog

func UploadsBlog(p, content string) string

UploadsBlog is the multisite blog id an uploads path belongs to (uploads/sites/<id>/), "" for the main site's.

Types

type AccessFacts

type AccessFacts struct {
	GitHub *GitHubAccess
	Kinsta *KinstaAccess
	Errors []string
}

AccessFacts is who can reach the site's code or server outside WordPress. A nil part wasn't asked (the CLI has no Kinsta key); Errors say what was asked and failed.

type Answer

type Answer struct {
	Status int    `json:"status"`
	Type   string `json:"type,omitempty"`
	Err    string `json:"err,omitempty"`
}

Answer is a URL's HTTP status (0 with Err when the request failed) and Content-Type.

func (Answer) Served

func (a Answer) Served() bool

Served reports whether the URL handed out a file (not an HTML page, which is a 404 page or a redirect target more often than the file).

type AppPassword

type AppPassword struct {
	UUID     string `json:"uuid"`
	Name     string `json:"name"`
	Created  int64  `json:"created"`
	LastUsed int64  `json:"last_used"`
	LastIP   string `json:"last_ip"`
}

type Baseline

type Baseline struct {
	At      time.Time         `json:"at"`
	Home    string            `json:"home"`
	Options map[string]string `json:"options"`
	Users   []BaselineUser    `json:"users"`
	WooKeys []WooKeyRef       `json:"woo_keys"`
	// Sensitive options' value hashes, active plugins and cron hooks, per
	// site. Nil in a baseline from before they were collected: then nothing
	// is "new" against it.
	Sensitive map[string]string   `json:"sensitive"` // not omitempty: an empty one is a baseline, nil isn't
	Plugins   map[string][]string `json:"plugins"`
	Cron      map[string][]string `json:"cron"`
}

Baseline is what the next audit compares with: only the facts a change in is a finding (who holds which roles and credentials, the watched options) and what can't be seen again (when an account was last used). Kept small: the rest of a run's facts aren't saved.

type BaselineUser

type BaselineUser struct {
	ID           int      `json:"id"`
	Roles        []string `json:"roles"`
	Privileged   bool     `json:"privileged"`
	AppPasswords []string `json:"app_passwords"`
	LastSeen     int64    `json:"last_seen,omitempty"`
}

BaselineUser is a listed account. LastSeen is the newest sign of its use any audit saw: a session's login, last-activity meta, an application password's use; a login seen once is remembered.

type Candidate

type Candidate struct {
	DataFile
	Type  string // dump, secret, repo, backup, archive, log, document
	Why   string
	Media bool // a media library upload: public on purpose, only its name is odd
}

Candidate is a file a web server may hand out that shouldn't be public.

func Candidates

func Candidates(f *FileFacts, repo *Repo, site *SiteFacts) (out []Candidate, notes []string)

Candidates are the hasher's data files worth asking the public URL about: anything risky by type, and documents outside the media library (or in it under a name that suggests people's data). Files the checkout's install has at the same path are the release's own; with no install or a checkout at another commit, the files git tracks at the deployed one are (Repo.Tracked), and what Composer installs (plugins, vendor) is only counted. notes say what was only counted. Pure and deterministic: the probes ask about these paths, and the exposed check joins their answers back to them. site (nil when the collector didn't run) says which documents are media library attachments: a site without year/month folders keeps them in uploads' root.

type Checksums

type Checksums struct {
	Core           []string         `json:"core"`
	Plugins        []PluginChecksum `json:"plugins"`
	PluginsSkipped int              `json:"plugins_skipped"`
	Skipped        bool             `json:"skipped"`
}

Checksums are wordpress.org's, fetched only when the release can't be compared with a local install (Skipped otherwise).

type Collaborator

type Collaborator struct {
	Login      string
	Permission string // admin, maintain, push, triage, pull
}
type Cookie struct {
	Name   string `json:"name"`
	Domain string `json:"domain"`
}

Cookie is one cookie a browser held: its name and the domain it was set for (without the leading dot), the site's own or a third party's.

type DataFile

type DataFile struct {
	Path  string
	Size  int64
	Mtime int64
}

DataFile is one DATA line: only what find knows.

type DeployKey

type DeployKey struct {
	ID       int64
	Title    string
	ReadOnly bool
	Created  string
	LastUsed string
}

type Facts

type Facts struct {
	At     time.Time
	Site   *SiteFacts   // the collector: the database through the site's wp-cli
	Files  *FileFacts   // the hasher: the release's files, by the server's own tools
	Web    *WebFacts    // the HTTP probes, from outside
	Access *AccessFacts // who can reach the site outside WordPress
	// WPOrg is wordpress.org's word on the repo's wordpress.org plugins, by
	// slug; nil when it wasn't asked.
	WPOrg map[string]WPOrgPlugin
	// Packages are the GitHub archives of the repo's Packages at composer.lock's
	// refs, by plugin folder; nil when they weren't fetched.
	Packages map[string]PackageFiles
}

Facts is everything one audit observed, from its sources. A nil part didn't run: its checks are reported as not judged.

type FileFacts

type FileFacts struct {
	Revision string            // the deployed commit: the caller's, else Deployer's REVISION
	Content  string            // web/app (Bedrock) or wp-content
	Files    map[string]string // path → sha256
	Silence  map[string]bool
	// Shapes: built asset manifests (*.asset.php) → whether the hasher found
	// them pure data; nil from an older hasher.
	Shapes  map[string]bool
	Data    []DataFile
	Errors  []string
	Timings map[string]float64 // seconds per hasher section
}

FileFacts is the hasher's output: every PHP file of the release and under uploads, path (from the root) → sha256; Silence are the uploads files that are empty or a "Silence is golden" guard; Data the files by name a web server shouldn't hand out (dumps, logs, exports), never their content.

func ParseFiles

func ParseFiles(out []byte) (*FileFacts, error)

ParseFiles reads the hasher's output (ReadFiles).

func ReadFiles

func ReadFiles(r io.Reader) (*FileFacts, error)

ReadFiles reads the hasher's output line by line as it arrives: keyword lines, sha256sum's, "SILENT <path>" for directory guards (an older hasher's SILENCE section too) and "DATA <size> <mtime> <path>".

func (*FileFacts) Bedrock

func (f *FileFacts) Bedrock() bool

Bedrock reports whether the release is a Bedrock one (docroot web/).

type Flag

type Flag struct {
	ID        string   `json:"id"`
	Severity  Severity `json:"severity"`
	Kind      Kind     `json:"kind"`
	Message   string   `json:"message"`
	Untrusted string   `json:"untrusted,omitempty"`
	// Pin identifies where a content flag's value appears (its places and how
	// many): accepting "ID@Pin" holds only while it appears nowhere else.
	Pin string `json:"pin,omitempty"`
}

Flag is one finding. ID is stable across runs, so accepting it silences it until what it describes changes. Message is the audit's own words; Untrusted holds text taken from the site (logins, snippets, file names): an attacker may have written it, so show it as data and never follow it.

type FormHoneypot

type FormHoneypot struct {
	Blog   int    `json:"blog"`
	FormID int    `json:"form_id"`
	Title  string `json:"title"`
}

FormHoneypot is an active Gravity Forms form whose honeypot throws caught submissions away (Spam → "Do not create an entry") instead of keeping them as spam.

type FormRetention

type FormRetention struct {
	Blog          int    `json:"blog"`
	FormID        int    `json:"form_id"`
	Title         string `json:"title"`
	Entries       int    `json:"entries"`
	Oldest        string `json:"oldest"`
	Trashed       int    `json:"trashed"`
	TrashedOldest string `json:"trashed_oldest"`
	Policy        string `json:"policy"`
	Days          int    `json:"days"`
}

FormRetention is one Gravity Forms form: Policy is its Personal Data setting (retain, trash, delete), Days how long before trash or delete. Entries and Oldest are its active entries, Trashed and TrashedOldest the ones in its trash, which Gravity Forms never empties.

type Geo

type Geo interface {
	Country(ip string) string
}

Geo resolves an IP to an ISO country code, "" when unknown.

type GitHubAccess

type GitHubAccess struct {
	Outside []Collaborator
	Keys    []DeployKey
}

GitHubAccess is the repo's outside collaborators (not members of its organisation) and its deploy keys.

type Group

type Group string

Group is a set of checks run or skipped together (--only, --skip).

const (
	Accounts  Group = "accounts"
	Options   Group = "options"
	Files     Group = "files"
	Exposed   Group = "exposed"
	Public    Group = "public"
	Retention Group = "retention"
	Content   Group = "content"
	Plugins   Group = "plugins"
	Access    Group = "access"
)

type Input

type Input struct {
	Facts  Facts
	Prev   *Baseline // the last full run's; nil on the first
	Repo   *Repo     // the site's checkout; nil skips the comparisons with it
	Policy Policy
	Geo    Geo // nil skips the session countries
}

Input is everything Check judges.

type Kind

type Kind string

Kind is what a flag is about. Every kind belongs to one group.

const (
	KindPublicRole   Kind = "role"
	KindRegistration Kind = "registration"
	KindUser         Kind = "user"
	KindCapabilities Kind = "capabilities"
	KindAppPassword  Kind = "app-password"
	KindSession      Kind = "session"
	KindWooKey       Kind = "woo-key"
	KindDormant      Kind = "dormant"
	KindLeaver       Kind = "leaver"
	KindOption       Kind = "option"
	KindFile         Kind = "file"
	KindRelease      Kind = "release"
	KindChecksum     Kind = "checksum"
	KindExposed      Kind = "exposed"
	KindPublic       Kind = "public"
	KindRetention    Kind = "retention"
	KindContent      Kind = "content"
	KindCron         Kind = "cron"
	KindPlugin       Kind = "plugin"
	KindCollaborator Kind = "collaborator"
	KindDeployKey    Kind = "deploy-key"
	KindKinstaUser   Kind = "kinsta-user"
	KindSFTP         Kind = "sftp"
)

func (Kind) Group

func (k Kind) Group() Group

Group is the group k belongs to.

type KinstaAccess

type KinstaAccess struct {
	Users []KinstaUser
	SFTP  []SFTPAccount
}

KinstaAccess is the Kinsta company's users who reach this site (company roles reach every site) and the extra SFTP accounts of its environments.

type KinstaUser

type KinstaUser struct {
	Email string
	Role  string // company-admin, company-developer, site-admin, ...
	Scope string // company or site
}

type Listing

type Listing struct {
	Listed bool   `json:"listed"`
	Err    string `json:"err,omitempty"`
}

type Location

type Location struct {
	Blog  int    `json:"blog"`
	Table string `json:"table"`
	ID    int64  `json:"id"`
	Field string `json:"field"`
	Key   string `json:"key"`
}

type Match

type Match struct {
	Kind    string     `json:"kind"`
	Hash    string     `json:"hash"`
	Snippet string     `json:"snippet"`
	Encoded bool       `json:"encoded"` // hidden in base64: obfuscation
	Escaped bool       `json:"escaped"` // HTML entities or URL encoding, as editors store markup
	Count   int        `json:"count"`
	At      []Location `json:"at"`
}

Match is one suspicious value found in content: Hash identifies kind and value, so the same script or iframe host is one flag wherever it appears. Count is how often it appears, At the first few places.

type Note

type Note struct {
	Group   Group  `json:"group,omitempty"`
	Problem bool   `json:"problem,omitempty"`
	Text    string `json:"text"`
}

Note is something the report says besides flags. A Problem is a check that didn't run or couldn't finish; the rest is information (what was counted or left out on purpose).

func (*Note) UnmarshalJSON

func (n *Note) UnmarshalJSON(b []byte) error

UnmarshalJSON also reads a report saved before notes had a group: a plain string, which then said what didn't run.

type OrphanUploads

type OrphanUploads struct {
	Blog   int    `json:"blog"`
	FormID int    `json:"form_id"`
	Files  int    `json:"files"`
	Bytes  int64  `json:"bytes"`
	Oldest string `json:"oldest"`
	Tmp    bool   `json:"tmp,omitempty"`
}

OrphanUploads is one form's upload files that no entry references; Tmp, its tmp/ files over 30 days old: uploads of submissions never finished, on a form nobody has submitted since.

type Package

type Package struct {
	Name, Repo, Ref string
	Release         string
	Patched         bool
}

Package is a plugin's Composer package, its GitHub repo and composer.lock's ref there, and whether a patch is applied to it on install. Release is the release asset ("<tag>/<file>.zip") composer.lock installs it from, when its dist is one: a zip its release workflow built, which can leave files out that the repo's archive at the ref has (tests, say).

type PackageFiles

type PackageFiles struct {
	Files map[string]string `json:"files,omitempty"`
	Err   string            `json:"err,omitempty"`
}

PackageFiles is a package's archive as Composer installs it: its files (path in the package → sha256), or Err when it couldn't be fetched.

type PluginChecksum

type PluginChecksum struct {
	Plugin  string `json:"plugin"`
	File    string `json:"file"`
	Message string `json:"message"`
}

type Policy

type Policy struct {
	AllowedCountries []string // ISO codes; empty skips the session country check
	AllowedIPs       []string // IPs or CIDR ranges never flagged, whatever their country
	StaffDomains     []string // email domains of the people who run the sites
	StaffEmails      []string // the current staff's addresses; empty skips the leaver check
	Skip             Skip
	Accepted         map[string]bool // flag IDs a person accepted
	// Pending are the last report's flags, ID → severity. A finding a change
	// raised (an option's new value, a new admin) stays flagged, and urgent,
	// until accepted, however often the audit runs in between. Any other
	// flag's severity is today's rules'.
	Pending map[string]Severity
}

Policy is what's true beyond the site's own facts and repo: who runs the sites, from where, which checks to run, and what a person decided.

type PublicSite

type PublicSite struct {
	Home       string    `json:"home"`
	Err        string    `json:"err,omitempty"` // the home page didn't answer
	Users      []string  `json:"users,omitempty"`
	AuthorSlug string    `json:"author_slug,omitempty"`
	XMLRPC     bool      `json:"xmlrpc"`
	Listing    bool      `json:"uploads_listing"`
	Headers    []string  `json:"missing_headers,omitempty"`
	CertExpiry time.Time `json:"cert_expiry,omitzero"`
	Trackers   []string  `json:"trackers_before_consent,omitempty"`
	Cookies    []Cookie  `json:"cookies_before_consent,omitempty"`
	BrowserErr string    `json:"browser_err,omitempty"`
}

PublicSite is one home URL's answers. Users are the REST API's user slugs (empty when it doesn't list them); AuthorSlug is where ?author=1 redirects; Trackers are the trackers its landing page starts before any consent; Cookies the cookies a fresh browser holds once the landing page has loaded and nothing was clicked (BrowserErr when the browser couldn't load it).

type Registration

type Registration struct {
	Open     bool     `json:"users_can_register"`
	Role     string   `json:"default_role"`
	RoleCaps []string `json:"default_role_caps"`
}

type Repo

type Repo struct {
	Plugins, MuPlugins, Dropins map[string]bool
	PatchedPlugins              map[string]bool
	PatchedCore                 bool
	PublicRoles                 map[string][]string
	ClientDomains               []string
	// PublicUploads are folders or files under uploads ("models/product-3d",
	// or "sites/2/…" on a multisite) whose documents are public on purpose.
	PublicUploads []string
	// InactivePlugins are plugin folders installed but inactive on purpose.
	InactivePlugins []string
	// LoginCountries are ISO codes, by user id ("12"), an account logs in
	// from on purpose beyond the policy's allowed countries.
	LoginCountries map[string][]string
	// NecessaryCookies are cookie names (or prefixes ending in *) the home
	// page sets before consent on purpose, each with why.
	NecessaryCookies map[string]string
	// ClientManagesNetworkSites: on a multisite, the client creates, renames
	// and staffs the network's sites, so a new site's options, URL moves
	// within the network's domains and a super admin's roles aren't news.
	ClientManagesNetworkSites bool
	// WPOrgPlugins are the wordpress.org slugs of the plugins it deploys
	// from wordpress.org (wp-plugin/ or wpackagist-plugin/ packages).
	WPOrgPlugins []string
	// Revision is the checkout's commit; Local its composer install's PHP
	// files hashed like the server's (nil, with LocalWhy, when there's none).
	Revision string
	Local    map[string]string
	LocalWhy string
	// Dir is the checkout when it has a composer install (Has).
	Dir string
	// Tracked are the files git tracks at TrackedAt: the checkout's commit
	// (ReadRepo), or the deployed one when the checkout is at another
	// (LoadTracked). What the release ships from the repo itself, whatever
	// the working tree holds.
	Tracked   map[string]bool
	TrackedAt string
	// Sources are the unpatched plugins and mu-plugins it installs from a
	// GitHub repo, by folder ("web/app/plugins/x"): composer.lock's ref of
	// each, for a file the checkout's install doesn't match (AtLock).
	Sources map[string]Source
	// WPOrgZips are the unpatched plugins and mu-plugins it installs from a
	// wordpress.org zip, by folder: composer.lock's dist URL, for a file the
	// checkout's install doesn't match (AtLock).
	WPOrgZips map[string]string
	// Packages are the plugins it installs from a Composer package other
	// than wordpress.org's, by folder: where composer.lock's version is on
	// GitHub (Repo "" when it isn't), for checksums when there's no install.
	Packages map[string]Package
	// contains filtered or unexported fields
}

Repo is what the site's repo says: what it deploys (plugin, mu-plugin and drop-in names, and what carries a patch, whose checksums are expected to fail) and its SettingsFile: the roles anyone can get per site and the client's email domains.

func ReadRepo

func ReadRepo(dir string) (*Repo, error)

ReadRepo reads a Bedrock checkout: what it deploys (Composer packages by their installer path, plus what git tracks under web/app) and its SettingsFile. The checkout should be at the deployed commit: a branch that adds or drops a plugin shows up as a flag. Local stays nil until HashInstall.

func (*Repo) AtLock

func (r *Repo) AtLock(p, sum string) bool

AtLock reports whether p, a file of one of the Sources or WPOrgZips, has sha256 sum at its package's composer.lock ref or zip. The checkout's install can be a copy that was edited by hand (worktrees clone it from the main checkout, a formatter run over web/app reformats it, and Composer doesn't reinstall a version it already has); the lock is what deploys ship.

func (*Repo) Comparable

func (r *Repo) Comparable(deployed string) bool

Comparable reports whether the release can be compared with the local install: there is one, at the deployed commit or at one that installs the same files.

func (*Repo) Has

func (r *Repo) Has(p string) bool

Has reports whether the checkout's install has a file at path p (from the root): a data file it has is the release's own (a plugin's sample CSV).

func (*Repo) HashInstall

func (r *Repo) HashInstall()

HashInstall hashes the composer install's PHP files like the server's, for the release comparison (Local). It's the slow part of reading a checkout, so it's separate: a run hashes while the site's scripts run, and one that skips the file checks doesn't hash at all.

func (*Repo) LoadTracked

func (r *Repo) LoadTracked(rev string)

LoadTracked reads the files git tracks at commit rev (one ls-tree), for a checkout that isn't at it, else GitHub's tree of that commit (gh, read only) when the checkout hasn't fetched it. Neither leaves Tracked nil: nothing is fetched into the checkout.

func (*Repo) Mentions

func (r *Repo) Mentions(names []string) map[string]bool

Mentions are the names among names that a PHP file of the checkout's install quotes ('name' or "name"): a scheduled hook its own code (a plugin, a package, the theme) schedules. Uploads, node_modules and .git are skipped.

type Report

type Report struct {
	Flags  []Flag  `json:"flags"`
	Notes  []Note  `json:"notes"`
	Judged []Group `json:"judged"`
}

Report is one audit's result. Judged are the groups it checked: a group that was skipped, or whose source didn't run, has no say in Flags.

func (Report) Merge

func (r Report) Merge(prev Report) Report

Merge keeps prev's flags for the groups r didn't judge, so a partial run (one check, or one whose collector failed) doesn't drop what the last full run found.

func (Report) Problems

func (r Report) Problems() []Note

Problems are the notes about checks that didn't run or finish.

func (Report) Text

func (r Report) Text(title string) string

Text is the report for people: one block per flag, site data quoted, then what didn't run and what was only counted.

func (Report) Urgent

func (r Report) Urgent() int

Urgent counts the urgent flags.

type Result

type Result struct {
	Report   Report
	Baseline *Baseline
}

Result is Check's verdict. Baseline is the next run's, nil when this run didn't judge both accounts and options (a partial run must not hide a change from the next full one).

func Check

func Check(in Input) Result

Check judges in: every group that isn't skipped and whose sources ran.

type RetentionFacts

type RetentionFacts struct {
	Forms    []FormRetention `json:"forms"`
	Woo      []WooRetention  `json:"woo"`
	Honeypot []FormHoneypot  `json:"honeypot"`
	// CleanTalkDeletes are the blogs where CleanTalk deletes the Gravity
	// Forms entries it judges spam (its "save spam" setting off).
	CleanTalkDeletes []int `json:"cleantalk_deletes"`
	// StateLifespan is, per blog with Gravity Forms active, how long its
	// state token stays valid as mu-plugins set it (gform_state_lifespan).
	StateLifespan []StateLifespan `json:"state_lifespan"`
	// OrphanUploads are, per form, Gravity Forms upload files no entry
	// references; UploadHosts the entries' upload links on another host than
	// the uploads URL, whose files Gravity Forms won't delete with the entry.
	OrphanUploads []OrphanUploads `json:"orphan_uploads"`
	UploadHosts   []UploadHost    `json:"upload_hosts"`
	// TmpPending are, per blog, the uploads of unfinished submissions in the
	// forms' tmp/ folders under 30 days old, which Gravity Forms deletes on
	// the form's next submission.
	TmpPending []TmpPending `json:"tmp_pending"`
}

RetentionFacts is how long personal data is kept: counts, dates and settings.

type SFTPAccount

type SFTPAccount struct {
	Env        string // live, staging
	Username   string
	Root       string
	Active     bool
	Permission string // read or write
}

type Section

type Section string

Section is a slow part of the collector that can be left out.

const (
	SectionContent   Section = "content"
	SectionRetention Section = "retention"
	SectionChecksums Section = "checksums" // wordpress.org's, one download per plugin
)

type Session

type Session struct {
	IP         string `json:"ip"`
	UA         string `json:"ua"`
	Login      int64  `json:"login"`
	Expiration int64  `json:"expiration"`
}

type Severity

type Severity string

Severity is how soon a flag needs a person: Urgent is worth a ping now, Review goes in the maintenance report.

const (
	Urgent Severity = "urgent"
	Review Severity = "review"
)

type SiteFacts

type SiteFacts struct {
	Version          int                 `json:"version"`
	Home             string              `json:"home"`
	WPVersion        string              `json:"wp_version"`
	WooCommerce      bool                `json:"woocommerce"`
	Multisite        bool                `json:"multisite"`
	Options          map[string]string   `json:"options"` // siteurl, home, admin_email, blog-tagged ("2:home")
	Registration     Registration        `json:"registration"`
	RoleCounts       map[string]int      `json:"role_counts"`
	PublicRoleCaps   map[string][]string `json:"public_role_caps"` // what each public role (blog-tagged) grants
	Users            []User              `json:"users"`
	WooKeys          []WooKey            `json:"woo_keys"`
	Content          []Match             `json:"content"`
	ContentTruncated bool                `json:"content_truncated"`
	Checksums        Checksums           `json:"checksums"`
	Retention        RetentionFacts      `json:"retention"`
	InstalledPlugins []string            `json:"installed_plugins"` // the plugin folder's entries: folders and single-file plugins
	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
	CronCore         map[string][]string `json:"cron_core"`         // blog id → those a core function handles
	Sensitive        map[string]string   `json:"sensitive"`         // option (blog-tagged) → its value's hash
	// 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"`
	// MediaFiles are the documents below uploads that are media library
	// attachments (every blog's _wp_attached_file, as paths below uploads):
	// uploaded on purpose, wherever the site keeps its uploads.
	MediaFiles []string           `json:"media_files"`
	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"`
	// contains filtered or unexported fields
}

SiteFacts is what the collector printed.

func ParseSite

func ParseSite(out []byte) (*SiteFacts, error)

ParseSite reads the collector's output, ignoring anything printed around it (wp-cli's notices, a shell's banner).

func ReadSite

func ReadSite(r io.Reader) (*SiteFacts, error)

ReadSite reads the collector's output as it arrives: the JSON after WPDA-BEGIN is decoded straight from r, never held whole as text.

type Skip

type Skip map[Group]bool

Skip is the set of groups not to run.

func ParseSkip

func ParseSkip(only, skip string) (Skip, error)

ParseSkip turns --only and --skip (comma-separated group names) into the groups not to run.

func (Skip) Needs

func (s Skip) Needs() (collector, hasher, web bool)

Needs says which sources the groups that run need: the collector (the database), the hasher (the release's files) and the web probes.

func (Skip) Runs

func (s Skip) Runs(g Group) bool

Runs reports whether g isn't skipped.

type Source

type Source struct{ Repo, Ref string }

Source is a package's GitHub repo ("owner/name") and composer.lock's ref.

type StateLifespan

type StateLifespan struct {
	Blog    int `json:"blog"`
	Seconds int `json:"seconds"`
}

StateLifespan is one blog's Gravity Forms state token lifespan.

type TmpPending

type TmpPending struct {
	Blog  int `json:"blog"`
	Files int `json:"files"`
}

TmpPending is one blog's count of recent unfinished-submission uploads.

type UploadHost

type UploadHost struct {
	Blog       int    `json:"blog"`
	Host       string `json:"host"`
	Links      int    `json:"links"`
	UploadHost string `json:"upload_host"`
}

UploadHost is a host other than the uploads URL's that entries' upload links use, and how many links.

type User

type User struct {
	ID           int           `json:"id"`
	Login        string        `json:"login"`
	Email        string        `json:"email"`
	Registered   string        `json:"registered"`
	Roles        []string      `json:"roles"`
	Privileged   bool          `json:"privileged"`
	ExtraCaps    []string      `json:"extra_caps"`
	Sessions     []Session     `json:"sessions"`
	AppPasswords []AppPassword `json:"app_passwords"`
	LastActive   int64         `json:"last_active"` // WooCommerce's or a plugin's last-activity meta
	Hash         string        `json:"hash"`        // the password hash's scheme: wp-bcrypt, phpass, md5, bcrypt, other
}

User is a user holding a role outside the site's public roles, a capability outside their roles, or an application password. On a multisite, roles and capabilities from sites other than the main one are prefixed "<blog id>:"; network admins have the role super_admin. Privileged is set when any role isn't public.

type WPOrgPlugin

type WPOrgPlugin struct {
	Closed      bool   `json:"closed,omitempty"`
	Reason      string `json:"reason,omitempty"`
	ClosedDate  string `json:"closed_date,omitempty"`
	LastUpdated string `json:"last_updated,omitempty"` // "2006-01-02"
	Err         string `json:"err,omitempty"`
}

WPOrgPlugin is what wordpress.org says about a plugin: closed (with why and when), or its last release's date. Err when it couldn't be asked.

type WebFacts

type WebFacts struct {
	Base     string             `json:"base"`     // the docroot's URL; "" when none was known, so nothing was asked
	Files    map[string]Answer  `json:"files"`    // a candidate's path → its URL's answer
	Listings map[string]Listing `json:"listings"` // a candidate's folder → whether it's listed
	Sites    []PublicSite       `json:"sites"`
	// UploadsPHP is the answer for a .php under uploads that doesn't exist,
	// asked when PHP files are there: 403 means the server refuses to run PHP
	// in uploads. Nil when not asked.
	UploadsPHP *Answer `json:"uploads_php,omitempty"`
}

WebFacts is what the site's public URLs answered.

type WooKey

type WooKey struct {
	Blog         int    `json:"blog"`
	ID           int    `json:"key_id"`
	UserID       int    `json:"user_id"`
	Description  string `json:"description"`
	Permissions  string `json:"permissions"`
	TruncatedKey string `json:"truncated_key"`
	LastAccess   string `json:"last_access"`
}

type WooKeyRef

type WooKeyRef struct {
	Blog int `json:"blog"`
	ID   int `json:"id"`
}

type WooRetention

type WooRetention struct {
	Blog     int               `json:"blog"`
	Orders   int               `json:"orders"`
	Oldest   string            `json:"oldest"`
	Settings map[string]string `json:"settings"`
}

WooRetention is one shop: Settings are WooCommerce's Accounts & Privacy retention options ("6 months", "" when off).

Directories

Path Synopsis
cmd
wp-data-audit command
Command wp-data-audit runs the audit from a site's checkout over its wp-cli alias.
Command wp-data-audit runs the audit from a site's checkout over its wp-cli alias.
Package geo looks up IP countries in a local DB-IP Lite database, so no IP leaves the machine.
Package geo looks up IP countries in a local DB-IP Lite database, so no IP leaves the machine.
Package ghzip fetches the zip Composer installs a GitHub package from and hashes its files: the repo's archive at a ref (export-ignore'd files left out), or the release asset composer.lock names as its dist.
Package ghzip fetches the zip Composer installs a GitHub package from and hashes its files: the repo's archive at a ref (export-ignore'd files left out), or the release asset composer.lock names as its dist.
Package runner is one audit end to end, however the caller reaches the site: Run takes a Transport (how to pipe a script to the site's wp-cli and to a shell in its release) and does the rest the same way for every caller: read the checkout, run both scripts and the probes that depend on them as a pipeline, judge, and save to the store the CLI and foreman share.
Package runner is one audit end to end, however the caller reaches the site: Run takes a Transport (how to pipe a script to the site's wp-cli and to a shell in its release) and does the rest the same way for every caller: read the checkout, run both scripts and the probes that depend on them as a pipeline, judge, and save to the store the CLI and foreman share.
Package store keeps the audit's state on disk: per site environment its baselines, last report and accepted flags, and the flags accepted on every site.
Package store keeps the audit's state on disk: per site environment its baselines, last report and accepted flags, and the flags accepted on every site.
web
Package web asks a site's public URLs what they give away, from outside: whether files that shouldn't be public are served, folders listed, users listed, XML-RPC open, headers missing, the certificate about to expire, trackers starting before consent.
Package web asks a site's public URLs what they give away, from outside: whether files that shouldn't be public are served, folders listed, users listed, XML-RPC open, headers missing, the certificate about to expire, trackers starting before consent.
browser
Package browser loads a page the way a first-time visitor's browser does, in a headless Chrome with an empty profile, and reports the cookies the browser holds afterwards: every domain's, as nothing was clicked, so nothing was consented to.
Package browser loads a page the way a first-time visitor's browser does, in a headless Chrome with an empty profile, and reports the cookies the browser holds afterwards: every domain's, as nothing was clicked, so nothing was consented to.
Package wporg asks wordpress.org's plugin API whether plugins are closed, and when each last had a release.
Package wporg asks wordpress.org's plugin API whether plugins are closed, and when each last had a release.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL