Skip to content

fix: harden BCOS directory server defaults - #5273

Merged
Scottcjn merged 1 commit into
Scottcjn:mainfrom
galanime:codex/bcos-directory-safe-defaults
May 15, 2026
Merged

Scottcjn merged 1 commit into
Scottcjn:mainfrom
galanime:codex/bcos-directory-safe-defaults

Conversation

@galanime

@galanime galanime commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

BCOS Checklist

  • Add a tier label: BCOS-L1
  • New test file includes SPDX header
  • Test evidence is included below

What Changed

  • Replaced the public hardcoded BCOS directory Flask SECRET_KEY with BCOS_DIRECTORY_SECRET_KEY, falling back to a per-process random secret.
  • Disabled Flask debug mode by default; it now requires BCOS_DIRECTORY_DEBUG=true.
  • Changed the default development host from 0.0.0.0 to 127.0.0.1, with BCOS_DIRECTORY_HOST and BCOS_DIRECTORY_PORT overrides for operators.
  • Added regression tests covering secret loading, random fallback, debug opt-in, and loopback default.

Root Cause / Impact

Fixes #5272.

The BCOS directory executable entrypoint used app.run(debug=True, host='0.0.0.0', port=5000) and a shared public bcos-directory-dev-key. Running the service as-is could expose the Werkzeug debugger beyond localhost and reuse a known Flask session signing secret across every checkout.

Testing / Evidence

  • /tmp/rustchain-bounty-venv/bin/python -m pytest tests/test_bcos_directory_security.py -q -> 4 passed
  • /tmp/rustchain-bounty-venv/bin/python -m py_compile bcos_directory.py tests/test_bcos_directory_security.py -> passed
  • git diff --check -- bcos_directory.py tests/test_bcos_directory_security.py -> passed
  • python3 tools/bcos_spdx_check.py --base-ref origin/main -> BCOS SPDX check: OK

Bounty / Payout

Bug bounty: #305
Wallet/miner ID: RTC74b80ab40602e5ae31819912b2fca974484e5dab
Requested severity: Medium/High security bug. Conservative expected minimum: 10 RTC.

@github-actions github-actions Bot added BCOS-L1 Beacon Certified Open Source tier BCOS-L1 (required for non-doc PRs) tests Test suite changes size/M PR: 51-200 lines labels May 15, 2026

@weilixiong weilixiong left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔐 Security Audit: PR #5273 – BCOS Directory Server Defaults Hardening

Reviewer: @weilixiong
Focus: Security-impact analysis
Verdict: ✅ APPROVED after thorough hardening


Changes Summary

The PR replaces four hardcoded Flask dev defaults with environment-variable-driven configuration, each with safe fallbacks. I reviewed every changed line plus all unchanged endpoints for remaining risk.


1. 🔴 CRITICAL: Secret Key – Fixed

Before After
SECRET_KEY = \x60bcos-directory-dev-key\x60 (hardcoded, public) Reads BCOS_DIRECTORY_SECRET_KEY env var, falls back to secrets.token_hex(32)

What was wrong: A hardcoded secret key is trivially discoverable from source. If this app ever added flask sessions, signed cookies, or itsdangerous tokens, any attacker who can read the source could forge valid session cookies.

What the fix does:

  • load_secret_key() reads env var BCOS_DIRECTORY_SECRET_KEY for production deployments
  • Falls back to secrets.token_hex(32) → 256-bit random key, generated fresh per process
  • Empty-string env var is treated as "not configured" (the strip() + truthy check correctly handles this)

Missed edge case: In a multi-worker production deployment (gunicorn/uwsgi with >1 worker), each worker generates a different random key when the env var is unset. This is a deployment configuration concern, not a code bug — operators must set BCOS_DIRECTORY_SECRET_KEY for multi-worker setups.


2. 🟠 HIGH: Debug Mode – Fixed

Before After
debug=True (always on) debug=debug_enabled() → checks BCOS_DIRECTORY_DEBUG env var, defaults to False

What was wrong: Flask dev server with debug=True enables the Werkzeug debugger/console, which allows arbitrary code execution via /console when an exception occurs. This was shipped to production by default.

What the fix does:

  • Debug = false by default
  • Opt-in via BCOS_DIRECTORY_DEBUG env var with multiple truthy variants accepted (1, true, yes, on)
  • The .strip().lower() normalization is correct; the set membership check is appropriate

3. 🟡 MEDIUM: Network Exposure – Fixed

Before After
host=\x600.0.0.0\x60 (binds all interfaces) host=server_host() → defaults to 127.0.0.1, configurable via BCOS_DIRECTORY_HOST

What was wrong: Binding to 0.0.0.0 exposes the dev server to the LAN/WAN, even when debug=False. This is unnecessary surface area.

What the fix does:

  • Loopback default keeps the port local-only
  • strip() + falsy fallback correctly handles whitespace-only env var values
  • Explicit opt-in for production deployments that need LAN access

4. ℹ️ LOW: Port Flexibility (Bonus Improvement)

Before After
Hardcoded port=5000 Configurable via BCOS_DIRECTORY_PORT, with int() + ValueError fallback

Minor note: No port range validation (1–65535). Setting BCOS_DIRECTORY_PORT=99999 passes int() but will fail at bind time. Low severity — the OS rejects it harmlessly.


5. Non-Changes (Still Present, Out of Scope)

The following were present before and remain unchanged — noted for awareness, not blocking:

  • render_template_string with user input: tier_filter and category_filter from request.args are passed as Jinja2 template variables. This is NOT exploitable for SSTI because Jinja2 auto-escapes template context variables, and the template string (MAIN_TEMPLATE) is static — not constructed from user input.
  • SQLite DB: No authentication on bcos_directory.db — acceptable for a simple directory service.
  • No input sanitization on DB queries: Parameterized queries are used throughout (? placeholders), so no SQLi risk.

6. PR #5272

No PR #5272 exists in this repo. No cross-reference findings.


Test Coverage Assessment

Test Present Notes
load_secret_key() reads env var ✅ test_bcos_directory_secret_key_uses_environment
load_secret_key() fallback ≠ old constant ✅ test_bcos_directory_secret_key_fallback_is_not_public_constant
Debug defaults to false ✅ test_bcos_directory_debug_requires_explicit_opt_in
Host defaults to loopback ✅ test_bcos_directory_host_defaults_to_loopback
Port edge cases ❌ Missing: invalid port, negative port boundary
Empty BCOS_DIRECTORY_SECRET_KEY edge case ❌ Missing: env var set to empty string
BCOS_DIRECTORY_HOST=\x60\x60 (empty) edge case ❌ Missing

Recommendation for follow-up (minor): Add tests for the three missing edge cases above. Not blocking.


Final Verdict

This PR eliminates three genuine security issues (hardcoded secret key, always-on debug mode, overly-broad network binding) with clean, testable code. No bypass vectors detected, no remaining vulnerability in the changed surface.

✅ APPROVED — Good hardening work.

@TJCurnutte TJCurnutte left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved. I checked the BCOS directory default-hardening path and the operator override behavior.

Validation performed on head 0afcfd81df3ea6601fada1dd0feec690d0c68116:

  • git diff --check origin/main...HEAD -- bcos_directory.py tests/test_bcos_directory_security.py
  • python3 -B -m py_compile bcos_directory.py tests/test_bcos_directory_security.py
  • python3 -m pytest tests/test_bcos_directory_security.py -q → 4 passed, 1 warning in 0.29s (urllib3/LibreSSL warning only)
  • Direct default probe returned: secret_len 64, debug_default False, host_default 127.0.0.1, port_default 5000, debug_yes True, host_blank 127.0.0.1, port_bad 5000

This removes the fixed public Flask secret, stops debug mode from being enabled by default, and avoids accidental 0.0.0.0 exposure while still allowing explicit environment overrides. The fallback secret is generated per process instead of being a shared constant, which is a clear improvement for the dev server default posture.

Looks safe to merge from this review pass.

@jaxint jaxint left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thanks for contributing. Approved.

@JaBi-aka

Copy link
Copy Markdown

Reviewed the BCOS directory hardening diff. The important security defaults are moving in the right direction:

  • The hardcoded Flask SECRET_KEY is removed from the runtime default, so fresh checkouts no longer share a public signing key.
  • Debug mode now requires explicit opt-in through BCOS_DIRECTORY_DEBUG, which avoids accidentally exposing Werkzeug debugger behavior.
  • The default host moves from 0.0.0.0 to 127.0.0.1, which is the right safe default for a Flask development server.
  • Tests cover configured secret loading, randomized fallback shape, debug opt-in, and loopback default.

No blocking findings from this review.

Two follow-up suggestions:

  • Consider documenting that production deployments should set BCOS_DIRECTORY_SECRET_KEY. The random fallback is much safer than a public constant, but it will rotate on every process restart and can invalidate signed sessions/cookies.
  • Consider adding a port validation test for out-of-range values, not just non-integer values. The current fallback handles ValueError, but values like 70000 may still fail later at server startup.

I would not block this PR on either item because the current patch removes the exposed-debug/public-secret risk and improves the default host behavior.

@HCIE2054 HCIE2054 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thanks for contributing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

BCOS-L1 Beacon Certified Open Source tier BCOS-L1 (required for non-doc PRs) size/M PR: 51-200 lines tests Test suite changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] BCOS directory runs Flask debug on all interfaces with public secret

7 participants