diff --git a/doc/code/converters/1_text_to_text_converters.py b/doc/code/converters/1_text_to_text_converters.py index 8c04acc6af..4790a422ee 100644 --- a/doc/code/converters/1_text_to_text_converters.py +++ b/doc/code/converters/1_text_to_text_converters.py @@ -61,6 +61,7 @@ DigitBijectionConverter, EcojiConverter, LetterBijectionConverter, + MathematicalAlphanumericConverter, MorseConverter, NatoConverter, NegationTrapConverter, @@ -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("Mathematical alphanumeric:", await MathematicalAlphanumericConverter().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 a256b213da..892795cac8 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, MathematicalAlphanumeric\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..7f0f5665ca 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, MathematicalAlphanumeric # # **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..8fbd04456b 100644 --- a/pyrit/converter/__init__.py +++ b/pyrit/converter/__init__.py @@ -83,6 +83,7 @@ from pyrit.converter.malicious_question_generator_converter import MaliciousQuestionGeneratorConverter from pyrit.converter.math_obfuscation_converter import MathObfuscationConverter from pyrit.converter.math_prompt_converter import MathPromptConverter + from pyrit.converter.mathematical_alphanumeric_converter import MathematicalAlphanumericConverter from pyrit.converter.morse_converter import MorseConverter from pyrit.converter.nato_converter import NatoConverter from pyrit.converter.negation_trap_converter import NegationTrapConverter @@ -214,6 +215,7 @@ "LSBImageStegoConverter": "pyrit.converter.lsb_image_stego_converter", "LSBImageStegoDecodeConverter": "pyrit.converter.lsb_image_stego_converter", "MaliciousQuestionGeneratorConverter": "pyrit.converter.malicious_question_generator_converter", + "MathematicalAlphanumericConverter": "pyrit.converter.mathematical_alphanumeric_converter", "MathObfuscationConverter": "pyrit.converter.math_obfuscation_converter", "MathPromptConverter": "pyrit.converter.math_prompt_converter", "MorseConverter": "pyrit.converter.morse_converter", diff --git a/pyrit/converter/mathematical_alphanumeric_converter.py b/pyrit/converter/mathematical_alphanumeric_converter.py new file mode 100644 index 0000000000..d5c96fcde3 --- /dev/null +++ b/pyrit/converter/mathematical_alphanumeric_converter.py @@ -0,0 +1,184 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from typing import Any, ClassVar + +from pyrit.converter.text_selection_strategy import WordSelectionStrategy +from pyrit.converter.word_level_converter import WordLevelConverter +from pyrit.models import ComponentIdentifier + +# Base code points for each style's A-Z, a-z, and (where defined) 0-9 runs inside the +# Unicode Mathematical Alphanumeric Symbols block (U+1D400-U+1D7FF). Each run is contiguous +# except for the reserved code points handled by ``_STYLE_EXCEPTIONS`` below. +_STYLE_BASES: dict[str, dict[str, int]] = { + "bold": {"upper": 0x1D400, "lower": 0x1D41A, "digit": 0x1D7CE}, + "italic": {"upper": 0x1D434, "lower": 0x1D44E}, + "bold_italic": {"upper": 0x1D468, "lower": 0x1D482}, + "script": {"upper": 0x1D49C, "lower": 0x1D4B6}, + "bold_script": {"upper": 0x1D4D0, "lower": 0x1D4EA}, + "fraktur": {"upper": 0x1D504, "lower": 0x1D51E}, + "bold_fraktur": {"upper": 0x1D56C, "lower": 0x1D586}, + "double_struck": {"upper": 0x1D538, "lower": 0x1D552, "digit": 0x1D7D8}, + "sans_serif": {"upper": 0x1D5A0, "lower": 0x1D5BA, "digit": 0x1D7E2}, + "sans_serif_bold": {"upper": 0x1D5D4, "lower": 0x1D5EE, "digit": 0x1D7EC}, + "sans_serif_italic": {"upper": 0x1D608, "lower": 0x1D622}, + "sans_serif_bold_italic": {"upper": 0x1D63C, "lower": 0x1D656}, + "monospace": {"upper": 0x1D670, "lower": 0x1D68A, "digit": 0x1D7F6}, +} + +# Reserved-codepoint exceptions. A handful of styled letters are "holes" in the U+1D400 block +# because the glyphs were already encoded in the Letterlike Symbols block (U+2100-U+214F). +# The naive ``base + offset`` arithmetic lands on an unassigned code point for these, so each +# must be mapped to its real glyph instead. Styles not listed here (bold, bold_italic, +# bold_script, bold_fraktur, every sans-serif variant, monospace) have fully contiguous runs. +_STYLE_EXCEPTIONS: dict[str, dict[str, str]] = { + "italic": { + "h": "ℎ", # PLANCK CONSTANT + }, + "script": { + "B": "ℬ", # SCRIPT CAPITAL B + "E": "ℰ", # SCRIPT CAPITAL E + "F": "ℱ", # SCRIPT CAPITAL F + "H": "ℋ", # SCRIPT CAPITAL H + "I": "ℐ", # SCRIPT CAPITAL I + "L": "ℒ", # SCRIPT CAPITAL L + "M": "ℳ", # SCRIPT CAPITAL M + "R": "ℛ", # SCRIPT CAPITAL R + "e": "ℯ", # SCRIPT SMALL E + "g": "ℊ", # SCRIPT SMALL G + "o": "ℴ", # SCRIPT SMALL O + }, + "fraktur": { + "C": "ℭ", # BLACK-LETTER CAPITAL C + "H": "ℌ", # BLACK-LETTER CAPITAL H + "I": "ℑ", # BLACK-LETTER CAPITAL I + "R": "ℜ", # BLACK-LETTER CAPITAL R + "Z": "ℨ", # BLACK-LETTER CAPITAL Z + }, + "double_struck": { + "C": "ℂ", # DOUBLE-STRUCK CAPITAL C + "H": "ℍ", # DOUBLE-STRUCK CAPITAL H + "N": "ℕ", # DOUBLE-STRUCK CAPITAL N + "P": "ℙ", # DOUBLE-STRUCK CAPITAL P + "Q": "ℚ", # DOUBLE-STRUCK CAPITAL Q + "R": "ℝ", # DOUBLE-STRUCK CAPITAL R + "Z": "ℤ", # DOUBLE-STRUCK CAPITAL Z + }, +} + + +def _build_style_map(style: str) -> dict[str, str]: + """ + Build the ASCII-to-styled character map for a single style. + + Args: + style (str): The style name (a key of ``_STYLE_BASES``). + + Returns: + dict[str, str]: Mapping from each ASCII letter/digit to its styled glyph. + """ + bases = _STYLE_BASES[style] + exceptions = _STYLE_EXCEPTIONS.get(style, {}) + char_map: dict[str, str] = {} + for offset in range(26): + upper = chr(ord("A") + offset) + lower = chr(ord("a") + offset) + char_map[upper] = exceptions.get(upper, chr(bases["upper"] + offset)) + char_map[lower] = exceptions.get(lower, chr(bases["lower"] + offset)) + if "digit" in bases: + for offset in range(10): + digit = chr(ord("0") + offset) + char_map[digit] = chr(bases["digit"] + offset) + return char_map + + +class MathematicalAlphanumericConverter(WordLevelConverter): + """ + Converts ASCII letters and digits to styled glyphs from the Unicode Mathematical + Alphanumeric Symbols block (U+1D400-U+1D7FF). + + The block provides a full set of Latin letters (and, for some styles, digits) rendered in + a selectable typographic style: bold, italic, script, fraktur, double-struck, sans-serif, + monospace, and bold/italic combinations of these. For example, with ``style="bold"``, + "Hello" becomes "𝐇𝐞𝐥𝐥𝐨"; with ``style="fraktur"`` it becomes "ℌ𝔢𝔩𝔩𝔬". + + A handful of styled letters are reserved ("holes") in the block because their glyphs were + already encoded in the Letterlike Symbols block (U+2100-U+214F) — e.g. the script/fraktur + capitals ℋ, ℌ and the double-struck ℍ. These are mapped to the correct glyph so no + unassigned code point is ever emitted. Characters with no styled form (punctuation, spaces, + digits for styles that define none, non-ASCII) are left unchanged. + + This is a filter-evasion / typographic-obfuscation style transform: the output is visually + close to the original but uses entirely different code points, which can slip past filters + or classifiers that match on exact ASCII without first normalizing the input. There is no + formal academic jailbreak source; it is a well-known Unicode obfuscation technique. + """ + + #: Style names accepted by the ``style`` parameter, each precomputed into a character map. + _STYLE_MAPS: ClassVar[dict[str, dict[str, str]]] = {style: _build_style_map(style) for style in _STYLE_BASES} + + def __init__( + self, + *, + style: str = "bold", + word_selection_strategy: WordSelectionStrategy | None = None, + word_split_separator: str | None = " ", + **kwargs: Any, + ) -> None: + """ + Initialize the converter with the chosen typographic style. + + Args: + style (str): The Mathematical Alphanumeric style to apply. One of: ``bold``, + ``italic``, ``bold_italic``, ``script``, ``bold_script``, ``fraktur``, + ``bold_fraktur``, ``double_struck``, ``sans_serif``, ``sans_serif_bold``, + ``sans_serif_italic``, ``sans_serif_bold_italic``, ``monospace``. Defaults to + ``bold``. + word_selection_strategy (WordSelectionStrategy | None): Strategy for selecting which + words to convert. If None, all words are converted. Defaults to None. + word_split_separator (str | None): Separator used to split words in the input text. + If None, splits by any whitespace. Defaults to " ". + **kwargs: Forwarded to ``WordLevelConverter.__init__``. + + Raises: + ValueError: If ``style`` is not a recognized style name. + """ + super().__init__( + word_selection_strategy=word_selection_strategy, + word_split_separator=word_split_separator, + **kwargs, + ) + if style not in self._STYLE_MAPS: + supported = ", ".join(sorted(self._STYLE_MAPS)) + raise ValueError(f"Unsupported style '{style}'. Supported styles: {supported}.") + self._style = style + self._char_map = self._STYLE_MAPS[style] + + def _build_identifier(self) -> ComponentIdentifier: + """ + Build identifier including the selected style alongside word-level parameters. + + Returns: + ComponentIdentifier: The identifier for this converter. + """ + return self._create_identifier( + params={ + "style": self._style, + "word_selection_strategy": self._word_selection_strategy.__class__.__name__, + "word_selection_strategy_params": self._word_selection_strategy.get_identifier_params(), + "word_split_separator": self._word_split_separator, + } + ) + + async def convert_word_async(self, word: str) -> str: + """ + Convert a single word into its styled Mathematical Alphanumeric form. + + Args: + word (str): The word to be converted. + + Returns: + str: The word with ASCII letters/digits replaced by styled glyphs; other + characters are left unchanged. + """ + return "".join(self._char_map.get(char, char) for char in word) diff --git a/pyrit/scenario/scenarios/garak/encoding.py b/pyrit/scenario/scenarios/garak/encoding.py index a427f02596..36aa7271da 100644 --- a/pyrit/scenario/scenarios/garak/encoding.py +++ b/pyrit/scenario/scenarios/garak/encoding.py @@ -20,6 +20,7 @@ Converter, EcojiConverter, LeetspeakConverter, + MathematicalAlphanumericConverter, MorseConverter, NatoConverter, ROT13Converter, @@ -129,6 +130,7 @@ class EncodingTechnique(ScenarioTechnique): AsciiSmuggler = ("ascii_smuggler", set[str]()) Bifid = ("bifid", set[str]()) ColumnarTransposition = ("columnar_transposition", set[str]()) + MathematicalAlphanumeric = ("mathematical_alphanumeric", set[str]()) @classmethod def get_aggregate_tags(cls) -> set[str]: @@ -317,6 +319,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"), + ([MathematicalAlphanumericConverter()], "mathematical_alphanumeric", "mathematical_alphanumeric"), ] # These are the same as Garak encoding attacks diff --git a/tests/unit/converter/test_mathematical_alphanumeric_converter.py b/tests/unit/converter/test_mathematical_alphanumeric_converter.py new file mode 100644 index 0000000000..c17454ade9 --- /dev/null +++ b/tests/unit/converter/test_mathematical_alphanumeric_converter.py @@ -0,0 +1,153 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import unicodedata + +import pytest + +from pyrit.converter import ( + ConverterResult, + MathematicalAlphanumericConverter, + WordIndexSelectionStrategy, +) +from pyrit.converter.mathematical_alphanumeric_converter import _STYLE_BASES + + +async def test_bold_maps_letters_and_digits_async() -> None: + result = await MathematicalAlphanumericConverter(style="bold").convert_async(prompt="Hello 123", input_type="text") + + assert isinstance(result, ConverterResult) + assert result.output_type == "text" + # 𝐇𝐞𝐥𝐥𝐨 𝟏𝟐𝟑 + assert result.output_text == "\U0001d407\U0001d41e\U0001d425\U0001d425\U0001d428 \U0001d7cf\U0001d7d0\U0001d7d1" + + +async def test_default_style_is_bold_async() -> None: + default_result = await MathematicalAlphanumericConverter().convert_async(prompt="Ab9", input_type="text") + bold_result = await MathematicalAlphanumericConverter(style="bold").convert_async(prompt="Ab9", input_type="text") + + assert default_result.output_text == bold_result.output_text + assert default_result.output_text == "\U0001d400\U0001d41b\U0001d7d7" + + +async def test_monospace_letters_and_digits_are_contiguous_async() -> None: + result = await MathematicalAlphanumericConverter(style="monospace").convert_async(prompt="Az0", input_type="text") + + # A -> U+1D670, z -> U+1D68A + 25 = U+1D6A3, 0 -> U+1D7F6 + assert result.output_text == "\U0001d670\U0001d6a3\U0001d7f6" + + +async def test_italic_h_uses_letterlike_exception_async() -> None: + result = await MathematicalAlphanumericConverter(style="italic").convert_async(prompt="h", input_type="text") + + # Reserved code point U+1D455 is a hole; the glyph is PLANCK CONSTANT (U+210E). + assert result.output_text == "ℎ" + + +async def test_script_capital_exceptions_async() -> None: + result = await MathematicalAlphanumericConverter(style="script").convert_async(prompt="HILR", input_type="text") + + # Script capitals H, I, L, R from the Letterlike Symbols block. + assert result.output_text == "ℋℐℒℛ" + + +async def test_script_small_exceptions_async() -> None: + result = await MathematicalAlphanumericConverter(style="script").convert_async(prompt="ego", input_type="text") + + # Script small e, g, o from the Letterlike Symbols block. + assert result.output_text == "ℯℊℴ" + + +async def test_fraktur_capital_exceptions_async() -> None: + result = await MathematicalAlphanumericConverter(style="fraktur").convert_async(prompt="CHIRZ", input_type="text") + + # Black-letter capitals C, H, I, R, Z from the Letterlike Symbols block. + assert result.output_text == "ℭℌℑℜℨ" + + +async def test_double_struck_exceptions_and_digits_async() -> None: + result = await MathematicalAlphanumericConverter(style="double_struck").convert_async( + prompt="CHNPQRZ 0", input_type="text" + ) + + # Double-struck capitals C, H, N, P, Q, R, Z then double-struck 0 (U+1D7D8). + assert result.output_text == "ℂℍℕℙℚℝℤ \U0001d7d8" + + +async def test_unmapped_characters_pass_through_async() -> None: + # 'e' with acute accent (U+00E9) and CJK are non-ASCII and must pass through unchanged. + result = await MathematicalAlphanumericConverter(style="bold").convert_async(prompt="café, 日", input_type="text") + + # c -> U+1D41C, a -> U+1D41A, f -> U+1D41F; accented e, comma, space and CJK unchanged. + assert result.output_text == "\U0001d41c\U0001d41a\U0001d41fé, 日" + + +async def test_styles_without_digit_runs_leave_digits_unchanged_async() -> None: + # italic defines no digit glyphs; digits must pass through untouched. + result = await MathematicalAlphanumericConverter(style="italic").convert_async(prompt="a1", input_type="text") + + assert result.output_text == "\U0001d44e1" + + +@pytest.mark.parametrize("style", sorted(_STYLE_BASES)) +async def test_every_style_emits_only_assigned_codepoints_async(style: str) -> None: + # Converting the full alphabet (and digits) must never produce an unassigned code point, + # which would mean a reserved "hole" in the block was not handled via an exception. + alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + + result = await MathematicalAlphanumericConverter(style=style).convert_async(prompt=alphabet, input_type="text") + + for char in result.output_text: + # unicodedata.name raises ValueError for unassigned code points. + assert unicodedata.name(char) + + +@pytest.mark.parametrize("style", sorted(_STYLE_BASES)) +async def test_nfkc_normalization_round_trips_to_plaintext_async(style: str) -> None: + # Every mapped glyph must carry a compatibility decomposition back to its plain ASCII + # letter/digit, so NFKC-normalizing the converted alphabet restores the original input. + # This pins the *represented* character of each glyph, not just that it is assigned: a one-off + # base shift (for example, AZ -> Ba) is caught here even though the glyphs stay in the block. + alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + + result = await MathematicalAlphanumericConverter(style=style).convert_async(prompt=alphabet, input_type="text") + + assert unicodedata.normalize("NFKC", result.output_text) == alphabet + + +async def test_invalid_style_raises_async() -> None: + with pytest.raises(ValueError): + MathematicalAlphanumericConverter(style="not_a_style") + + +async def test_respects_word_selection_strategy_async() -> None: + converter = MathematicalAlphanumericConverter( + style="bold", word_selection_strategy=WordIndexSelectionStrategy(indices=[1]) + ) + + result = await converter.convert_async(prompt="keep change keep", input_type="text") + + # Only the middle word ("change") is styled: c h a n g e -> bold glyphs. + assert result.output_text == "keep \U0001d41c\U0001d421\U0001d41a\U0001d427\U0001d420\U0001d41e keep" + + +async def test_empty_prompt_returns_empty_text_async() -> None: + result = await MathematicalAlphanumericConverter().convert_async(prompt="", input_type="text") + + assert result.output_text == "" + + +async def test_rejects_unsupported_input_type_async() -> None: + with pytest.raises(ValueError): + await MathematicalAlphanumericConverter().convert_async(prompt="hello", input_type="image_path") + + +def test_identifier_includes_style_and_is_stable() -> None: + bold_first = MathematicalAlphanumericConverter(style="bold").get_identifier() + bold_second = MathematicalAlphanumericConverter(style="bold").get_identifier() + fraktur = MathematicalAlphanumericConverter(style="fraktur").get_identifier() + + assert bold_first.class_name == "MathematicalAlphanumericConverter" + assert bold_first.hash == bold_second.hash + # Different styles must produce distinct identifiers. + assert bold_first.hash != fraktur.hash diff --git a/tests/unit/registry/converter_identifier_samples.py b/tests/unit/registry/converter_identifier_samples.py index 117d61e2ee..24e8996e43 100644 --- a/tests/unit/registry/converter_identifier_samples.py +++ b/tests/unit/registry/converter_identifier_samples.py @@ -410,6 +410,7 @@ def make_samples(folder: Path) -> dict[str, tuple[Any, ...]]: "seed": (0, 1), "random_seed": (0, 1), "CaesarConverter.caesar_offset": (1, -1, 2, 0, 24, 25), + "MathematicalAlphanumericConverter.style": ("italic", "script", "fraktur", "monospace"), "trap_template": ( "{prompt} is {wrong_value}", "Is {prompt} {wrong_value}?", diff --git a/tests/unit/scenario/garak/test_encoding.py b/tests/unit/scenario/garak/test_encoding.py index 5e4bd78538..0ae2cfc862 100644 --- a/tests/unit/scenario/garak/test_encoding.py +++ b/tests/unit/scenario/garak/test_encoding.py @@ -253,7 +253,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) == 19 + assert len(all_names) == 20 # The niche/lossy schemes stay ALL-only. assert all_names - default_names == { "braille", @@ -262,6 +262,7 @@ def test_default_aggregate_curates_representative_subset(self): "ascii_smuggler", "bifid", "columnar_transposition", + "mathematical_alphanumeric", } def test_get_aggregate_tags_includes_default(self):