From 5506dc0a887f3b282d2f4d6b07963503d7297836 Mon Sep 17 00:00:00 2001 From: Roland Date: Tue, 6 Oct 2026 11:07:36 -0600 Subject: [PATCH] repos: harden README search against untrusted READMEs A README comes from an untrusted remote. * Escape the README headline: snippet() marks matches with control characters, the text is HTML-escaped, then the markers become . Headlines are rendered as HTML (HeadlineText). * Never follow a symlinked README (O_NOFOLLOW, regular files only). * Convert markdown line by line with linear-time patterns. The old multiline patterns backtracked polynomially; a README of blank lines never finished, and runs of `', re.DOTALL), ' '), - (re.compile(r'<[^>\n]+>'), ' '), # HTML tags. - (re.compile(r'^\s*\[[^\]]+\]:\s*\S+.*$', re.MULTILINE), ''), # Link reference definitions. - (re.compile(r'!\[([^\]]*)\]\([^)]*\)'), r'\1'), # Images (and badges) become their alt text. - (re.compile(r'\[([^\]]*)\]\([^)]*\)'), r'\1'), # Links become their text. - (re.compile(r'^\s*(```|~~~).*$', re.MULTILINE), ''), # Code fences. - (re.compile(r'^\s{0,3}#{1,6}\s*', re.MULTILINE), ''), # Headings. - (re.compile(r'^\s{0,3}>\s?', re.MULTILINE), ''), # Block quotes. - (re.compile(r'^\s*\|?[\s:|-]+\|[\s:|-]*$', re.MULTILINE), ''), # Table separator rows. +# A README is untrusted; every pattern here must run in linear time. Each bracketed run stops at the next +# opening bracket, so scans from different starting points never overlap. +INLINE_MARKDOWN_PATTERNS = [ + (re.compile(r'<[^<>\n]*>'), ' '), # HTML tags. + (re.compile(r'!\[([^\[\]\n]*)\]\([^()\n]*\)'), r'\1'), # Images (and badges) become their alt text. + (re.compile(r'\[([^\[\]\n]*)\]\([^()\n]*\)'), r'\1'), # Links become their text. (re.compile(r'[*`|]+'), ' '), # Emphasis, inline code, table cells. (re.compile(r'[ \t]+'), ' '), - (re.compile(r'\n\s*\n+'), '\n'), ] +HEADING_RE = re.compile(r'#{1,6}(?=\s|$)') +LINK_REFERENCE_RE = re.compile(r'\[[^\[\]]+\]:\s') +TABLE_SEPARATOR_CHARACTERS = set('|:- \t') + + +def _remove_html_comments(text: str) -> str: + parts, position = [], 0 + while (comment := text.find('', comment + 4) + if end == -1: + return ''.join(parts) + parts.append(' ') + position = end + 3 + parts.append(text[position:]) + return ''.join(parts) + + +def markdown_to_text(text: str) -> str: + """Remove markdown syntax so search snippets read as plain text.""" + lines = [] + for line in _remove_html_comments(text).splitlines(): + stripped = line.strip() + if stripped.startswith(('```', '~~~')) or LINK_REFERENCE_RE.match(stripped): + continue + if '-' in stripped and set(stripped) <= TABLE_SEPARATOR_CHARACTERS: + continue # A table separator row, or a horizontal rule. + stripped = stripped.lstrip('>').strip() + if heading := HEADING_RE.match(stripped): + stripped = stripped[heading.end():].strip() + for pattern, replacement in INLINE_MARKDOWN_PATTERNS: + stripped = pattern.sub(replacement, stripped) + if stripped := stripped.strip(): + lines.append(stripped) + return '\n'.join(lines) def read_readme_text(path: pathlib.Path) -> Optional[str]: - """Read a README as plain text for search; markdown syntax is removed so snippets read well.""" + """Read a README as plain text for search; markdown syntax is removed so snippets read well. + + A symlink is never followed (it could point outside the repo).""" try: - with path.open('rb') as fh: - text = fh.read(FILE_MAX_TEXT_SIZE).decode(errors='replace') - except (FileNotFoundError, IsADirectoryError): + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: return None + with os.fdopen(fd, 'rb') as fh: + if not stat.S_ISREG(os.fstat(fh.fileno()).st_mode): + return None + text = fh.read(FILE_MAX_TEXT_SIZE).decode(errors='replace') if path.suffix.lower() in MARKDOWN_SUFFIXES: - for pattern, replacement in MARKDOWN_PATTERNS: - text = pattern.sub(replacement, text) + text = markdown_to_text(text) return text.strip() or None @@ -364,7 +400,8 @@ def _repo_search_sql(search_str: Optional[str], tag_names: Optional[List[str]]) if len(tag_names) > 1: # A Repo has one Tag. return None - search = fts.repository_search_join(search_str) if search_str else None + search = fts.repository_search_join(search_str, start=HIGHLIGHT_START, stop=HIGHLIGHT_STOP) \ + if search_str else None if search is None and (search_str and search_str.strip() or not tag_names): # Nothing usable to search, or nothing to filter by. return None @@ -400,10 +437,22 @@ def search_repos(session: Session, search_str: str = None, tag_names: List[str] repos = session.query(Repository).options(*Repository.json_options()) \ .filter(Repository.id.in_([i[0] for i in rows])).all() repos = {i.id: i for i in repos} - results = [dict(repos[id_].__json__(), readme_headline=headline) for id_, headline, _ in rows if id_ in repos] + results = [dict(repos[id_].__json__(), readme_headline=_safe_headline(headline)) + for id_, headline, _ in rows if id_ in repos] return results, rows[0][2] +# Highlight markers which cannot be confused with HTML. See `_safe_headline`. +HIGHLIGHT_START, HIGHLIGHT_STOP = '\x02', '\x03' + + +def _safe_headline(headline: Optional[str]) -> Optional[str]: + """A README is untrusted and its headline is rendered as HTML: escape it, then mark the matches with .""" + if not headline: + return headline + return html.escape(headline).replace(HIGHLIGHT_START, '').replace(HIGHLIGHT_STOP, '') + + def count_repos(session: Session, search_str: str = None, tag_names: List[str] = None) -> int: """The number of Repos `search_repos` would find.""" query = _repo_search_sql(search_str, tag_names) diff --git a/modules/repos/test/test_search.py b/modules/repos/test/test_search.py index 3516bda5..2fb37dfd 100644 --- a/modules/repos/test/test_search.py +++ b/modules/repos/test/test_search.py @@ -1,5 +1,6 @@ import json import sqlite3 +import time from http import HTTPStatus import pytest @@ -127,3 +128,63 @@ async def test_search_api(test_session, async_client, test_wrolpi_config): request, response = await async_client.post('/api/search_suggestions', content=json.dumps(dict(search_str='kiw'))) assert response.json['repos'] == [ dict(id=kiwix.id, name='kiwix-tools', tag_name='software', location=f'/repos/{kiwix.id}')] + + +@pytest.mark.asyncio +async def test_readme_headline_is_escaped(test_session, async_client, test_wrolpi_config): + """A README comes from an untrusted remote; its headline is rendered as HTML, so only the highlight is markup.""" + repo = lib.create_repository(test_session, 'https://github.com/a/b') + set_readme(test_session, repo, 'zim & bold') + + repos, _ = lib.search_repos(test_session, 'zim') + assert repos[0]['readme_headline'] == \ + 'zim <img src=x onerror="alert(1)"> &amp; <b>bold</b>' + + +def test_read_readme_text_refuses_symlinks(tmp_path): + secret = tmp_path / 'secret.txt' + secret.write_text('secret') + readme = tmp_path / 'README.md' + readme.symlink_to(secret) + assert lib.read_readme_text(readme) is None + assert lib.find_readme(tmp_path) is None + + +@pytest.mark.parametrize('text', [ + '|' + ' ' * 100_000 + 'x', + '-' * 100_000 + 'x', + ' + +[![CI](https://x/badge.svg)](https://ci) **Kiwix** is an *offline* reader. See [the docs](https://docs). + +| a | b | +|---|---| +| 1 | 2 | + +```bash +kiwix-serve --port 80 +``` +> quoted +[ref]: https://example.com +--- +#hashtag +''' + assert lib.markdown_to_text(readme) == \ + 'Kiwix Tools\nCI Kiwix is an offline reader. See the docs.\na b\n1 2\nkiwix-serve --port 80\nquoted\n#hashtag'