Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/code/converters/1_text_to_text_converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
MorseConverter,
NatoConverter,
NegationTrapConverter,
RegionalIndicatorConverter,
ROT13Converter,
TokenBijectionConverter,
VigenereConverter,
Expand All @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still applies at the current head: the paired notebook has neither the import nor the example. Also update the saved modality table in 0_converters.ipynb, which omits RegionalIndicatorConverter; the converter instructions require that reference update. Its source already discovers converters dynamically, so no hard-coded row is needed.

Verified on commit 085f5aa95f50f863e6dd2935f666c6013b5aa575.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code defects on this PR (the flag-boundary separation and the scenario-selection test) are fixed in the latest push. The paired-notebook sync is not included: 1_text_to_text_converters.ipynb and the 0_converters.ipynb modality table need a docs build that executes the notebooks (later cells call live LLM targets and need credentials), which I can't produce correct saved output for here. Leaving this open so it is tracked.

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
Expand Down
4 changes: 2 additions & 2 deletions doc/scanner/garak.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
4 changes: 2 additions & 2 deletions doc/scanner/garak.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions pyrit/converter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down
89 changes: 89 additions & 0 deletions pyrit/converter/regional_indicator_converter.py
Original file line number Diff line number Diff line change
@@ -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")
3 changes: 3 additions & 0 deletions pyrit/scenario/scenarios/garak/encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
LeetspeakConverter,
MorseConverter,
NatoConverter,
RegionalIndicatorConverter,
ROT13Converter,
SearchReplaceConverter,
ZalgoConverter,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"),
Expand Down
152 changes: 152 additions & 0 deletions tests/unit/converter/test_regional_indicator_converter.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading