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
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, 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",
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, 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
Expand Down
2 changes: 2 additions & 0 deletions pyrit/converter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down
106 changes: 106 additions & 0 deletions pyrit/converter/_character_substitution_converter.py
Original file line number Diff line number Diff line change
@@ -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)
104 changes: 30 additions & 74 deletions pyrit/converter/leetspeak_converter.py
Original file line number Diff line number Diff line change
@@ -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,
*,
Expand All @@ -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.
Expand All @@ -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 = (
Expand All @@ -125,26 +95,12 @@ 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.

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)
83 changes: 83 additions & 0 deletions pyrit/converter/pigpen_converter.py
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading