diff --git a/doc/code/converters/1_text_to_text_converters.py b/doc/code/converters/1_text_to_text_converters.py index 8c04acc6af..e31b018faa 100644 --- a/doc/code/converters/1_text_to_text_converters.py +++ b/doc/code/converters/1_text_to_text_converters.py @@ -64,6 +64,7 @@ MorseConverter, NatoConverter, NegationTrapConverter, + RegionalIndicatorConverter, ROT13Converter, TokenBijectionConverter, VigenereConverter, @@ -84,6 +85,7 @@ print("ROT13:", await ROT13Converter().convert_async(prompt=prompt)) # type: ignore print("Base64:", await Base64Converter().convert_async(prompt=prompt)) # type: ignore print("Base2048:", await Base2048Converter().convert_async(prompt=prompt)) # type: ignore +print("Regional indicator:", await RegionalIndicatorConverter().convert_async(prompt=prompt)) # type: ignore print("Binary:", await BinaryConverter().convert_async(prompt=prompt)) # type: ignore print("BinAscii:", await BinAsciiConverter().convert_async(prompt=prompt)) # type: ignore print("Morse:", await MorseConverter().convert_async(prompt=prompt)) # type: ignore diff --git a/doc/scanner/garak.ipynb b/doc/scanner/garak.ipynb index 50c7320488..d9625dbbf1 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, RegionalIndicator\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 525e70d3ec..6aef9a2e3d 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, RegionalIndicator # # **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..3e9585cebb 100644 --- a/pyrit/converter/__init__.py +++ b/pyrit/converter/__init__.py @@ -96,6 +96,7 @@ from pyrit.converter.qr_code_converter import QRCodeConverter from pyrit.converter.random_capital_letters_converter import RandomCapitalLettersConverter from pyrit.converter.random_translation_converter import RandomTranslationConverter + from pyrit.converter.regional_indicator_converter import RegionalIndicatorConverter from pyrit.converter.repeat_token_converter import RepeatTokenConverter from pyrit.converter.role_play_tool_call_converter import RolePlayToolCallConverter from pyrit.converter.rot13_converter import ROT13Converter @@ -232,6 +233,7 @@ "PuzzleType": "pyrit.converter.puzzled", "PuzzledConverter": "pyrit.converter.puzzled", "QRCodeConverter": "pyrit.converter.qr_code_converter", + "RegionalIndicatorConverter": "pyrit.converter.regional_indicator_converter", "ROT13Converter": "pyrit.converter.rot13_converter", "RandomCapitalLettersConverter": "pyrit.converter.random_capital_letters_converter", "RandomTranslationConverter": "pyrit.converter.random_translation_converter", diff --git a/pyrit/converter/regional_indicator_converter.py b/pyrit/converter/regional_indicator_converter.py new file mode 100644 index 0000000000..61786a064f --- /dev/null +++ b/pyrit/converter/regional_indicator_converter.py @@ -0,0 +1,89 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + + +from pyrit.converter.converter import Converter, ConverterResult +from pyrit.models import PromptDataType + + +class RegionalIndicatorConverter(Converter): + """ + Converts ASCII letters to Unicode Regional Indicator Symbols (the "flag letters"). + + Each letter A-Z (case-insensitive) is mapped to the corresponding code point in the + Regional Indicator Symbol block, U+1F1E6 (REGIONAL INDICATOR SYMBOL LETTER A) through + U+1F1FF (REGIONAL INDICATOR SYMBOL LETTER Z). These square letter tiles were introduced + to encode ISO 3166-1 region codes: rendered in pairs they become emoji flags (for + example "US" -> the flag of the United States), but a single tile displays as a + boxed capital letter. + + To keep the output readable letter-by-letter rather than collapsing consecutive pairs + into flag emoji, a ZERO WIDTH NON-JOINER (U+200C) is inserted between two adjacent + regional indicators whenever at least one of them was produced by this converter. The + joiner is invisible and breaks the flag sequence defined in UTS #51, so "US" renders as + two boxed letters instead of one flag. Two regional indicators that were both already in + the input (an existing flag) are left joined, so pre-existing flags are preserved. + Non-letter characters (digits, punctuation, spaces, and anything outside the Latin + alphabet) are left unchanged, which also naturally breaks any flag run. + + This is a purely typographic transform with no formal academic source; it was + popularized as an emoji-flag obfuscation trick, in the spirit of the P4RS3LT0NGV3 + (parseltongue) toolkit: https://github.com/BASI-LABS/parseltongue + + Note: This converter is useful for testing how AI systems handle text disguised as + emoji-flag tiles, which can be used to obfuscate potentially harmful content. + """ + + SUPPORTED_INPUT_TYPES = ("text",) + SUPPORTED_OUTPUT_TYPES = ("text",) + + #: First code point of the Regional Indicator Symbol block (letter A). + _REGIONAL_INDICATOR_A = 0x1F1E6 + #: Last code point of the Regional Indicator Symbol block (letter Z). + _REGIONAL_INDICATOR_Z = 0x1F1FF + #: Zero-width non-joiner inserted between adjacent tiles to prevent flag formation. + _SEPARATOR = "‌" + + async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text") -> ConverterResult: + """ + Convert the given text into Regional Indicator Symbols. + + Args: + prompt (str): The text to convert. + input_type (PromptDataType, optional): Type of input data. Defaults to "text". + + Returns: + ConverterResult: The text with ASCII letters replaced by regional indicators. + + Raises: + ValueError: If the input type is not supported (only "text" is supported). + """ + if not self.input_supported(input_type): + raise ValueError("Input type not supported") + + result: list[str] = [] + # Track the previously emitted character: whether it was a regional indicator at all, and + # whether that indicator was one this converter produced (vs. already present in the input). + previous_was_indicator = False + previous_was_converted = False + for char in prompt: + if "a" <= char.lower() <= "z" and char.isascii(): + emitted = chr(self._REGIONAL_INDICATOR_A + ord(char.lower()) - ord("a")) + is_indicator = True + is_converted = True + else: + emitted = char + is_converted = False + is_indicator = self._REGIONAL_INDICATOR_A <= ord(char) <= self._REGIONAL_INDICATOR_Z + + # Separate two adjacent indicators only when at least one was produced here, so a newly + # converted letter cannot form a flag with a neighbor. Two indicators that were both + # already in the input (an existing flag) are left joined. + if is_indicator and previous_was_indicator and (is_converted or previous_was_converted): + result.append(self._SEPARATOR) + + result.append(emitted) + previous_was_indicator = is_indicator + previous_was_converted = is_converted and is_indicator + + return ConverterResult(output_text="".join(result), output_type="text") diff --git a/pyrit/scenario/scenarios/garak/encoding.py b/pyrit/scenario/scenarios/garak/encoding.py index 3d07dd9d46..f891385ce6 100644 --- a/pyrit/scenario/scenarios/garak/encoding.py +++ b/pyrit/scenario/scenarios/garak/encoding.py @@ -22,6 +22,7 @@ LeetspeakConverter, MorseConverter, NatoConverter, + RegionalIndicatorConverter, ROT13Converter, SearchReplaceConverter, ZalgoConverter, @@ -130,6 +131,7 @@ class EncodingTechnique(ScenarioTechnique): AsciiSmuggler = ("ascii_smuggler", set[str]()) Bifid = ("bifid", set[str]()) ColumnarTransposition = ("columnar_transposition", set[str]()) + RegionalIndicator = ("regional_indicator", 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"), + ([RegionalIndicatorConverter()], "regional_indicator", "regional_indicator"), # "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/converter/test_regional_indicator_converter.py b/tests/unit/converter/test_regional_indicator_converter.py new file mode 100644 index 0000000000..c8bb01015e --- /dev/null +++ b/tests/unit/converter/test_regional_indicator_converter.py @@ -0,0 +1,152 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import pytest + +from pyrit.converter import ConverterResult, RegionalIndicatorConverter + +# U+1F1E6 REGIONAL INDICATOR SYMBOL LETTER A. +REGIONAL_INDICATOR_A = 0x1F1E6 +# Zero-width non-joiner inserted between adjacent tiles. +ZWNJ = "‌" + + +def _tile(letter: str) -> str: + """Return the regional indicator tile for a single ASCII letter a-z/A-Z.""" + return chr(REGIONAL_INDICATOR_A + ord(letter.lower()) - ord("a")) + + +async def test_regional_indicator_simple_letters(): + """Each letter maps to its regional indicator, separated by a zero-width non-joiner.""" + converter = RegionalIndicatorConverter() + + result = await converter.convert_async(prompt="abc", input_type="text") + + assert isinstance(result, ConverterResult) + assert result.output_type == "text" + assert result.output_text == _tile("a") + ZWNJ + _tile("b") + ZWNJ + _tile("c") + + +async def test_regional_indicator_case_insensitive(): + """Uppercase and lowercase letters map to the same tiles.""" + converter = RegionalIndicatorConverter() + + lower = await converter.convert_async(prompt="hello", input_type="text") + upper = await converter.convert_async(prompt="HELLO", input_type="text") + + assert lower.output_text == upper.output_text + + +async def test_regional_indicator_known_code_points(): + """A -> U+1F1E6 and Z -> U+1F1FF (block boundaries).""" + converter = RegionalIndicatorConverter() + + result = await converter.convert_async(prompt="AZ", input_type="text") + + assert result.output_text == chr(0x1F1E6) + ZWNJ + chr(0x1F1FF) + + +async def test_regional_indicator_non_letters_unchanged(): + """Digits, punctuation, and spaces pass through unchanged and break the tile run.""" + converter = RegionalIndicatorConverter() + + result = await converter.convert_async(prompt="a1 b", input_type="text") + + # "a" then "1", space pass through, then "b". No separator is inserted because + # the letters are not adjacent. + assert result.output_text == _tile("a") + "1 " + _tile("b") + + +async def test_regional_indicator_separator_only_between_adjacent_tiles(): + """The non-joiner appears only between consecutive tiles, not around non-letters.""" + converter = RegionalIndicatorConverter() + + result = await converter.convert_async(prompt="ab cd", input_type="text") + + expected = _tile("a") + ZWNJ + _tile("b") + " " + _tile("c") + ZWNJ + _tile("d") + assert result.output_text == expected + # The space-separated pair should not be joined. + assert f"{_tile('b')} {_tile('c')}" in result.output_text + + +async def test_regional_indicator_single_letter_has_no_separator(): + """A single letter produces one tile with no separator.""" + converter = RegionalIndicatorConverter() + + result = await converter.convert_async(prompt="x", input_type="text") + + assert result.output_text == _tile("x") + assert ZWNJ not in result.output_text + + +async def test_regional_indicator_separates_converted_tile_from_existing_indicator_after(): + """A converted letter next to a pre-existing indicator in the input must not form a flag.""" + converter = RegionalIndicatorConverter() + + # Input: existing indicator U (already a tile) immediately followed by the letter S. + result = await converter.convert_async(prompt=_tile("u") + "S", input_type="text") + + # Without the fix this returned the joined pair _tile("u")+_tile("s") -> the "US" flag. + assert result.output_text == _tile("u") + ZWNJ + _tile("s") + + +async def test_regional_indicator_separates_converted_tile_from_existing_indicator_before(): + """Same, with the existing indicator on the other side of the converted letter.""" + converter = RegionalIndicatorConverter() + + # Input: the letter U followed by an existing indicator S. + result = await converter.convert_async(prompt="U" + _tile("s"), input_type="text") + + assert result.output_text == _tile("u") + ZWNJ + _tile("s") + + +async def test_regional_indicator_preserves_existing_flag(): + """Two indicators that were both already in the input (an existing flag) are left joined.""" + converter = RegionalIndicatorConverter() + + existing_flag = _tile("u") + _tile("s") + result = await converter.convert_async(prompt=existing_flag, input_type="text") + + # Neither tile was produced by the converter, so no separator is inserted. + assert result.output_text == existing_flag + assert ZWNJ not in result.output_text + + +async def test_regional_indicator_empty_prompt(): + """An empty prompt yields empty output.""" + converter = RegionalIndicatorConverter() + + result = await converter.convert_async(prompt="", input_type="text") + + assert result.output_text == "" + + +async def test_regional_indicator_non_ascii_letters_pass_through(): + """Accented and non-Latin letters have no regional indicator and are left unchanged.""" + converter = RegionalIndicatorConverter() + + result = await converter.convert_async(prompt="café中", input_type="text") + + assert result.output_text == _tile("c") + ZWNJ + _tile("a") + ZWNJ + _tile("f") + "é中" + + +async def test_regional_indicator_input_type_not_supported(): + """Non-text input types raise ValueError.""" + converter = RegionalIndicatorConverter() + + with pytest.raises(ValueError, match="Input type not supported"): + await converter.convert_async(prompt="test", input_type="image_path") + + +def test_regional_indicator_input_supported(): + """input_supported only accepts text.""" + converter = RegionalIndicatorConverter() + assert converter.input_supported("text") is True + assert converter.input_supported("image_path") is False + + +def test_regional_indicator_output_supported(): + """output_supported only accepts text.""" + converter = RegionalIndicatorConverter() + assert converter.output_supported("text") is True + assert converter.output_supported("image_path") is False diff --git a/tests/unit/scenario/garak/test_encoding.py b/tests/unit/scenario/garak/test_encoding.py index da4c169488..4653bc816a 100644 --- a/tests/unit/scenario/garak/test_encoding.py +++ b/tests/unit/scenario/garak/test_encoding.py @@ -11,6 +11,7 @@ AskToDecodeConverter, Base64Converter, ColumnarTranspositionConverter, + RegionalIndicatorConverter, SearchReplaceConverter, ) from pyrit.executor.attack import PromptSendingAttack @@ -258,7 +259,7 @@ 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", @@ -268,6 +269,7 @@ def test_default_aggregate_curates_representative_subset(self): "ubbi_dubbi", "bifid", "columnar_transposition", + "regional_indicator", } def test_get_aggregate_tags_includes_default(self): @@ -530,6 +532,52 @@ async def test_get_prompt_attacks_creates_attack_runs( assert isinstance(run.attack_technique.attack, PromptSendingAttack) assert len(run._seed_groups) == len(mock_attack_seed_groups) + async def test_regional_indicator_technique_builds_converter_attacks( + self, mock_objective_target, mock_objective_scorer, mock_attack_seed_groups, mock_dataset_config + ): + """Selecting RegionalIndicator must register a row that applies the converter. + + The enum-level tests pass even if the ``regional_indicator`` row is removed or misnamed in + ``_converter_variants()``; this exercises the selection path end to end so such a regression + is caught. + """ + from unittest.mock import patch + + with patch.object( + Encoding, + "_resolve_seed_groups_by_dataset_async", + new_callable=AsyncMock, + return_value={"memory": mock_attack_seed_groups}, + ): + scenario = Encoding(objective_scorer=mock_objective_scorer) + scenario.set_params_from_args( + args={ + "objective_target": mock_objective_target, + "dataset_config": mock_dataset_config, + "scenario_techniques": [EncodingTechnique.RegionalIndicator], + } + ) + await scenario.initialize_async() + + attacks = scenario._get_converter_attacks( + context=scenario._build_scenario_context(seed_groups_by_dataset={"memory": mock_attack_seed_groups}) + ) + + # The technique must produce attacks (a missing/misnamed row would yield none). + assert attacks, "regional_indicator technique built no attacks" + assert all(aa.display_group == "regional_indicator" for aa in attacks) + + names = {aa.atomic_attack_name for aa in attacks} + assert "regional_indicator_raw" in names, "missing raw variant" + assert any(n != "regional_indicator_raw" for n in names), "missing decode variant" + + # The RegionalIndicatorConverter is actually applied in every variant's request converters. + for aa in attacks: + applied = [ + conv for config in aa.attack_technique.attack.get_request_converters() for conv in config.converters + ] + assert any(isinstance(conv, RegionalIndicatorConverter) for conv in applied) + async def test_decode_prompts_disclose_keyed_cipher_description( self, mock_objective_target, mock_objective_scorer, mock_attack_seed_groups, mock_dataset_config ):