diff --git a/doc/scanner/garak.ipynb b/doc/scanner/garak.ipynb index 4b3f1143a4..125065333d 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** (20 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex,\n", + "**Available techniques** (21 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex,\n", "QuotedPrintable, UUencode, ROT13, Braille, Atbash, MorseCode, NATO, Ecoji, Zalgo, LeetSpeak,\n", - "AsciiSmuggler, Bifid, ColumnarTransposition, UbbiDubbi\n", + "AsciiSmuggler, Bifid, ColumnarTransposition, UbbiDubbi, 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 33b72d4a44..3873ff766e 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** (20 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex, +# **Available techniques** (21 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex, # QuotedPrintable, UUencode, ROT13, Braille, Atbash, MorseCode, NATO, Ecoji, Zalgo, LeetSpeak, -# AsciiSmuggler, Bifid, ColumnarTransposition, UbbiDubbi +# AsciiSmuggler, Bifid, ColumnarTransposition, UbbiDubbi, 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 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 3d07dd9d46..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, @@ -130,6 +131,7 @@ class EncodingTechnique(ScenarioTechnique): AsciiSmuggler = ("ascii_smuggler", set[str]()) Bifid = ("bifid", set[str]()) ColumnarTransposition = ("columnar_transposition", set[str]()) + Pigpen = ("pigpen", set[str]()) UbbiDubbi = ("ubbi_dubbi", set[str]()) @classmethod @@ -319,6 +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"), + ([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_encoding.py b/tests/unit/scenario/garak/test_encoding.py index da4c169488..8636e90825 100644 --- a/tests/unit/scenario/garak/test_encoding.py +++ b/tests/unit/scenario/garak/test_encoding.py @@ -258,13 +258,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) == 20 + assert len(all_names) == 21 # The niche/lossy schemes stay ALL-only. assert all_names - default_names == { "braille", "ecoji", "zalgo", "ascii_smuggler", + "pigpen", "ubbi_dubbi", "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..c5c4c314cd --- /dev/null +++ b/tests/unit/scenario/garak/test_pigpen_technique.py @@ -0,0 +1,59 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +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 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 + "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_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``. + """ + 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_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 (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