You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by as...@apache.org on 2026/04/21 08:23:37 UTC
(tooling-agents) branch main updated: ASVS L1 audit: 2.2.1 (web_input_validation)
This is an automated email from the ASF dual-hosted git repository.
asf-tooling pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-agents.git
The following commit(s) were added to refs/heads/main by this push:
new e682d80 ASVS L1 audit: 2.2.1 (web_input_validation)
e682d80 is described below
commit e682d80ea0498d497fc0af732d44554530bfba75
Author: ASF Tooling Team <ro...@apache.org>
AuthorDate: Tue Apr 21 10:23:32 2026 +0200
ASVS L1 audit: 2.2.1 (web_input_validation)
---
.../steve/d0aa7e9/web_input_validation/2.2.1.md | 335 +++++++++++++++++++++
1 file changed, 335 insertions(+)
diff --git a/repos/apache/ASVS/reports/steve/d0aa7e9/web_input_validation/2.2.1.md b/repos/apache/ASVS/reports/steve/d0aa7e9/web_input_validation/2.2.1.md
new file mode 100644
index 0000000..8de25a4
--- /dev/null
+++ b/repos/apache/ASVS/reports/steve/d0aa7e9/web_input_validation/2.2.1.md
@@ -0,0 +1,335 @@
+# ASVS 2.2.1 Input Validation Security Audit Report
+
+## Executive Summary
+
+- **Repository:** apache/steve
+- **Audit Date:** Apr 21, 2026
+- **Auditor:** Tooling Agents
+- **ASVS Requirement:** 2.2.1 — Verify that input is validated to enforce business or functional expectations for that input. This should either use positive validation against an allow list of values, patterns, and ranges, or be based on comparing the input to an expected structure and logical limits according to predefined rules. For L1, this can focus on input which is used to make specific business or security decisions. For L2 and up, this should apply to all input.
+- **ASVS Level:** 1
+- **ASVS Section:** Input Validation
+- **Files Analyzed:** 20 relevant out of 20 total, 0 skipped
+
+### Finding Summary
+
+| Severity | Count | Description |
+|----------|-------|-------------|
+| **Critical** | 1 | Vote content (votestring) not validated against issue vote type |
+| **High** | 0 | — |
+| **Medium** | 0 | — |
+| **Low** | 0 | — |
+| **Total** | 1 | |
+
+---
+
+## Security Controls Inventory
+
+| Control | Defined Location | Purpose | Coverage Status |
+|---------|-----------------|---------|-----------------|
+| Election ID validation | `load_election()` decorator, `pages.py` ~L148 | Validates election exists before processing routes | Applied to all `<eid>` routes ✓ |
+| Issue ID validation | `load_election_issue()` decorator, `pages.py` ~L171 | Validates issue exists within election | Applied to `<eid>/<iid>` routes ✓ |
+| Date format validation | `_set_election_date()`, `pages.py` ~L76 | Validates ISO date format for election dates | Applied to date-setting endpoints ✓ |
+| Vote type assertion | `election.py` `add_issue()` L199: `assert vtype in vtypes.TYPES` | Enforces allowlist of valid vote types | Applied to issue creation ✓ |
+| Election state assertion | `election.py` various: `assert self.is_editable()` etc. | Enforces state machine for election lifecycle | Applied to state-changing operations ✓ |
+| **Votestring content validation** | `election.py` L229: `### validate VOTESTRING for ISSUE.TYPE voting` | **Should validate vote content against issue type** | **DEFINED as comment, NOT IMPLEMENTED ✗** |
+| Issue existence check on vote submit | `pages.py` ~L429: `if iid not in issue_dict` | Prevents voting on non-existent issues | Applied in `do_vote_endpoint` ✓ |
+| Mayvote eligibility check (vote page) | `pages.py` ~L273: `election.q_find_issues.perform(result.uid, ...)` | Restricts voting to eligible voters | Applied in `vote_on_page` GET only, **NOT in POST** |
+| Authentication decorators | `@asfquart.auth.require({R.committer})` | Enforces authentication on protected routes | Applied to all protected routes ✓ |
+
+---
+
+## Critical File Review
+
+### `v3/server/pages.py` — Web Entry Points
+
+| Endpoint | Method | Input Parameter | Validation Status |
+|----------|--------|----------------|-------------------|
+| `/do-vote/<eid>` | POST | `eid` (URL) | ✓ via `load_election` |
+| `/do-vote/<eid>` | POST | `iid` (form key) | ✓ checked against `issue_dict` |
+| `/do-vote/<eid>` | POST | **votestring** (form value) | **✗ NOT VALIDATED** |
+| `/do-create-election` | POST | `title` (form) | Partial (no length/content check) |
+| `/do-add-issue/<eid>` | POST | `title`, `description` (form) | Partial (no length/content check) |
+| `/do-edit-issue/<eid>/<iid>` | POST | `title`, `description` (form) | Partial (no length/content check) |
+| `/do-set-open_at/<eid>` | POST | `date` (JSON) | ✓ `fromisoformat` + null check |
+| `/do-set-close_at/<eid>` | POST | `date` (JSON) | ✓ `fromisoformat` + null check |
+| `/docs/<iid>/<docname>` | GET | `docname` (URL) | Framework-protected (`send_from_directory`) |
+
+### `v3/steve/election.py` — Business Logic Layer
+
+| Method | Input Parameter | Validation Status |
+|--------|----------------|-------------------|
+| `add_vote()` | `votestring` | **✗ Comment marks as needed, not implemented** |
+| `add_issue()` | `vtype` | ✓ `assert vtype in vtypes.TYPES` |
+| `add_issue()` | `title`, `description` | Partial (no content validation) |
+| `open()` | (state) | ✓ `assert self.is_editable()` |
+| `close()` | (state) | ✓ `assert self.is_open()` |
+| `create()` | `title` | ✗ No validation |
+
+---
+
+## Findings
+
+### Critical Severity
+
+#### ASVS-221-CRT-001: Vote Content (votestring) Not Validated Against Issue Vote Type
+
+**Severity:** CRITICAL
+**Gap Type:** Type B — Control EXISTS (documented intent) but NOT CALLED
+**ASVS Requirement:** 2.2.1 (L1) — Input validation for business-critical decisions
+
+**Location:**
+- **Primary File:** `v3/steve/election.py`
+- **Primary Function:** `add_vote()`
+- **Primary Line:** ~229
+- **Secondary File:** `v3/server/pages.py`
+- **Secondary Function:** `do_vote_endpoint()`
+- **Secondary Lines:** ~410-447
+
+**Related Functions Checked:**
+- `election.py`: `add_vote()`, `q_get_issue`, `json2kv()`
+- `pages.py`: `do_vote_endpoint()`, `load_election()`
+- `vtypes/__init__.py`: `TYPES`, `vtype_module()`
+- `crypto.py`: `create_vote()`
+
+#### Vulnerable Code
+
+**election.py — `add_vote()`:**
+```python
+def add_vote(self, pid: str, iid: str, votestring: str):
+ "Add VOTESTRING as the (latest) vote by PID for IID."
+
+ # The Election should be open.
+ md = self._all_metadata(self.S_OPEN)
+
+ ### validate VOTESTRING for ISSUE.TYPE voting # <── CONTROL DOCUMENTED BUT NOT IMPLEMENTED
+
+ mayvote = self.q_get_mayvote.first_row(pid, iid)
+ vote_token = crypto.gen_vote_token(md.opened_key, pid, iid, mayvote.salt)
+
+ # Pass MAYVOTE.SALT for PBKDF.
+ ciphertext = crypto.create_vote(vote_token, mayvote.salt, votestring)
+
+ self.c_add_vote.perform(vote_token, ciphertext)
+```
+
+**pages.py — `do_vote_endpoint()`:**
+```python
+votes = {}
+for key, value in form.items():
+ if key.startswith('vote-'):
+ iid = key.split('-', 1)[1]
+ votes[iid] = value # <── arbitrary string accepted
+
+for iid, votestring in votes.items():
+ if iid not in issue_dict: # <── IID validated
+ ...
+ try:
+ election.add_vote(result.uid, iid, votestring) # <── votestring NOT validated
+```
+
+#### Data Flow
+
+```
+Source: HTTP POST form field value (e.g., vote-abc123=<attacker_value>)
+ ↓
+pages.py do_vote_endpoint(): extracted from form, IID validated, VALUE NOT validated
+ ↓
+election.py add_vote(): comment marks validation as needed, NOT implemented
+ ↓
+Sink: crypto.create_vote() encrypts and stores arbitrary string as official vote
+ ↓
+tally_issue() decrypts and passes to vtypes tally module with corrupted data
+```
+
+#### Proof of Concept
+
+**For a YNA issue** (valid values: `y`, `n`, `a`):
+```http
+POST /do-vote/a1b2c3d4e5 HTTP/1.1
+Content-Type: application/x-www-form-urlencoded
+Cookie: [valid_session]
+
+vote-f6g7h8i9j0=INVALID_STRING&vote-k1l2m3n4o5=ynaynayna
+```
+
+**For an STV issue** (valid values: comma-separated candidate labels from the issue's `labelmap`):
+```http
+POST /do-vote/a1b2c3d4e5 HTTP/1.1
+Content-Type: application/x-www-form-urlencoded
+Cookie: [valid_session]
+
+vote-p6q7r8s9t0=nonexistent_candidate1,nonexistent_candidate2,duplicate,duplicate
+```
+
+Both requests will be encrypted and stored as valid votes. At tally time, the `vtypes` module will receive these corrupted votestrings, potentially causing:
+- Incorrect tally results (invalid values counted or causing exceptions)
+- Denial of service during tallying (unexpected input to counting algorithms)
+- Duplicate candidate rankings in STV breaking the single-transferable-vote invariant
+
+#### Impact
+
+This is the **core business-critical input** of a voting system. Without server-side validation:
+
+1. **Election integrity compromise**: Arbitrary vote values are encrypted and stored, corrupting the permanent vote record
+2. **Tally corruption**: The `vtypes` tally module receives invalid data — STV algorithms specifically depend on valid candidate labels and unique rankings to function correctly
+3. **Silent corruption**: Because votes are encrypted, invalid values cannot be detected without decrypting all votes during tallying — there is no early warning
+4. **No recovery mechanism**: Once encrypted with per-voter tokens, invalid votes are indistinguishable from valid ones until tally time
+5. **Business continuity risk**: Corrupted votes may cause tally failures, requiring manual intervention or potentially invalidating entire elections
+
+The client-side form constrains YNA to radio buttons (`y`/`n`/`a`) and STV to drag-and-drop from known candidates, but these controls are trivially bypassed via direct HTTP requests.
+
+#### Remediation
+
+**Step 1: Implement validation in `election.py` before encryption:**
+
+```python
+def add_vote(self, pid: str, iid: str, votestring: str):
+ "Add VOTESTRING as the (latest) vote by PID for IID."
+
+ # The Election should be open.
+ md = self._all_metadata(self.S_OPEN)
+
+ # Validate votestring against the issue's vote type
+ issue = self.q_get_issue.first_row(iid)
+ if not issue:
+ raise IssueNotFound(iid)
+
+ vtype_mod = vtypes.vtype_module(issue.type)
+ kv = self.json2kv(issue.kv)
+ if not vtype_mod.validate(votestring, kv):
+ raise InvalidVoteString(iid, issue.type, votestring)
+
+ mayvote = self.q_get_mayvote.first_row(pid, iid)
+ # ... rest of method unchanged
+```
+
+**Step 2: Add validation functions to each vtype module (e.g., `vtypes/yna.py`):**
+
+```python
+VALID_YNA = {'y', 'n', 'a'}
+
+def validate(votestring: str, kv: dict) -> bool:
+ """Validate that votestring is a valid YNA vote."""
+ return votestring in VALID_YNA
+```
+
+**Step 3: For STV (`vtypes/stv.py`):**
+
+```python
+def validate(votestring: str, kv: dict) -> bool:
+ """Validate that votestring contains valid, unique candidate labels."""
+ if not votestring:
+ return False
+ labels = votestring.split(',')
+ valid_labels = set(kv.get('labelmap', {}).keys())
+ # Each label must be valid and appear at most once
+ return (all(label in valid_labels for label in labels)
+ and len(labels) == len(set(labels)))
+```
+
+**Step 4: Add defense-in-depth validation in the web handler (`pages.py`):**
+
+```python
+for iid, votestring in votes.items():
+ if iid not in issue_dict:
+ await flash_danger(f'Invalid issue ID: {iid}')
+ return quart.redirect(f'/vote-on/{election.eid}', code=303)
+
+ # Validate vote content against issue type
+ issue = issue_dict[iid]
+ if issue.vtype == 'yna' and votestring not in ('y', 'n', 'a'):
+ await flash_danger(f'Invalid vote value for issue {issue.title}.')
+ return quart.redirect(f'/vote-on/{election.eid}', code=303)
+ elif issue.vtype == 'stv':
+ labels = set(votestring.split(',')) if votestring else set()
+ valid_labels = set(issue.kv.get('labelmap', {}).keys())
+ if not labels or not labels.issubset(valid_labels):
+ await flash_danger(f'Invalid candidate ranking for {issue.title}.')
+ return quart.redirect(f'/vote-on/{election.eid}', code=303)
+```
+
+---
+
+## Positive Security Patterns
+
+1. **Date validation in `_set_election_date()`**: Properly validates date format using `fromisoformat()` with `try/except` and null check — well-implemented input validation pattern that serves as a model for other validations.
+
+2. **Election/Issue ID existence validation**: The `load_election` and `load_election_issue` decorators consistently validate that database objects exist before proceeding, returning proper 404 responses. This pattern prevents operations on non-existent resources.
+
+3. **Vote type assertion on issue creation**: `assert vtype in vtypes.TYPES` in `add_issue()` enforces the allowlist of valid vote types, preventing arbitrary vote type creation.
+
+4. **State-machine assertions**: Election state transitions are guarded by assertions (`is_editable()`, `is_open()`, `is_closed()`) preventing operations in invalid states, enforcing business logic flow.
+
+5. **EZT template escaping**: The templates use `[format "js,html"]` for values embedded in JavaScript contexts (e.g., `onclick` handlers in `manage.ezt`), showing awareness of context-specific encoding requirements.
+
+6. **`send_from_directory` usage**: File serving uses Quart's `send_from_directory` which internally employs `safe_join` for path traversal protection, preventing directory traversal attacks.
+
+7. **Issue ID validation in vote handler**: The `do_vote_endpoint` validates submitted issue IDs against the election's actual issue list before processing, preventing votes on arbitrary issue IDs.
+
+---
+
+## Architecture Observations
+
+1. **Validation responsibility is split inconsistently**: Date validation happens at the web handler level (`pages.py`), vote type validation happens at the model level (`election.py` via assertion), but vote content validation happens at **neither** level. This inconsistency creates gaps in the security posture.
+
+2. **The `vtypes` module infrastructure exists**: The system references `vtypes.TYPES` and `vtypes.vtype_module()`, providing the natural location for vote content validation functions, but no `validate()` interface is defined or called. This represents missed architectural opportunity.
+
+3. **Assert statements for state validation**: Using Python `assert` for business logic validation is fragile — running with `-O` flag disables all assertions. These should be converted to explicit conditional checks with proper exceptions to ensure protection cannot be disabled.
+
+4. **Defense-in-depth opportunity**: The two-layer architecture (web handlers in `pages.py`, business logic in `election.py`) provides natural defense-in-depth opportunities, but validation is not consistently applied at both layers.
+
+5. **Encryption masks validation gaps**: The immediate encryption of vote data in `add_vote()` means that validation failures cannot be detected post-storage without decryption, making pre-encryption validation critical.
+
+---
+
+## Recommendations Summary
+
+### Immediate (Critical Priority)
+
+1. **Implement votestring validation** in `election.add_vote()` and the `do_vote_endpoint` handler — this is the highest priority as it affects the core business function of the voting system. Add a `validate()` method to each vtypes module (YNA: allowlist of `{y,n,a}`; STV: valid labels from labelmap, uniqueness check) and call it before encryption.
+
+### Short-term (Recommended)
+
+2. **Convert assert-based state checks to explicit validation** — Replace `assert self.is_editable()` patterns with `if not self.is_editable(): raise ElectionBadState(...)` to ensure protection cannot be disabled by Python optimization flags.
+
+3. **Add length and content validation for text fields** — Election titles, issue titles, and descriptions should have maximum length limits and basic content validation to prevent storage abuse and ensure data quality.
+
+### Long-term (Enhancement)
+
+4. **Establish consistent validation architecture** — Define clear guidelines for where validation occurs (web layer vs. business logic layer) and implement defense-in-depth by validating at both layers for critical inputs.
+
+5. **Create validation test suite** — Implement comprehensive tests for all validation functions, including boundary conditions, invalid inputs, and bypass attempts to ensure validation remains effective as the codebase evolves.
+
+---
+
+## Appendix: Files Analyzed
+
+<details>
+<summary>Click to expand full file list (20 files)</summary>
+
+- `v3/server/api.py` (relevance: 10)
+- `v3/server/pages.py` (relevance: 10)
+- `v3/server/templates/about.ezt` (relevance: 10)
+- `v3/server/templates/admin.ezt` (relevance: 10)
+- `v3/server/templates/e_bad_eid.ezt` (relevance: 10)
+- `v3/server/templates/e_bad_iid.ezt` (relevance: 10)
+- `v3/server/templates/e_bad_pid.ezt` (relevance: 10)
+- `v3/server/templates/flashes.ezt` (relevance: 10)
+- `v3/server/templates/footer.ezt` (relevance: 10)
+- `v3/server/templates/header.ezt` (relevance: 10)
+- `v3/server/templates/home.ezt` (relevance: 10)
+- `v3/server/templates/manage-stv.ezt` (relevance: 10)
+- `v3/server/templates/manage.ezt` (relevance: 10)
+- `v3/server/templates/privacy.ezt` (relevance: 10)
+- `v3/server/templates/profile.ezt` (relevance: 10)
+- `v3/server/templates/settings.ezt` (relevance: 10)
+- `v3/server/templates/vote-on.ezt` (relevance: 10)
+- `v3/server/templates/voter.ezt` (relevance: 10)
+- `v3/steve/election.py` (relevance: 10)
+- `v3/steve/persondb.py` (relevance: 10)
+
+</details>
+
+---
+
+**End of Report**
\ No newline at end of file
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org