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
10 changes: 10 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,13 @@ updates:
directory: /
schedule:
interval: weekly
- package-ecosystem: composer
directory: /tools/security
schedule:
interval: weekly
- package-ecosystem: docker
directories:
- /tools/security
- /tools/security/semgrep
schedule:
interval: weekly
40 changes: 40 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: CodeQL

on:
push:
branches: [main]
pull_request:
schedule:
- cron: '23 5 * * 1'
workflow_dispatch:

permissions:
contents: read

jobs:
analyze:
name: Analyze (${{ matrix.language }})
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
# CodeQL does not support PHP.
language: [actions, javascript-typescript, python]
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Initialize CodeQL
uses: github/codeql-action/init@v4
with:
languages: ${{ matrix.language }}
build-mode: none
queries: security-extended
- name: Analyze and upload results
uses: github/codeql-action/analyze@v4
with:
category: '/language:${{ matrix.language }}'
53 changes: 53 additions & 0 deletions .github/workflows/php-security.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
name: PHP security

on:
push:
branches: [main]
pull_request:
schedule:
- cron: '43 5 * * 1'
workflow_dispatch:

permissions:
contents: read

jobs:
php:
name: PHP security (${{ matrix.scanner }})
runs-on: ubuntu-latest
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
scanner: [psalm, phpcs]
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Build PHP scanner environment
run: docker build -t soca-security-php tools/security
- name: Install locked development tools
run: |
docker run --rm -v "$PWD:/app" -w /app/tools/security soca-security-php \
composer validate --strict
docker run --rm -v "$PWD:/app" -w /app/tools/security soca-security-php \
composer install --no-interaction --prefer-dist --no-progress
- name: Verify detection fixtures and scan PHP without network access
run: |
docker run --rm --network none -v "$PWD:/app:ro" -w /app soca-security-php \
sh tools/security/run.sh "${{ matrix.scanner }}"

semgrep:
name: PHP security (Semgrep CE)
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Pull pinned Semgrep CE
run: docker build -t soca-security-semgrep tools/security/semgrep
- name: Verify rule fixtures and scan PHP without network access
run: |
docker run --rm --network none -v "$PWD:/src:ro" -w /src soca-security-semgrep \
sh tools/security/run.sh semgrep
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,7 @@ wp-config.php
node_modules/
__pycache__/
*.pyc

# Development-only security scanners; the plugin's bundled vendor stays tracked.
/tools/security/vendor/
/tools/security/.cache/
31 changes: 31 additions & 0 deletions docs/DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,34 @@ python3 tools/build.py
```

[TESTING.md](TESTING.md) documents the real WordPress, concurrent-request, browser and multisite suites, exact tested profiles and limitations. Test fixtures live outside the installable plugin and must never be deployed to production. `tools/build.py` excludes all test fixtures, runtime databases, credentials and scratch work from release archives.

## PHP security scanning

`.github/workflows/php-security.yml` runs Psalm taint analysis, WordPressCS security sniffs through PHP_CodeSniffer, and Semgrep Community Edition on pull requests, pushes to `main`, weekly, and on manual dispatch. Findings fail the respective job. Scanner output stays in the Actions logs; no scanner account, API token, hosted analysis service, remote ruleset, or report upload is used. Image builds and dependency installation need network access; all fixture checks and production scans run in containers with `--network none` and a read-only repository mount.

Run the same checks locally from the repository root:

```sh
docker build -t soca-security-php tools/security
docker run --rm -v "$PWD:/app" -w /app/tools/security soca-security-php \
composer install --no-interaction --prefer-dist --no-progress
docker run --rm --network none -v "$PWD:/app:ro" -w /app soca-security-php \
sh tools/security/run.sh psalm
docker run --rm --network none -v "$PWD:/app:ro" -w /app soca-security-php \
sh tools/security/run.sh phpcs
docker build -t soca-security-semgrep tools/security/semgrep
docker run --rm --network none -v "$PWD:/src:ro" -w /src soca-security-semgrep \
sh tools/security/run.sh semgrep
```

Podman works with the same commands. PHP tooling uses PHP 8.3; Psalm analyzes the plugin against its PHP 8.1 minimum. Development tools have their own Composer manifest and lockfile under `tools/security`; they do not change the root runtime dependency inventory or the plugin's private dependency loader. Dependabot tracks these Composer packages and scanner container images. To update PHP scanner dependencies deliberately, run `composer update` in that directory using the PHP scanner container, then rerun all three checks.

The checks cover complementary cases:

- **Psalm** follows untrusted request data across files and through the plugin's actual `Support::scalar` wrapper. The WordPress plugin provides types; `PsalmTaintPlugin` loads additional taint models after those type stubs so `wp_unslash` and `sanitize_text_field` preserve taint, HTML escaping removes only HTML taints, HTTP response bodies are untrusted, and `wpdb` query arguments are SQL sinks. Both interpolated SQL and untrusted `prepare` templates are checked.
- **WordPressCS** checks output escaping, validated and sanitized input, nonce verification, prepared SQL, and placeholders. Existing public login and metadata flows have line-specific nonce exceptions with reasons: public callbacks use OAuth state, PKCE and ID-token validation; administrator settings still require a WordPress nonce. The JSON document output has a local HTML-taint exception because it is served as `application/json` with `nosniff`. There is no blanket baseline or disabled security category.
- **Semgrep CE** uses ten committed rule groups in `tools/security/semgrep/php.yml`: runtime PHP evaluation, shell execution, PHP deserialization, disabled TLS verification, weak hashes, request-controlled SQL, untrusted SQL templates, unescaped output, unsafe redirects, and request-controlled includes. It uses the open-source engine with metrics and update checks disabled. These are repository-maintained rules, not a mirror of Semgrep's hosted registry. CE does not provide cross-file analysis; Psalm supplies that complementary check. A local exception covers the login button helper whose URL and label are escaped internally.

Each scanner first checks deliberately unsafe and safe fixtures. Psalm's fixtures verify cross-file HTML, SQL and shell flows, input sanitization without output escaping, database-mode URL escaping, and untrusted HTTP bodies. WordPressCS verifies the core security sniffs and a safe nonce/escaping/prepared-SQL example. Semgrep tests positive and negative examples for every rule group. Fixture checks fail if expected vulnerabilities stop being detected. These files are analyzed only, never executed, and are excluded from the installable ZIP along with all scanner dependencies and configuration.

Extend taint models and fixtures when adding new WordPress wrappers or input/output paths. Static scans do not prove OAuth correctness or authorization policy; keep the protocol and WordPress integration suites in place.
36 changes: 23 additions & 13 deletions simple-oauth-cimd-access/includes/Plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ public static function boot(): void {
add_action('admin_post_nopriv_' . $action, [self::class,$method]);
}
// The button helper escapes its URL and label before returning HTML.
add_action('login_form', static function () { echo self::button(Support::scalar(wp_unslash($_GET), 'redirect_to')); }); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- button() escapes its markup.
// nosemgrep: php-request-to-output -- button() escapes its URL and label; scanned independently by Psalm and WordPressCS.
add_action('login_form', static function () { echo self::button(Support::scalar(wp_unslash($_GET), 'redirect_to')); }); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped,WordPress.Security.NonceVerification.Recommended -- Public login button; no state change. button() escapes its markup.
add_action('login_init', [self::class,'automatic']);
add_filter('login_message', static function ($message) {
if (isset($_GET['soca_error'])) {
$errorRef = sanitize_text_field(wp_unslash($_GET['soca_error'] ?? ''));
if (isset($_GET['soca_error'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only login error display; the reference is validated and escaped.
$errorRef = sanitize_text_field(wp_unslash($_GET['soca_error'] ?? '')); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only login error display; the reference is validated and escaped.
$ref = preg_match('/^[a-f0-9]{12}$/D', $errorRef) ? $errorRef : '';
$message .= '<p class="message">SOCA login did not complete. You can retry or use your local account. An administrator can review the redacted audit events.' . ($ref ? ' Reference: <code>' . esc_html($ref) . '</code>.' : '') . '</p>';
}
Expand Down Expand Up @@ -56,16 +57,25 @@ public static function deactivate(bool $network = false): void {
} else { wp_clear_scheduled_hook('soca_maintenance'); }
}
public static function documents(): void {
if (!isset($_GET['soca_doc'])) { return; }
if (!isset($_GET['soca_doc'])) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only public client metadata and JWKS endpoint.
$method = Support::serverString('REQUEST_METHOD');
if (!in_array($method, ['GET','HEAD'], true)) { status_header(405); exit; }
try {
$kind = Support::scalar(wp_unslash($_GET),'soca_doc');
$kind = Support::scalar(wp_unslash($_GET),'soca_doc'); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only public client metadata and JWKS endpoint; kind is allowlisted.
Support::need(in_array($kind,['client','jwks'],true), 'document', 'Unknown public document.');
$doc = $kind === 'jwks' ? Keys::jwks() : Metadata::document(Settings::get(), true);
header('Content-Type: application/json; charset=utf-8'); header('Cache-Control: public, max-age=300, must-revalidate');
header('X-Content-Type-Options: nosniff'); header('Access-Control-Allow-Origin: *');
if ($method !== 'HEAD') { echo Support::json($doc); } exit; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- JSON response, not HTML.
// The response is application/json with nosniff, never embedded in HTML.
if ($method !== 'HEAD') {
/**
* @psalm-taint-escape html
* @psalm-taint-escape has_quotes
*/
$json = Support::json($doc);
echo $json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- JSON response, not HTML.
}
exit;
} catch (\Throwable $e) { status_header(503); header('Cache-Control: no-store'); header('Content-Type: application/json'); echo '{"error":"metadata_unavailable"}'; exit; }
}
public static function button(string $destination = ''): string {
Expand All @@ -82,8 +92,8 @@ public static function automatic(): void {
$s = Settings::get();
if (!$s['enabled'] || !$s['automatic'] || Settings::disabled() || is_user_logged_in() || Support::serverString('REQUEST_METHOD') !== 'GET') { return; }
// A narrow allowlist preserves recovery, reset, logout, interim, reauth and plugin-specific flows.
if (array_diff(array_keys($_GET), ['redirect_to','action']) || (isset($_GET['action']) && $_GET['action'] !== 'login')) { return; }
wp_safe_redirect(Support::query(admin_url('admin-post.php'), ['action'=>'soca_start','redirect_to'=>Support::destination(Support::scalar(wp_unslash($_GET),'redirect_to'))])); exit;
if (array_diff(array_keys($_GET), ['redirect_to','action']) || (isset($_GET['action']) && $_GET['action'] !== 'login')) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public login initiation; the callback requires one-time OAuth state and PKCE.
wp_safe_redirect(Support::query(admin_url('admin-post.php'), ['action'=>'soca_start','redirect_to'=>Support::destination(Support::scalar(wp_unslash($_GET),'redirect_to'))])); exit; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public login initiation; the callback requires one-time OAuth state and PKCE.
}
private static function rate(string $purpose, int $limit): void {
$address = Support::serverString('REMOTE_ADDR');
Expand Down Expand Up @@ -152,7 +162,7 @@ private static function begin(string $purpose, string $ref, string &$step): void
$tx=['settings'=>$s,'discovery'=>$d,'client'=>Metadata::clientId($s),'callback'=>Metadata::callback(),'kid'=>$keys['active'],
'nonce'=>$nonce,'verifier'=>$verifier,'user_agent'=>self::userAgentHash(),'started'=>time(),'purpose'=>$purpose,'reauth'=>$purpose!=='login',
'user'=>$purpose==='login'?0:get_current_user_id(),'session'=>$purpose==='login'?'':hash('sha256',wp_get_session_token()),
'destination'=>Support::destination(Support::scalar(wp_unslash($_GET),'redirect_to')),'audit_ref'=>$ref];
'destination'=>Support::destination(Support::scalar(wp_unslash($_GET),'redirect_to')),'audit_ref'=>$ref]; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public login destination is restricted to this site before storage and redirect.
Store::createTransaction($state,$tx);
Support::audit('login_started', $purpose==='test' ? get_current_user_id() : 0, ['flow'=>$purpose,'step'=>'redirect','ref'=>$ref]);
$step = 'redirect';
Expand Down Expand Up @@ -182,7 +192,7 @@ public static function callback(): void {
Support::need(strlen($queryString) <= 16384, 'callback_query', 'Callback query is too long.');
$names=[]; foreach (explode('&',$queryString) as $pair) { $name=urldecode(explode('=',$pair,2)[0]); Support::need(!in_array($name,$names,true),'duplicate_parameter','Duplicate callback parameter.'); $names[]=$name; }
$step = 'transaction';
$state=Support::scalar(wp_unslash($_GET),'state',100);
$state=Support::scalar(wp_unslash($_GET),'state',100); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- OAuth callback consumes one-time state bound to the browser transaction.
$tx=Store::consumeTransaction($state,self::userAgentHash());
$ref = is_string($tx['audit_ref'] ?? null) && preg_match('/^[a-f0-9]{12}$/D', $tx['audit_ref']) ? $tx['audit_ref'] : $ref;
$flow = ($tx['purpose'] ?? '') === 'test' ? 'test' : 'login';
Expand All @@ -191,10 +201,10 @@ public static function callback(): void {
$s=Settings::get();
Support::need(!Settings::disabled() && $s['revision']===$tx['settings']['revision'] && ($s['enabled'] || $tx['purpose']!=='login'),'configuration_changed','Configuration changed during login. Start again.');
$step = 'authorization_response';
$iss=Support::scalar(wp_unslash($_GET),'iss');
$iss=Support::scalar(wp_unslash($_GET),'iss'); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- OAuth callback validates the response issuer against the stored provider.
Support::need(($iss==='' && empty($tx['discovery']['authorization_response_iss_parameter_supported'])) || $iss===$tx['settings']['issuer'],'response_issuer','Authorization response issuer mismatch or missing.');
Support::need(!isset($_GET['error']),'provider_denied','Provider cancelled or denied the request.');
$code=Support::authorizationCode(Support::scalar(wp_unslash($_GET),'code'));
Support::need(!isset($_GET['error']),'provider_denied','Provider cancelled or denied the request.'); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- OAuth callback rejects provider errors after consuming one-time state.
$code=Support::authorizationCode(Support::scalar(wp_unslash($_GET),'code')); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- OAuth callback exchanges the code using PKCE and validates the signed ID token.
if ($tx['purpose']!=='login') {
Support::need(get_current_user_id()===$tx['user'] && hash_equals($tx['session'],hash('sha256',wp_get_session_token())),'session','The original authenticated local session is required.');
}
Expand Down
Loading
Loading