Exploit database

GH-de79f9bc167cd9df0000aa805acd65ba

rakib-nyc/nullorigin

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2021-42574

11 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files2
rakib-nyc/nulloriginRevision c2d68bb79550

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

nullorigin/engines/code/source_scanner.py

Python · 9,966 bytes
"""
Source-code scanning for invisible and deceptive characters.

This engine exists for a different reason than the rest of NullOrigin. There is
no watermark in AI-generated source code to remove: no provider watermarks code
output, and no public detector exists. What source code *does* have is a real,
published attack surface that the generic text path handles badly.

**Trojan Source** (CVE-2021-42574, Boucher & Anderson 2021). Bidirectional
control characters reorder how text is *displayed* without changing how it is
*compiled*. A reviewer reads one program and the compiler builds another:

    if access_level != "user‮ ⁦// Check if admin⁩⁦":

renders as a harmless comment while the string comparison says something else
entirely. This is invisible in every editor that honours the Unicode bidi
algorithm, which is most of them.

**Homoglyph identifiers** (CVE-2021-42694). Two identifiers that render
identically but differ by codepoint — Cyrillic `а` for Latin `a` — create silent
aliasing that no code review catches by eye.

Three things follow, and they are why the plain-text path is not reused here:

  1. **No NFKC normalization.** Normalizing source code rewrites string literal
     *values*: `"Hello"` becomes `"Hello"`, `"office"` becomes `"office"`.
     That changes what the program compares, hashes, and transmits.
  2. **No paraphrasing.** Sending code to a rewriting model produces code that
     does not run.
  3. **Homoglyphs are reported, not folded, by default.** Folding a Cyrillic
     `а` merges two distinct identifiers into one, changing the program's
     meaning. Detection is the value here; the fix is a human decision.

Author: Muhammad Rakibul Islam <[email protected]>
License: Apache-2.0
"""

import re
import unicodedata
from dataclasses import dataclass, field
from pathlib import Path

from nullorigin.engines.text.unicode_cleaner import (
    CONFUSABLE_MAP,
    INVISIBLE_UNICODE_REGEX,
)

# Extensions treated as source code. The point of the list is to route these
# away from the NFKC/paraphrase path, so it errs toward inclusion.
CODE_EXTENSIONS = {
    ".py", ".pyi", ".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".java",
    ".c", ".h", ".cc", ".cpp", ".hpp", ".cs", ".go", ".rs", ".rb", ".php",
    ".swift", ".kt", ".kts", ".scala", ".sh", ".bash", ".zsh", ".fish",
    ".ps1", ".pl", ".pm", ".lua", ".r", ".jl", ".hs", ".ml", ".ex", ".exs",
    ".erl", ".clj", ".cljs", ".dart", ".vue", ".svelte", ".sql", ".graphql",
    ".tf", ".hcl", ".proto", ".cmake", ".gradle", ".groovy", ".m", ".mm",
    ".asm", ".s", ".vb", ".fs", ".fsx", ".nim", ".zig", ".v", ".sol",
}

# Bidirectional formatting characters. The overrides and isolates are the
# Trojan Source vector; the embeddings are included because they compose.
BIDI_CONTROLS = {
    "‪": "LEFT-TO-RIGHT EMBEDDING",
    "‫": "RIGHT-TO-LEFT EMBEDDING",
    "‬": "POP DIRECTIONAL FORMATTING",
    "‭": "LEFT-TO-RIGHT OVERRIDE",
    "‮": "RIGHT-TO-LEFT OVERRIDE",
    "⁦": "LEFT-TO-RIGHT ISOLATE",
    "⁧": "RIGHT-TO-LEFT ISOLATE",
    "⁨": "FIRST STRONG ISOLATE",
    "⁩": "POP DIRECTIONAL ISOLATE",
    "‎": "LEFT-TO-RIGHT MARK",
    "‏": "RIGHT-TO-LEFT MARK",
    "؜": "ARABIC LETTER MARK",
}

_BIDI_REGEX = re.compile("[" + re.escape("".join(BIDI_CONTROLS)) + "]")

# A word-like run, used to locate the token a confusable sits inside.
_TOKEN = re.compile(r"\w+", re.UNICODE)

SEVERITY_ORDER = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "INFO": 3}


@dataclass
class Finding:
    """One suspicious character, located in the file."""

    severity: str
    kind: str
    codepoint: str
    name: str
    line: int
    column: int
    line_text: str
    detail: str = ""

    def __str__(self) -> str:
        return (
            f"{self.severity:<8} line {self.line}:{self.column}  "
            f"{self.codepoint} {self.name} — {self.detail or self.kind}"
        )


@dataclass
class CodeReport:
    """Everything found in one source file."""

    path: str = ""
    language: str = ""
    lines: int = 0
    findings: list[Finding] = field(default_factory=list)
    bidi_controls: int = 0
    invisible_characters: int = 0
    homoglyph_identifiers: int = 0
    homoglyph_other: int = 0

    @property
    def trojan_source(self) -> bool:
        """True when bidi controls are present — the CVE-2021-42574 vector."""
        return self.bidi_controls > 0

    @property
    def found_anything(self) -> bool:
        return bool(self.findings)

    @property
    def worst_severity(self) -> str | None:
        if not self.findings:
            return None
        return min((f.severity for f in self.findings), key=lambda s: SEVERITY_ORDER[s])

    def sorted_findings(self) -> list[Finding]:
        return sorted(
            self.findings, key=lambda f: (SEVERITY_ORDER[f.severity], f.line, f.column)
        )


def _char_name(ch: str) -> str:
    try:
        return unicodedata.name(ch)
    except ValueError:
        return f"UNNAMED (category {unicodedata.category(ch)})"


def _is_mixed_script_token(line: str, column: int) -> bool:
    """True when the confusable sits in a token that also contains ASCII letters.

    Mixed script is the actual attack signature. `tot<CYRILLIC A>l` is dangerous
    because it renders identically to `total` while being a different name. A
    token written entirely in another script — an ordinary Russian word in a
    comment — is legitimate text and folding it would be vandalism, so it is
    reported at INFO rather than MEDIUM.
    """
    index = column - 1
    for match in _TOKEN.finditer(line):
        if match.start() <= index < match.end():
            token = match.group(0)
            has_ascii_letter = any("a" <= c.lower() <= "z" for c in token if c.isascii())
            has_confusable = any(c in CONFUSABLE_MAP for c in token)
            return has_ascii_letter and has_confusable
    return False


def scan_code(source: str | bytes, path: str = "", language: str = "") -> CodeReport:
    """Scan source text for invisible, bidi, and homoglyph characters."""
    if isinstance(source, bytes):
        source = source.decode("utf-8", errors="replace")

    report = CodeReport(path=path, language=language)
    lines = source.splitlines()
    report.lines = len(lines)

    for line_no, line in enumerate(lines, start=1):
        for column, ch in enumerate(line, start=1):
            if ch in BIDI_CONTROLS:
                report.bidi_controls += 1
                report.findings.append(
                    Finding(
                        severity="CRITICAL",
                        kind="bidi_control",
                        codepoint=f"U+{ord(ch):04X}",
                        name=BIDI_CONTROLS[ch],
                        line=line_no,
                        column=column,
                        line_text=line,
                        detail=(
                            "Trojan Source (CVE-2021-42574): reorders displayed text "
                            "without changing what the compiler sees"
                        ),
                    )
                )
            elif INVISIBLE_UNICODE_REGEX.match(ch):
                report.invisible_characters += 1
                report.findings.append(
                    Finding(
                        severity="HIGH",
                        kind="invisible",
                        codepoint=f"U+{ord(ch):04X}",
                        name=_char_name(ch),
                        line=line_no,
                        column=column,
                        line_text=line,
                        detail="invisible character; can carry a hidden payload",
                    )
                )
            elif ch in CONFUSABLE_MAP:
                in_ident = _is_mixed_script_token(line, column)
                if in_ident:
                    report.homoglyph_identifiers += 1
                else:
                    report.homoglyph_other += 1
                report.findings.append(
                    Finding(
                        severity="MEDIUM" if in_ident else "INFO",
                        kind="mixed_script_token" if in_ident else "homoglyph",
                        codepoint=f"U+{ord(ch):04X}",
                        name=_char_name(ch),
                        line=line_no,
                        column=column,
                        line_text=line,
                        detail=(
                            f"renders as {CONFUSABLE_MAP[ch]!r} inside a mixed-script "
                            "token; two names can look identical but differ "
                            "(CVE-2021-42694)"
                            if in_ident
                            else f"renders as {CONFUSABLE_MAP[ch]!r}"
                        ),
                    )
                )

    return report


def purge_code(
    source: str | bytes,
    fold_homoglyphs: bool = False,
    path: str = "",
) -> tuple[str, CodeReport]:
    """Remove invisible and bidi characters from source code.

    NFKC normalization is deliberately not applied: it rewrites string literal
    values and would change what the program does.

    `fold_homoglyphs` is off by default. Folding a Cyrillic `а` to Latin `a`
    merges two identifiers that the compiler currently treats as distinct, which
    silently changes behavior. The report locates them; a human decides.
    """
    if isinstance(source, bytes):
        source = source.decode("utf-8", errors="replace")

    report = scan_code(source, path=path)

    cleaned = _BIDI_REGEX.sub("", source)
    cleaned = INVISIBLE_UNICODE_REGEX.sub("", cleaned)

    if fold_homoglyphs:
        cleaned = re.sub(
            "[" + re.escape("".join(CONFUSABLE_MAP)) + "]",
            lambda m: CONFUSABLE_MAP[m.group(0)],
            cleaned,
        )

    return cleaned, report


def is_code_file(path: str | Path) -> bool:
    return Path(path).suffix.lower() in CODE_EXTENSIONS