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/22 07:13:54 UTC

(tooling-agents) branch main updated: ASVS L3 audit: 1.2.10 (input_validation_and_injection)

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 967264e  ASVS L3 audit: 1.2.10 (input_validation_and_injection)
967264e is described below

commit 967264e8d10ae79b5be1d53cbe364c7cdd1e02c6
Author: ASF Tooling Team <ro...@apache.org>
AuthorDate: Wed Apr 22 09:13:49 2026 +0200

    ASVS L3 audit: 1.2.10 (input_validation_and_injection)
---
 .../input_validation_and_injection/1.2.10.md       | 393 +++++++++++++++++++++
 1 file changed, 393 insertions(+)

diff --git a/repos/apache/ASVS/reports/steve/v3/d0aa7e9/input_validation_and_injection/1.2.10.md b/repos/apache/ASVS/reports/steve/v3/d0aa7e9/input_validation_and_injection/1.2.10.md
new file mode 100644
index 0000000..05dca53
--- /dev/null
+++ b/repos/apache/ASVS/reports/steve/v3/d0aa7e9/input_validation_and_injection/1.2.10.md
@@ -0,0 +1,393 @@
+# ASVS 1.2.10 Security Audit Report
+
+## Executive Summary
+
+**Audit Metadata:**
+- **Repository:** apache/steve
+- **Audit Date:** Apr 22, 2026
+- **Auditor:** Tooling Agents
+- **ASVS Requirement:** 1.2.10 — Verify that the application is protected against CSV and Formula Injection. The application must follow the escaping rules defined in RFC 4180 sections 2.6 and 2.7 when exporting CSV content. Additionally, when exporting to CSV or other spreadsheet formats (such as XLS, XLSX, or ODF), special characters (including '=', '+', '-', '@', '\t' (tab), and '\0' (null character)) must be escaped with a single quote if they appear as the first character in a field value.
+- **Files Analyzed:** 23 relevant out of 23 total, 0 skipped
+
+**Finding Summary:**
+
+| Severity | Count | Finding IDs |
+|----------|-------|-------------|
+| Critical | 0 | - |
+| High | 0 | - |
+| Medium | 2 | ASVS-1210-MED-001, ASVS-1210-MED-002 |
+| Low | 0 | - |
+| **Total** | **2** | |
+
+**Key Findings:**
+ASVS 1.2.10 requires protection against CSV and Formula Injection, including proper escaping when exporting CSV/spreadsheet content and sanitization of dangerous leading characters (`=`, `+`, `-`, `@`, `\t`, `\0`). After thorough analysis of the codebase, the application has **no CSV export functionality** in the provided source, and **no defensive controls** (input sanitization or output encoding) against formula injection characters in any user-controllable data path. Given that the vo [...]
+
+---
+
+## Security Controls Inventory
+
+| Control | Defined? | Location | Applied to All Entry Points? | Coverage |
+|---------|----------|----------|------------------------------|----------|
+| CSV Export with RFC 4180 escaping | ❌ No | N/A | N/A | 0% |
+| Formula injection character sanitization on input | ❌ No | N/A | N/A | 0% |
+| Formula injection character escaping on output | ❌ No | N/A | N/A | 0% |
+| CSV-safe export utility function | ❌ No | N/A | N/A | 0% |
+| Vote string format validation | ❌ No (TODO in code) | `election.py:add_vote()` | N/A | 0% |
+
+---
+
+## Critical File Review
+
+### Files Analyzed for CSV/Formula Injection Vectors
+
+| File | Relevance to ASVS 1.2.10 | User-Controllable Data | CSV/Export Path |
+|------|--------------------------|------------------------|-----------------|
+| `v3/server/pages.py` | HIGH - accepts user input for titles, descriptions, votes | Election titles, issue titles/descriptions, vote strings | None found |
+| `v3/steve/election.py` | HIGH - stores data, produces tally results & voter lists | All election/issue/vote data | `tally_issue()`, `get_voters_for_email()` produce exportable tabular data |
+| `v3/steve/persondb.py` | MEDIUM - stores person data from LDAP | Names, emails | `list_persons()` returns all PII |
+| `v3/server/bin/create-election.py` | LOW - CLI tool reads YAML | Issue titles from YAML | None |
+| `v3/queries.yaml` | LOW - query definitions | N/A (parameterized) | N/A |
+
+---
+
+## Findings
+
+### Medium Severity Findings
+
+#### ASVS-1210-MED-001: No CSV/Formula Injection Protection Architecture
+
+**Severity:** MEDIUM
+
+**Location:**
+- **File:** Application-wide (architecture gap)
+- **Component:** All data input/output paths
+
+**Related Functions Checked:**
+- `v3/server/pages.py:do_create_endpoint()` (lines ~361-376)
+- `v3/server/pages.py:do_add_issue_endpoint()` (lines ~414-433)
+- `v3/server/pages.py:do_vote_endpoint()` (lines ~474-502)
+- `v3/steve/election.py:add_vote()` (lines ~197-209)
+- `v3/steve/election.py:tally_issue()` (lines ~210-265)
+- `v3/steve/election.py:get_voters_for_email()` (lines ~301-307)
+
+**Description:**
+
+The application stores user-controllable data (election titles, issue titles, issue descriptions, vote strings) without any sanitization of CSV formula injection characters. No CSV export functionality, CSV-safe utility functions, or formula injection escaping mechanisms exist anywhere in the codebase. The voting system produces tabular data through `tally_issue()` and `get_voters_for_email()` that are natural candidates for CSV/spreadsheet export, yet no architectural provision has been [...]
+
+**Vulnerable Code:**
+
+Vote acceptance without validation (`v3/steve/election.py`, lines ~197-209):
+```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   # <-- TODO: not implemented
+
+    mayvote = self.q_get_mayvote.first_row(pid, iid)
+    vote_token = crypto.gen_vote_token(md.opened_key, pid, iid, mayvote.salt)
+    ciphertext = crypto.create_vote(vote_token, mayvote.salt, votestring)
+    self.c_add_vote.perform(vote_token, ciphertext)
+```
+
+Issue creation without validation (`v3/server/pages.py`, lines ~414-433):
+```python
+@APP.post('/do-add-issue/<eid>')
+@asfquart.auth.require({R.committer})
+@load_election
+async def do_add_issue_endpoint(election):
+    result = await basic_info()
+    form = edict(await quart.request.form)
+    # No sanitization of form.title or form.description
+    iid = election.add_issue(form.title, form.description, vtype, kv)
+```
+
+Election creation without validation (`v3/server/pages.py`, lines ~361-376):
+```python
+@APP.post('/do-create-election')
+@asfquart.auth.require({R.pmc_member})
+async def do_create_endpoint():
+    form = edict(await quart.request.form)
+    # No sanitization of form.title
+    election = steve.election.Election.create(DB_FNAME, form.title, result.uid)
+```
+
+**Data Flow:**
+
+1. **Election Title:** `pages.py:do_create_endpoint()` → `form.title` → `Election.create()` → DB → potential tally/report export
+2. **Issue Title/Description:** `pages.py:do_add_issue_endpoint()` → `form.title`, `form.description` → `election.add_issue()` → DB → potential export
+3. **Vote Strings:** `pages.py:do_vote_endpoint()` → `form['vote-<iid>']` → `election.add_vote()` → encrypted in DB → `tally_issue()` decrypts → potential export
+
+**Proof of Concept:**
+
+An authenticated committer creates an issue with a formula injection payload:
+
+```http
+POST /do-add-issue/abc123 HTTP/1.1
+Content-Type: application/x-www-form-urlencoded
+
+title==cmd('calc')&description==HYPERLINK("http://evil.com","Click")
+```
+
+This value is stored in the database. When `tally_issue()` is called and results are exported to CSV/Excel:
+```csv
+Issue Title,Votes For,Votes Against
+=cmd('calc'),5,2
+```
+
+Opening this CSV in Excel/LibreOffice would execute the formula.
+
+Similarly, a malicious voter submits a formula as a vote string:
+```http
+POST /do-vote/abc123 HTTP/1.1
+Content-Type: application/x-www-form-urlencoded
+
+vote-issue1==cmd('powershell+-nop+-w+hidden+-enc+...')
+```
+
+When tallied via `tally_issue()` and exported, the decrypted votestring contains the payload.
+
+**Impact:**
+- If tally results or voter/election data are ever exported to CSV/XLS/XLSX/ODF (a common operational need for voting systems), formula injection payloads stored by authenticated users would execute in the recipient's spreadsheet application.
+- Could lead to arbitrary command execution on the machine of an election administrator reviewing results.
+- The `tally_issue()` method already decrypts and collects vote strings; the `get_voters_for_email()` method already produces structured person data — both are ready for export.
+
+**Gap Type:** Type A — No control exists for this attack vector at any layer.
+
+**Remediation:**
+
+1. **Add a CSV-safe export utility:**
+
+```python
+# v3/steve/csv_utils.py
+import csv
+import io
+
+# Characters that trigger formula interpretation in spreadsheet applications
+FORMULA_CHARS = {'=', '+', '-', '@', '\t', '\0'}
+
+def sanitize_csv_field(value):
+    """Escape formula injection characters per ASVS 1.2.10.
+    
+    If the first character is a formula trigger character,
+    prefix with a single quote to prevent spreadsheet interpretation.
+    """
+    if value is None:
+        return ''
+    s = str(value)
+    if s and s[0] in FORMULA_CHARS:
+        return "'" + s
+    return s
+
+def export_csv(rows, fieldnames, sanitize=True):
+    """Export rows to CSV string with RFC 4180 compliance and formula injection protection."""
+    output = io.StringIO()
+    writer = csv.DictWriter(output, fieldnames=fieldnames, 
+                            quoting=csv.QUOTE_ALL)  # RFC 4180 §2.6/2.7
+    writer.writeheader()
+    for row in rows:
+        if sanitize:
+            row = {k: sanitize_csv_field(v) for k, v in row.items()}
+        writer.writerow(row)
+    return output.getvalue()
+```
+
+2. **Add vote string validation (defense-in-depth):**
+
+```python
+# In election.py add_vote()
+def add_vote(self, pid: str, iid: str, votestring: str):
+    md = self._all_metadata(self.S_OPEN)
+    
+    # Validate votestring format for the issue type
+    issue = self.q_get_issue.first_row(iid)
+    if not issue:
+        raise IssueNotFound(iid)
+    
+    m = vtypes.vtype_module(issue.type)
+    if not m.validate_vote(votestring, self.json2kv(issue.kv)):
+        raise ValueError(f'Invalid vote format for {issue.type}: {votestring}')
+    
+    mayvote = self.q_get_mayvote.first_row(pid, iid)
+    vote_token = crypto.gen_vote_token(md.opened_key, pid, iid, mayvote.salt)
+    ciphertext = crypto.create_vote(vote_token, mayvote.salt, votestring)
+    self.c_add_vote.perform(vote_token, ciphertext)
+```
+
+3. **Add input validation for titles/descriptions (defense-in-depth):**
+
+```python
+# In pages.py, before storing titles
+def sanitize_text_input(text):
+    """Strip formula injection characters from leading position."""
+    if text and text[0] in {'=', '+', '-', '@', '\t', '\0'}:
+        text = text.lstrip('=+-@\t\0')
+    return text.strip()
+```
+
+---
+
+#### ASVS-1210-MED-002: Tally Results Contain Unvalidated User Data Without Export Safeguards
+
+**Severity:** MEDIUM  
+
+**Location:**
+- **File:** `v3/steve/election.py`
+- **Function:** `tally_issue()` (lines ~210-265)
+- **Function:** `get_voters_for_email()` (lines ~301-307)
+
+**Related Functions Checked:**
+- `v3/steve/election.py:add_vote()` (lines ~197-209)
+- `v3/steve/election.py:tally_issue()` (lines ~210-265)
+- `v3/steve/election.py:get_voters_for_email()` (lines ~301-307)
+- `v3/server/pages.py:do_vote_endpoint()` (lines ~474-502)
+
+**Description:**
+
+The `tally_issue()` method decrypts and collects raw vote strings submitted by voters. These vote strings have no format validation (as noted in the `add_vote()` TODO). The method returns these strings to the caller without any sanitization. Combined with `get_voters_for_email()` which returns person names and emails, the application produces two distinct data sets containing user-controllable content with no formula injection protection at the point of data assembly.
+
+**Vulnerable Code:**
+
+`v3/steve/election.py`, lines ~245-264:
+```python
+def tally_issue(self, iid):
+    # ...
+    for mayvote in self.q_tally.fetchall():
+        vote_token = crypto.gen_vote_token(
+            md.opened_key, mayvote.pid, iid, mayvote.salt,
+        )
+        row = self.q_recent_vote.first_row(vote_token)
+        if row is None:
+            continue
+        voters.add(mayvote.pid)
+        # Raw user-controlled votestring returned without sanitization
+        votestring = crypto.decrypt_votestring(
+            vote_token, mayvote.salt, row.ciphertext,
+        )
+        votes.append(votestring)
+    
+    crypto.shuffle(votes)
+    m = vtypes.vtype_module(issue.type)
+    return m.tally(votes, self.json2kv(issue.kv)), voters
+```
+
+`v3/steve/election.py`, lines ~301-307:
+```python
+def get_voters_for_email(self):
+    "Return a list of distinct voters (pid, name, email) eligible for this election."
+    self.q_voting_persons.perform(self.eid)
+    return [
+        edict(pid=row.pid, name=row.name, email=row.email)
+        for row in self.q_voting_persons.fetchall()
+    ]
+```
+
+**Data Flow:**
+
+`User form input` → `do_vote_endpoint()` → `election.add_vote()` (no validation) → encrypted in DB → `tally_issue()` decrypts → raw votestring returned to caller → potential CSV/spreadsheet export
+
+**Proof of Concept:**
+
+A voter submits an STV ranking containing a formula payload:
+```
+=cmd('calc'),candidate_a,candidate_b
+```
+Since there's no validation that STV votes only contain valid candidate labels, this is stored. When tallied and exported to a spreadsheet for review, the formula executes.
+
+**Impact:**
+- Election administrators reviewing tally results in a spreadsheet application could trigger arbitrary formula execution.
+- Voter identity data (names, emails) from `get_voters_for_email()` could also carry injection payloads if LDAP data is compromised.
+
+**Gap Type:** Type A — No protection exists at the output/export layer.
+
+**Remediation:**
+
+Apply the CSV-safe export utility from Finding ASVS-1210-MED-001 at any point where tally results or voter data are serialized for export. Additionally, implement vote string validation as described above.
+
+---
+
+## Positive Security Patterns
+
+| Pattern | Location | Description |
+|---------|----------|-------------|
+| Parameterized SQL queries | `queries.yaml` | All SQL queries use `?` placeholders, preventing SQL injection |
+| LDAPS connection | `asf-load-ldap.py` | Uses `ldaps://` for encrypted LDAP communication |
+| EZT template escaping | Templates (`manage.ezt`, `manage-stv.ezt`) | Uses `[format "js,html"]` for JavaScript/HTML context escaping |
+| Cryptographic vote anonymization | `election.py` | Per-voter salts and vote tokens decouple identity from votes |
+| State machine enforcement | `election.py` | Assert-based state checks prevent invalid operations |
+| `send_from_directory()` usage | `pages.py` | Quart's safe static file serving (prevents basic path traversal) |
+| Client-side `escapeHtml()` | `vote-on.ezt` | JavaScript HTML entity escaping for candidate names |
+
+---
+
+## Architecture Observations
+
+1. **No Export Layer Exists:** The application has a complete data lifecycle (input → storage → processing via `tally_issue()`) but no export/reporting layer in the provided code. This is the most common point where CSV formula injection manifests.
+
+2. **Vote Validation Gap is Acknowledged:** The comment `### validate VOTESTRING for ISSUE.TYPE voting` in `election.py:add_vote()` explicitly marks this as known technical debt. Implementing this validation would simultaneously address formula injection in vote data and improve data integrity.
+
+3. **Tally Infrastructure Ready for Export:** The `tally_issue()` and `get_voters_for_email()` methods produce structured tabular data that is a single function call away from CSV serialization. The absence of any CSV-safe export utility means adding an export feature would likely introduce formula injection by default.
+
+4. **LDAP Data is External Input:** While `asf-load-ldap.py` imports names and emails from a trusted LDAP server, these values are still external input that flows into the database and could appear in CSV exports.
+
+---
+
+## Recommendations Summary
+
+### Immediate Actions (Priority 1)
+
+| Priority | Recommendation | Effort | Impact |
+|----------|----------------|--------|--------|
+| 1 | **Implement vote string validation** in `add_vote()` per vote type (e.g., YNA accepts only `y`/`n`/`a`; STV accepts only comma-separated valid candidate labels) | Low | Eliminates the primary user-controllable vector for formula injection payload storage |
+
+### Short-term Actions (Priority 2-3)
+
+| Priority | Recommendation | Effort | Impact |
+|----------|----------------|--------|--------|
+| 2 | **Create a CSV-safe export utility** (`csv_utils.py`) with RFC 4180 compliance and formula character escaping, to be used by any future export functionality | Low | Provides a reusable control for all export paths |
+| 3 | **Add input validation for election/issue titles** rejecting or escaping leading formula characters (`=`, `+`, `-`, `@`, `\t`, `\0`) | Low | Defense-in-depth for administrative data |
+
+### Long-term Actions (Priority 4)
+
+| Priority | Recommendation | Effort | Impact |
+|----------|----------------|--------|--------|
+| 4 | **Document CSV export security requirements** in a developer guide, ensuring any future export feature uses the safe utility | Minimal | Prevents regression when export features are inevitably added |
+
+---
+
+## Appendix: Files Analyzed
+
+<details>
+<summary>Click to expand full file list (23 files)</summary>
+
+1. `v3/queries.yaml` (relevance: 10)
+2. `v3/server/api.py` (relevance: 10)
+3. `v3/server/bin/asf-load-ldap.py` (relevance: 10)
+4. `v3/server/bin/create-election.py` (relevance: 10)
+5. `v3/server/pages.py` (relevance: 10)
+6. `v3/server/templates/about.ezt` (relevance: 10)
+7. `v3/server/templates/admin.ezt` (relevance: 10)
+8. `v3/server/templates/e_bad_eid.ezt` (relevance: 10)
+9. `v3/server/templates/e_bad_iid.ezt` (relevance: 10)
+10. `v3/server/templates/e_bad_pid.ezt` (relevance: 10)
+11. `v3/server/templates/flashes.ezt` (relevance: 10)
+12. `v3/server/templates/footer.ezt` (relevance: 10)
+13. `v3/server/templates/header.ezt` (relevance: 10)
+14. `v3/server/templates/home.ezt` (relevance: 10)
+15. `v3/server/templates/manage-stv.ezt` (relevance: 10)
+16. `v3/server/templates/manage.ezt` (relevance: 10)
+17. `v3/server/templates/privacy.ezt` (relevance: 10)
+18. `v3/server/templates/profile.ezt` (relevance: 10)
+19. `v3/server/templates/settings.ezt` (relevance: 10)
+20. `v3/server/templates/vote-on.ezt` (relevance: 10)
+21. `v3/server/templates/voter.ezt` (relevance: 10)
+22. `v3/steve/election.py` (relevance: 10)
+23. `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