From 194134af8eaa3df366e1f00a366a6925405d126e Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Thu, 19 Nov 2026 22:06:56 -0800 Subject: [PATCH 1/4] FEAT: Add pigpen Encoding technique via LeetspeakConverter Per review (reuse and compose before adding): keep the pigpen technique but implement it as LeetspeakConverter(custom_substitutions=) instead of a dedicated PigpenConverter class. The documented Pigpen key is retained as _PIGPEN_SUBSTITUTIONS. Co-Authored-By: Claude Opus 4.8 --- pyrit/scenario/scenarios/garak/encoding.py | 36 +++++++++++++++++++ tests/unit/scenario/garak/test_encoding.py | 3 +- .../scenario/garak/test_pigpen_technique.py | 13 +++++++ 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 tests/unit/scenario/garak/test_pigpen_technique.py diff --git a/pyrit/scenario/scenarios/garak/encoding.py b/pyrit/scenario/scenarios/garak/encoding.py index a427f02596..eb3d6bdcf8 100644 --- a/pyrit/scenario/scenarios/garak/encoding.py +++ b/pyrit/scenario/scenarios/garak/encoding.py @@ -51,6 +51,40 @@ from pyrit.scenario.core.scenario_technique import ScenarioTechnique from pyrit.score import DecodingScorer, TrueFalseScorer +# Pigpen (Freemason's / Masonic) cipher: a geometric monoalphabetic substitution of the Latin +# alphabet; see https://en.wikipedia.org/wiki/Pigpen_cipher . Framing classical ciphers as an +# LLM jailbreak vector: CipherChat (Yuan et al., 2023, arXiv:2308.06463). +# Kept as a Leetspeak substitution table rather than a dedicated converter (reuse and compose +# before adding). +_PIGPEN_SUBSTITUTIONS: dict[str, list[str]] = { + "a": ["┌"], + "b": ["┬"], + "c": ["┐"], + "d": ["├"], + "e": ["┼"], + "f": ["┤"], + "g": ["└"], + "h": ["┴"], + "i": ["┘"], + "j": ["┌̇"], + "k": ["┬̇"], + "l": ["┐̇"], + "m": ["├̇"], + "n": ["┼̇"], + "o": ["┤̇"], + "p": ["└̇"], + "q": ["┴̇"], + "r": ["┘̇"], + "s": ["△"], + "t": ["▷"], + "u": ["▽"], + "v": ["◁"], + "w": ["△̇"], + "x": ["▷̇"], + "y": ["▽̇"], + "z": ["◁̇"], +} + class EncodingDatasetConfiguration(DatasetAttackConfiguration): """ @@ -129,6 +163,7 @@ class EncodingTechnique(ScenarioTechnique): AsciiSmuggler = ("ascii_smuggler", set[str]()) Bifid = ("bifid", set[str]()) ColumnarTransposition = ("columnar_transposition", set[str]()) + Pigpen = ("pigpen", set[str]()) @classmethod def get_aggregate_tags(cls) -> set[str]: @@ -317,6 +352,7 @@ def _converter_variants() -> list[tuple[list[Converter], str, str]]: ([AsciiSmugglerConverter()], "ascii_smuggler", "ascii_smuggler"), ([BifidConverter()], "bifid", "bifid"), ([ColumnarTranspositionConverter(key="ZEBRAS")], "columnar_transposition", "columnar_transposition"), + ([LeetspeakConverter(custom_substitutions=_PIGPEN_SUBSTITUTIONS)], "pigpen", "pigpen"), ] # These are the same as Garak encoding attacks diff --git a/tests/unit/scenario/garak/test_encoding.py b/tests/unit/scenario/garak/test_encoding.py index 5e4bd78538..15be167842 100644 --- a/tests/unit/scenario/garak/test_encoding.py +++ b/tests/unit/scenario/garak/test_encoding.py @@ -253,13 +253,14 @@ def test_default_aggregate_curates_representative_subset(self): } all_names = {t.value for t in EncodingTechnique.get_all_techniques()} assert default_names < all_names - assert len(all_names) == 19 + assert len(all_names) == 20 # The niche/lossy schemes stay ALL-only. assert all_names - default_names == { "braille", "ecoji", "zalgo", "ascii_smuggler", + "pigpen", "bifid", "columnar_transposition", } diff --git a/tests/unit/scenario/garak/test_pigpen_technique.py b/tests/unit/scenario/garak/test_pigpen_technique.py new file mode 100644 index 0000000000..75f9339c80 --- /dev/null +++ b/tests/unit/scenario/garak/test_pigpen_technique.py @@ -0,0 +1,13 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from pyrit.converter import LeetspeakConverter +from pyrit.scenario.scenarios.garak.encoding import _PIGPEN_SUBSTITUTIONS + + +async def test_pigpen_technique_substitutes_letters(): + """The pigpen Encoding technique is a LeetspeakConverter configured with the Pigpen glyph table.""" + converter = LeetspeakConverter(custom_substitutions=_PIGPEN_SUBSTITUTIONS) + result = await converter.convert_async(prompt="abc") + assert result.output_text == "".join(_PIGPEN_SUBSTITUTIONS[ch][0] for ch in "abc") + assert result.output_text != "abc" From 07a661e3e9ce53140dc086186adc8510a724d968 Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Fri, 20 Nov 2026 22:58:30 -0800 Subject: [PATCH 2/4] FIX: Correct the Pigpen glyph table to match the cipher key MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses the P1 on #4446: _PIGPEN_SUBSTITUTIONS picked each glyph by its Unicode stroke directions, which draws the mirror of the key's shape, so 24 of 26 letters were wrong (e.g. 'a' gave the key's I and 'e' a cross instead of a closed box). A target that knows Pigpen would read 'cat' as 'git', and DecodingScorer would record a non-decode. Remap each letter to the lines the key draws around its grid cell: A-I on the tic-tac-toe grid (┘⊔└⊐□⊏┐⊓┌), J-R the same with a combining dot, S-V on the saltire (▽▷◁△), W-Z the same with a dot. Replace the self-checking test with one that pins the table to an independent transcription of the key, so a mirrored or swapped glyph fails. Co-Authored-By: Claude Opus 4.8 --- pyrit/scenario/scenarios/garak/encoding.py | 50 ++++++++++--------- .../scenario/garak/test_pigpen_technique.py | 46 +++++++++++++++-- 2 files changed, 67 insertions(+), 29 deletions(-) diff --git a/pyrit/scenario/scenarios/garak/encoding.py b/pyrit/scenario/scenarios/garak/encoding.py index eb3d6bdcf8..5309fc52a4 100644 --- a/pyrit/scenario/scenarios/garak/encoding.py +++ b/pyrit/scenario/scenarios/garak/encoding.py @@ -54,35 +54,37 @@ # Pigpen (Freemason's / Masonic) cipher: a geometric monoalphabetic substitution of the Latin # alphabet; see https://en.wikipedia.org/wiki/Pigpen_cipher . Framing classical ciphers as an # LLM jailbreak vector: CipherChat (Yuan et al., 2023, arXiv:2308.06463). +# Each glyph is the shape the key draws around that letter's grid cell: the tic-tac-toe grid for +# A-I, the same with a dot for J-R, the saltire (X) for S-V, and the same with a dot for W-Z. # Kept as a Leetspeak substitution table rather than a dedicated converter (reuse and compose # before adding). _PIGPEN_SUBSTITUTIONS: dict[str, list[str]] = { - "a": ["┌"], - "b": ["┬"], - "c": ["┐"], - "d": ["├"], - "e": ["┼"], - "f": ["┤"], - "g": ["└"], - "h": ["┴"], - "i": ["┘"], - "j": ["┌̇"], - "k": ["┬̇"], - "l": ["┐̇"], - "m": ["├̇"], - "n": ["┼̇"], - "o": ["┤̇"], - "p": ["└̇"], - "q": ["┴̇"], - "r": ["┘̇"], - "s": ["△"], + "a": ["┘"], + "b": ["⊔"], + "c": ["└"], + "d": ["⊐"], + "e": ["□"], + "f": ["⊏"], + "g": ["┐"], + "h": ["⊓"], + "i": ["┌"], + "j": ["┘̇"], + "k": ["⊔̇"], + "l": ["└̇"], + "m": ["⊐̇"], + "n": ["□̇"], + "o": ["⊏̇"], + "p": ["┐̇"], + "q": ["⊓̇"], + "r": ["┌̇"], + "s": ["▽"], "t": ["▷"], - "u": ["▽"], - "v": ["◁"], - "w": ["△̇"], + "u": ["◁"], + "v": ["△"], + "w": ["▽̇"], "x": ["▷̇"], - "y": ["▽̇"], - "z": ["◁̇"], + "y": ["◁̇"], + "z": ["△̇"], } diff --git a/tests/unit/scenario/garak/test_pigpen_technique.py b/tests/unit/scenario/garak/test_pigpen_technique.py index 75f9339c80..88b3a7dd26 100644 --- a/tests/unit/scenario/garak/test_pigpen_technique.py +++ b/tests/unit/scenario/garak/test_pigpen_technique.py @@ -4,10 +4,46 @@ from pyrit.converter import LeetspeakConverter from pyrit.scenario.scenarios.garak.encoding import _PIGPEN_SUBSTITUTIONS +# Expected glyphs independently transcribed from the Pigpen key +# (https://en.wikipedia.org/wiki/Pigpen_cipher): each glyph is the shape the key draws around the +# letter's grid cell. A-I use the tic-tac-toe grid; J-R repeat A-I with a combining dot; S-V use +# the saltire (X); W-Z repeat S-V with a dot. Each value is annotated with its Unicode name so it +# can be checked against the key (not the rendered font), pinning the production table to the key +# rather than re-deriving it from the same source. +_DOT = "̇" # COMBINING DOT ABOVE +_EXPECTED_PIGPEN = { + "a": "┘", # ┘ BOX DRAWINGS LIGHT UP AND LEFT + "b": "⊔", # ⊔ SQUARE CUP + "c": "└", # └ BOX DRAWINGS LIGHT UP AND RIGHT + "d": "⊐", # ⊐ SQUARE ORIGINAL OF + "e": "□", # □ WHITE SQUARE + "f": "⊏", # ⊏ SQUARE IMAGE OF + "g": "┐", # ┐ BOX DRAWINGS LIGHT DOWN AND LEFT + "h": "⊓", # ⊓ SQUARE CAP + "i": "┌", # ┌ BOX DRAWINGS LIGHT DOWN AND RIGHT + "s": "▽", # ▽ WHITE DOWN-POINTING TRIANGLE + "t": "▷", # ▷ WHITE RIGHT-POINTING TRIANGLE + "u": "◁", # ◁ WHITE LEFT-POINTING TRIANGLE + "v": "△", # △ WHITE UP-POINTING TRIANGLE +} +# J-R are the A-I glyphs with the combining dot; W-Z are the S-V glyphs with the dot. +_EXPECTED_PIGPEN.update({chr(ord("j") + k): _EXPECTED_PIGPEN[chr(ord("a") + k)] + _DOT for k in range(9)}) +_EXPECTED_PIGPEN.update({chr(ord("w") + k): _EXPECTED_PIGPEN[chr(ord("s") + k)] + _DOT for k in range(4)}) -async def test_pigpen_technique_substitutes_letters(): - """The pigpen Encoding technique is a LeetspeakConverter configured with the Pigpen glyph table.""" + +def test_pigpen_table_matches_the_key(): + """Every letter maps to the glyph the Pigpen key draws around its cell. + + The expected values are transcribed directly from the key, so a mirrored or swapped glyph + (e.g. ``a`` drawn as the key's ``i``) fails here instead of silently encoding ``cat`` as ``git``. + """ + actual = {letter: glyphs[0] for letter, glyphs in _PIGPEN_SUBSTITUTIONS.items()} + assert actual == _EXPECTED_PIGPEN + + +async def test_pigpen_technique_encodes_to_key_glyphs(): + """The pigpen technique (a LeetspeakConverter config) encodes to the key's glyphs.""" converter = LeetspeakConverter(custom_substitutions=_PIGPEN_SUBSTITUTIONS) - result = await converter.convert_async(prompt="abc") - assert result.output_text == "".join(_PIGPEN_SUBSTITUTIONS[ch][0] for ch in "abc") - assert result.output_text != "abc" + result = await converter.convert_async(prompt="cat") + # c, a, t written independently from the key: └ ┘ ▷ + assert result.output_text == "└┘▷" From bebf87a69c821f815614e0dfe7c0fd8225b5eaf1 Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Fri, 20 Nov 2026 23:00:33 -0800 Subject: [PATCH 3/4] DOC: Update garak scanner technique list to 20 (add Columnar, Pigpen) The Encoding scenario's ALL aggregate now has 20 techniques; the scanner guide still said 18 and ended at Bifid, omitting ColumnarTransposition (already on main) and this PR's Pigpen. Update both the paired .py and .ipynb. Co-Authored-By: Claude Opus 4.8 --- doc/scanner/garak.ipynb | 4 ++-- doc/scanner/garak.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/scanner/garak.ipynb b/doc/scanner/garak.ipynb index a256b213da..a08ed73378 100644 --- a/doc/scanner/garak.ipynb +++ b/doc/scanner/garak.ipynb @@ -303,9 +303,9 @@ "pyrit_scan run garak.encoding --target openai_chat --techniques base64 --max-total 1\n", "```\n", "\n", - "**Available techniques** (18 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex,\n", + "**Available techniques** (20 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex,\n", "QuotedPrintable, UUencode, ROT13, Braille, Atbash, MorseCode, NATO, Ecoji, Zalgo, LeetSpeak,\n", - "AsciiSmuggler, Bifid\n", + "AsciiSmuggler, Bifid, ColumnarTransposition, Pigpen\n", "\n", "**Aggregate techniques:** `ALL` (every encoding, exhaustive) and `DEFAULT` (a broad curated subset\n", "spanning every encoding family — base-N, byte-encodings, substitution ciphers, and symbolic\n", diff --git a/doc/scanner/garak.py b/doc/scanner/garak.py index 5250721af5..d6839def2e 100644 --- a/doc/scanner/garak.py +++ b/doc/scanner/garak.py @@ -136,9 +136,9 @@ # pyrit_scan run garak.encoding --target openai_chat --techniques base64 --max-total 1 # ``` # -# **Available techniques** (18 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex, +# **Available techniques** (20 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex, # QuotedPrintable, UUencode, ROT13, Braille, Atbash, MorseCode, NATO, Ecoji, Zalgo, LeetSpeak, -# AsciiSmuggler, Bifid +# AsciiSmuggler, Bifid, ColumnarTransposition, Pigpen # # **Aggregate techniques:** `ALL` (every encoding, exhaustive) and `DEFAULT` (a broad curated subset # spanning every encoding family — base-N, byte-encodings, substitution ciphers, and symbolic From 286e88ab65c3e0e861e7049617a5347a3cbb37b5 Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Sat, 21 Nov 2026 00:53:36 -0800 Subject: [PATCH 4/4] REFACTOR: Add PigpenConverter on a shared character-substitution base Per design discussion, extract the per-character substitution engine from LeetspeakConverter into a shared abstract base (_CharacterSubstitutionConverter, on WordLevelConverter): the table, deterministic/random selection, and validation. LeetspeakConverter and the new public PigpenConverter are thin named members. Mirror/upside-down (whole-string transforms) are intentionally out of scope. Pigpen moves from a LeetspeakConverter(custom_substitutions=...) config to a first-class PigpenConverter, mirroring the base16/32/64 decision. The glyph table (the corrected key mapping) lives with the converter; the Encoding scenario now registers PigpenConverter(). LeetspeakConverter's public behaviour and identifier are preserved byte-for-byte (it keeps its own __init__ and _build_identifier, including the default-table-not- hashed semantics); verified across default/custom/empty/case modes. The base is abstract so only the named members are discoverable converters. Co-Authored-By: Claude Opus 4.8 --- pyrit/converter/__init__.py | 2 + .../_character_substitution_converter.py | 106 ++++++++++++++++++ pyrit/converter/leetspeak_converter.py | 104 +++++------------ pyrit/converter/pigpen_converter.py | 83 ++++++++++++++ pyrit/scenario/scenarios/garak/encoding.py | 39 +------ .../scenario/garak/test_pigpen_technique.py | 36 +++--- 6 files changed, 246 insertions(+), 124 deletions(-) create mode 100644 pyrit/converter/_character_substitution_converter.py create mode 100644 pyrit/converter/pigpen_converter.py diff --git a/pyrit/converter/__init__.py b/pyrit/converter/__init__.py index 1e6375f545..2c75061c53 100644 --- a/pyrit/converter/__init__.py +++ b/pyrit/converter/__init__.py @@ -89,6 +89,7 @@ from pyrit.converter.noise_converter import NoiseConverter from pyrit.converter.pdf_converter import PDFConverter from pyrit.converter.persuasion_converter import PersuasionConverter + from pyrit.converter.pigpen_converter import PigpenConverter from pyrit.converter.pinyin_converter import PinyinConverter from pyrit.converter.policy_puppetry_converter import PolicyPuppetryConverter, PolicyPuppetryTemplate from pyrit.converter.prompt_template_converter import PromptTemplateConverter @@ -222,6 +223,7 @@ "NoiseConverter": "pyrit.converter.noise_converter", "PDFConverter": "pyrit.converter.pdf_converter", "PersuasionConverter": "pyrit.converter.persuasion_converter", + "PigpenConverter": "pyrit.converter.pigpen_converter", "PinyinConverter": "pyrit.converter.pinyin_converter", "PolicyPuppetryConverter": "pyrit.converter.policy_puppetry_converter", "PolicyPuppetryTemplate": "pyrit.converter.policy_puppetry_converter", diff --git a/pyrit/converter/_character_substitution_converter.py b/pyrit/converter/_character_substitution_converter.py new file mode 100644 index 0000000000..a1153b3f0e --- /dev/null +++ b/pyrit/converter/_character_substitution_converter.py @@ -0,0 +1,106 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from pyrit.converter.text_selection_strategy import WordSelectionStrategy +from pyrit.converter.word_level_converter import WordLevelConverter + + +class _CharacterSubstitutionConverter(WordLevelConverter): + """ + Shared base for converters that replace each character with fixed replacement(s). + + A substitution table maps a (case-folded) character to a non-empty list of replacement strings. + In deterministic mode the first replacement is always used; otherwise one is chosen at random. + Characters absent from the table are left unchanged. Word selection is inherited from + ``WordLevelConverter``. + + Members of this family are ``LeetspeakConverter`` (look-alike leet glyphs) and + ``PigpenConverter`` (Pigpen cipher glyphs). This base is intentionally *not* for whole-string + transforms (e.g. mirror/upside-down, which also reverse the text). + """ + + def __init__( + self, + *, + substitutions: dict[str, list[str]], + deterministic: bool = True, + word_selection_strategy: WordSelectionStrategy | None = None, + ) -> None: + """ + Initialize the converter. + + Args: + substitutions (dict[str, list[str]]): Map of single characters to a non-empty list of + replacement strings. Assumed already validated/normalized by the subclass. + deterministic (bool): If True, always use the first replacement for each character; + if False, choose one at random. + word_selection_strategy (WordSelectionStrategy | None): Strategy for selecting which words + to convert. If None, all words are converted. + """ + super().__init__(word_selection_strategy=word_selection_strategy) + self._substitutions = substitutions + self._deterministic = deterministic + + @staticmethod + def _validate_substitutions( + substitutions: dict[str, list[str]], *, param_name: str = "substitutions" + ) -> dict[str, list[str]]: + """ + Validate a substitution table and key it by lowercase character. + + ``convert_word_async`` looks characters up in lowercase, so an uppercase or multi-character + key would never match, and an empty replacement list would fail on the first matching character. + + Args: + substitutions (dict[str, list[str]]): The substitution table to validate. + param_name (str): Name used in error messages (e.g. ``"custom_substitutions"``). + + Returns: + dict[str, list[str]]: The substitutions keyed by lowercase character. + + Raises: + ValueError: If a key is not a single character, two keys differ only in case, or a value + is not a non-empty list of strings. + """ + normalized: dict[str, list[str]] = {} + for char, replacements in substitutions.items(): + if not isinstance(char, str) or len(char) != 1: + raise ValueError(f"{param_name} keys must be single characters, got {char!r}.") + if ( + not isinstance(replacements, list) + or not replacements + or not all(isinstance(replacement, str) for replacement in replacements) + ): + raise ValueError(f"{param_name}[{char!r}] must be a non-empty list of strings, got {replacements!r}.") + lower_char = char.lower() + if lower_char in normalized: + raise ValueError(f"{param_name} has more than one key for {lower_char!r}.") + normalized[lower_char] = list(replacements) + return normalized + + def _substitute_word(self, word: str) -> str: + """ + Substitute each character in a word per the table. + + Concrete subclasses call this from ``convert_word_async``. This class stays abstract (it does + not implement ``convert_word_async``) so only the named members (Leetspeak, Pigpen) are + discoverable converters. + + Args: + word (str): The word to be converted. + + Returns: + str: The converted word. + """ + converted_word = [] + rng = self._get_random_generator(stream="character-substitutions") + for char in word: + lower_char = char.lower() + if lower_char in self._substitutions: + if self._deterministic: + converted_word.append(self._substitutions[lower_char][0]) + else: + converted_word.append(rng.choice(self._substitutions[lower_char])) + else: + converted_word.append(char) + return "".join(converted_word) diff --git a/pyrit/converter/leetspeak_converter.py b/pyrit/converter/leetspeak_converter.py index f394605cc4..d7bdd1f752 100644 --- a/pyrit/converter/leetspeak_converter.py +++ b/pyrit/converter/leetspeak_converter.py @@ -1,16 +1,34 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. +from pyrit.converter._character_substitution_converter import _CharacterSubstitutionConverter from pyrit.converter.text_selection_strategy import AllWordsSelectionStrategy, WordSelectionStrategy -from pyrit.converter.word_level_converter import WordLevelConverter from pyrit.models import ComponentIdentifier -class LeetspeakConverter(WordLevelConverter): +class LeetspeakConverter(_CharacterSubstitutionConverter): """ Converts a string to a leetspeak version. + + Leetspeak is the look-alike member of the character-substitution family + (see ``_CharacterSubstitutionConverter``): by default it uses the standard leet table, and a + ``custom_substitutions`` map can override it. """ + _DEFAULT_SUBSTITUTIONS = { + "a": ["4", "@", "/\\", "@", "^", "/-\\"], + "b": ["8", "6", "13", "|3", "/3", "!3"], + "c": ["(", "[", "<", "{"], + "e": ["3"], + "g": ["9"], + "i": ["1", "!"], + "l": ["1", "|"], + "o": ["0"], + "s": ["5", "$"], + "t": ["7"], + "z": ["2"], + } + def __init__( self, *, @@ -34,66 +52,18 @@ def __init__( ValueError: If ``custom_substitutions`` has a key that is not a single character, two keys that differ only in case, or a value that is not a non-empty list of strings. """ - super().__init__(word_selection_strategy=word_selection_strategy) - - default_substitutions = { - "a": ["4", "@", "/\\", "@", "^", "/-\\"], - "b": ["8", "6", "13", "|3", "/3", "!3"], - "c": ["(", "[", "<", "{"], - "e": ["3"], - "g": ["9"], - "i": ["1", "!"], - "l": ["1", "|"], - "o": ["0"], - "s": ["5", "$"], - "t": ["7"], - "z": ["2"], - } - if custom_substitutions is not None: - custom_substitutions = self._validate_custom_substitutions(custom_substitutions) + custom_substitutions = self._validate_substitutions(custom_substitutions, param_name="custom_substitutions") # Use custom substitutions if provided, otherwise default to the standard ones - self._leet_substitutions = custom_substitutions if custom_substitutions else default_substitutions - self._deterministic = deterministic + substitutions = custom_substitutions if custom_substitutions else self._DEFAULT_SUBSTITUTIONS + super().__init__( + substitutions=substitutions, + deterministic=deterministic, + word_selection_strategy=word_selection_strategy, + ) self._has_custom_substitutions = custom_substitutions is not None - @staticmethod - def _validate_custom_substitutions(custom_substitutions: dict[str, list[str]]) -> dict[str, list[str]]: - """ - Validate custom substitutions and key them by lowercase character. - - ``convert_word_async`` looks characters up in lowercase, so an uppercase or multi-character - key would never match, and an empty replacement list would fail on the first matching character. - - Args: - custom_substitutions (dict[str, list[str]]): The substitutions passed to the converter. - - Returns: - dict[str, list[str]]: The substitutions keyed by lowercase character. - - Raises: - ValueError: If a key is not a single character, two keys differ only in case, or a value - is not a non-empty list of strings. - """ - normalized: dict[str, list[str]] = {} - for char, replacements in custom_substitutions.items(): - if not isinstance(char, str) or len(char) != 1: - raise ValueError(f"custom_substitutions keys must be single characters, got {char!r}.") - if ( - not isinstance(replacements, list) - or not replacements - or not all(isinstance(replacement, str) for replacement in replacements) - ): - raise ValueError( - f"custom_substitutions[{char!r}] must be a non-empty list of strings, got {replacements!r}." - ) - lower_char = char.lower() - if lower_char in normalized: - raise ValueError(f"custom_substitutions has more than one key for {lower_char!r}.") - normalized[lower_char] = list(replacements) - return normalized - def _build_identifier(self) -> ComponentIdentifier: """ Build the converter identifier with leetspeak parameters. @@ -107,7 +77,7 @@ def _build_identifier(self) -> ComponentIdentifier: # Hash custom substitutions if provided substitutions_hash = None if self._has_custom_substitutions: - substitutions_str = json.dumps(self._leet_substitutions, sort_keys=True) + substitutions_str = json.dumps(self._substitutions, sort_keys=True) substitutions_hash = hashlib.sha256(substitutions_str.encode("utf-8")).hexdigest()[:16] selection_params = ( @@ -125,7 +95,7 @@ def _build_identifier(self) -> ComponentIdentifier: async def convert_word_async(self, word: str) -> str: """ - Convert a single word into the target format supported by the converter. + Convert a single word into leetspeak. Args: word (str): The word to be converted. @@ -133,18 +103,4 @@ async def convert_word_async(self, word: str) -> str: Returns: str: The converted word. """ - converted_word = [] - rng = self._get_random_generator(stream="character-substitutions") - for char in word: - lower_char = char.lower() - if lower_char in self._leet_substitutions: - if self._deterministic: - # Use the first substitution for deterministic mode - converted_word.append(self._leet_substitutions[lower_char][0]) - else: - # Randomly select a substitution for each character - converted_word.append(rng.choice(self._leet_substitutions[lower_char])) - else: - # If character not in substitutions, keep it as is - converted_word.append(char) - return "".join(converted_word) + return self._substitute_word(word) diff --git a/pyrit/converter/pigpen_converter.py b/pyrit/converter/pigpen_converter.py new file mode 100644 index 0000000000..70d40d7e4a --- /dev/null +++ b/pyrit/converter/pigpen_converter.py @@ -0,0 +1,83 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from pyrit.converter._character_substitution_converter import _CharacterSubstitutionConverter +from pyrit.converter.text_selection_strategy import WordSelectionStrategy + +# Pigpen (Freemason's / Masonic) cipher: a geometric monoalphabetic substitution of the Latin +# alphabet; see https://en.wikipedia.org/wiki/Pigpen_cipher . Framing classical ciphers as an +# LLM jailbreak vector: CipherChat (Yuan et al., 2023, arXiv:2308.06463). +# +# Each glyph is the shape the key draws around that letter's grid cell: the tic-tac-toe grid for +# A-I, the same with a dot for J-R, the saltire (X) for S-V, and the same with a dot for W-Z. +# Base glyphs are written as explicit code points so each can be checked against its Unicode name. +_DOT = "̇" # COMBINING DOT ABOVE +_BASE_GLYPHS = { + "a": "┘", # ┘ BOX DRAWINGS LIGHT UP AND LEFT + "b": "⊔", # ⊔ SQUARE CUP + "c": "└", # └ BOX DRAWINGS LIGHT UP AND RIGHT + "d": "⊐", # ⊐ SQUARE ORIGINAL OF + "e": "□", # □ WHITE SQUARE + "f": "⊏", # ⊏ SQUARE IMAGE OF + "g": "┐", # ┐ BOX DRAWINGS LIGHT DOWN AND LEFT + "h": "⊓", # ⊓ SQUARE CAP + "i": "┌", # ┌ BOX DRAWINGS LIGHT DOWN AND RIGHT + "s": "▽", # ▽ WHITE DOWN-POINTING TRIANGLE + "t": "▷", # ▷ WHITE RIGHT-POINTING TRIANGLE + "u": "◁", # ◁ WHITE LEFT-POINTING TRIANGLE + "v": "△", # △ WHITE UP-POINTING TRIANGLE +} + + +def _build_pigpen_substitutions() -> dict[str, list[str]]: + """ + Build the full A-Z Pigpen table: A-I/S-V as-is, J-R/W-Z the same glyphs with a combining dot. + + Returns: + dict[str, list[str]]: The Pigpen substitution table keyed by lowercase letter. + """ + table = {letter: [glyph] for letter, glyph in _BASE_GLYPHS.items()} + # J-R repeat the A-I glyphs with the dot; W-Z repeat the S-V glyphs with the dot. + table.update({chr(ord("j") + i): [_BASE_GLYPHS[chr(ord("a") + i)] + _DOT] for i in range(9)}) + table.update({chr(ord("w") + i): [_BASE_GLYPHS[chr(ord("s") + i)] + _DOT] for i in range(4)}) + return table + + +_PIGPEN_SUBSTITUTIONS = _build_pigpen_substitutions() + + +class PigpenConverter(_CharacterSubstitutionConverter): + """ + Encodes text with the Pigpen (Freemason's / Masonic) cipher. + + Pigpen is a geometric monoalphabetic substitution: each letter becomes the fragment of the grid + that surrounds its cell. This is the geometric member of the character-substitution family + (see ``_CharacterSubstitutionConverter``); like Leetspeak it is case-folding and not reversible + (``Hello`` and ``hello`` encode identically). + """ + + def __init__(self, *, word_selection_strategy: WordSelectionStrategy | None = None) -> None: + """ + Initialize the converter. + + Args: + word_selection_strategy (WordSelectionStrategy | None): Strategy for selecting which words + to convert. If None, all words are converted. + """ + super().__init__( + substitutions=_PIGPEN_SUBSTITUTIONS, + deterministic=True, + word_selection_strategy=word_selection_strategy, + ) + + async def convert_word_async(self, word: str) -> str: + """ + Convert a single word into Pigpen glyphs. + + Args: + word (str): The word to be converted. + + Returns: + str: The converted word. + """ + return self._substitute_word(word) diff --git a/pyrit/scenario/scenarios/garak/encoding.py b/pyrit/scenario/scenarios/garak/encoding.py index 2eab238fb8..a23e160f63 100644 --- a/pyrit/scenario/scenarios/garak/encoding.py +++ b/pyrit/scenario/scenarios/garak/encoding.py @@ -22,6 +22,7 @@ LeetspeakConverter, MorseConverter, NatoConverter, + PigpenConverter, ROT13Converter, SearchReplaceConverter, ZalgoConverter, @@ -52,42 +53,6 @@ from pyrit.scenario.core.scenario_technique import ScenarioTechnique from pyrit.score import DecodingScorer, TrueFalseScorer -# Pigpen (Freemason's / Masonic) cipher: a geometric monoalphabetic substitution of the Latin -# alphabet; see https://en.wikipedia.org/wiki/Pigpen_cipher . Framing classical ciphers as an -# LLM jailbreak vector: CipherChat (Yuan et al., 2023, arXiv:2308.06463). -# Each glyph is the shape the key draws around that letter's grid cell: the tic-tac-toe grid for -# A-I, the same with a dot for J-R, the saltire (X) for S-V, and the same with a dot for W-Z. -# Kept as a Leetspeak substitution table rather than a dedicated converter (reuse and compose -# before adding). -_PIGPEN_SUBSTITUTIONS: dict[str, list[str]] = { - "a": ["┘"], - "b": ["⊔"], - "c": ["└"], - "d": ["⊐"], - "e": ["□"], - "f": ["⊏"], - "g": ["┐"], - "h": ["⊓"], - "i": ["┌"], - "j": ["┘̇"], - "k": ["⊔̇"], - "l": ["└̇"], - "m": ["⊐̇"], - "n": ["□̇"], - "o": ["⊏̇"], - "p": ["┐̇"], - "q": ["⊓̇"], - "r": ["┌̇"], - "s": ["▽"], - "t": ["▷"], - "u": ["◁"], - "v": ["△"], - "w": ["▽̇"], - "x": ["▷̇"], - "y": ["◁̇"], - "z": ["△̇"], -} - class EncodingDatasetConfiguration(DatasetAttackConfiguration): """ @@ -356,7 +321,7 @@ def _converter_variants() -> list[tuple[list[Converter], str, str]]: ([AsciiSmugglerConverter()], "ascii_smuggler", "ascii_smuggler"), ([BifidConverter()], "bifid", "bifid"), ([ColumnarTranspositionConverter(key="ZEBRAS")], "columnar_transposition", "columnar_transposition"), - ([LeetspeakConverter(custom_substitutions=_PIGPEN_SUBSTITUTIONS)], "pigpen", "pigpen"), + ([PigpenConverter()], "pigpen", "pigpen"), # "ubbi_dubbi": a language game that prefixes each vowel run with "ub", popularized by # the PBS children's show Zoom (1972). https://en.wikipedia.org/wiki/Ubbi_dubbi ([SearchReplaceConverter(pattern=r"([aeiouAEIOU]+)", replace=r"ub\1")], "ubbi_dubbi", "ubbi_dubbi"), diff --git a/tests/unit/scenario/garak/test_pigpen_technique.py b/tests/unit/scenario/garak/test_pigpen_technique.py index 88b3a7dd26..c5c4c314cd 100644 --- a/tests/unit/scenario/garak/test_pigpen_technique.py +++ b/tests/unit/scenario/garak/test_pigpen_technique.py @@ -1,15 +1,14 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -from pyrit.converter import LeetspeakConverter -from pyrit.scenario.scenarios.garak.encoding import _PIGPEN_SUBSTITUTIONS +from pyrit.converter import PigpenConverter # Expected glyphs independently transcribed from the Pigpen key # (https://en.wikipedia.org/wiki/Pigpen_cipher): each glyph is the shape the key draws around the # letter's grid cell. A-I use the tic-tac-toe grid; J-R repeat A-I with a combining dot; S-V use # the saltire (X); W-Z repeat S-V with a dot. Each value is annotated with its Unicode name so it -# can be checked against the key (not the rendered font), pinning the production table to the key -# rather than re-deriving it from the same source. +# can be checked against the key (not the rendered font), pinning the converter to the key rather +# than re-deriving it from the production table. _DOT = "̇" # COMBINING DOT ABOVE _EXPECTED_PIGPEN = { "a": "┘", # ┘ BOX DRAWINGS LIGHT UP AND LEFT @@ -31,19 +30,30 @@ _EXPECTED_PIGPEN.update({chr(ord("w") + k): _EXPECTED_PIGPEN[chr(ord("s") + k)] + _DOT for k in range(4)}) -def test_pigpen_table_matches_the_key(): - """Every letter maps to the glyph the Pigpen key draws around its cell. +async def test_pigpen_converter_encodes_every_letter_to_the_key(): + """PigpenConverter encodes each letter to the glyph the key draws around its cell. The expected values are transcribed directly from the key, so a mirrored or swapped glyph (e.g. ``a`` drawn as the key's ``i``) fails here instead of silently encoding ``cat`` as ``git``. """ - actual = {letter: glyphs[0] for letter, glyphs in _PIGPEN_SUBSTITUTIONS.items()} - assert actual == _EXPECTED_PIGPEN + converter = PigpenConverter() + for letter, expected in _EXPECTED_PIGPEN.items(): + result = await converter.convert_async(prompt=letter) + assert result.output_text == expected, f"{letter!r} encoded wrong" -async def test_pigpen_technique_encodes_to_key_glyphs(): - """The pigpen technique (a LeetspeakConverter config) encodes to the key's glyphs.""" - converter = LeetspeakConverter(custom_substitutions=_PIGPEN_SUBSTITUTIONS) - result = await converter.convert_async(prompt="cat") +async def test_pigpen_converter_encodes_word_to_key_glyphs(): + """A whole word encodes to the key's glyphs (and is case-folding).""" + converter = PigpenConverter() # c, a, t written independently from the key: └ ┘ ▷ - assert result.output_text == "└┘▷" + assert (await converter.convert_async(prompt="cat")).output_text == "└┘▷" + # Case-folding: Hello and hello encode identically. + assert (await converter.convert_async(prompt="Hello")).output_text == ( + await converter.convert_async(prompt="hello") + ).output_text + + +def test_pigpen_converter_is_exported_and_text_only(): + converter = PigpenConverter() + assert converter.input_supported("text") is True + assert converter.input_supported("image_path") is False