ChepyCore class

The ChepyCore class for Chepy is primarily used as an interface for all the current modules/classes in Chepy, or for plugin development. The ChepyCore class is what provides the various attributes like states, buffers, etc and is required to use and extend Chepy.

The most important ChepyCore attributes and methods are:

  • state The state is where all objects are always stored when modified by any methods.

  • _convert_to_* methods These are helper methods that ensures data is being accessed and put in the state in the correct manner. For example, binasii.unhexlify requires a bytes like object. We can use

self.state = binasii.unhexlify(self._convert_to_bytes())

This will ensure that the correct data type is being used at all times.

class chepy.core.ChepyCore(*data)

The ChepyCore class for Chepy is primarily used as an interface for all the current modules/classes in Chepy, or for plugin development. The ChepyCore class is what provides the various attributes like states, buffers, etc and is required to use and extend Chepy.

Parameters

*data (tuple) – The core class takes arbitrary number of arguments as *args.

states

Contains all the current states. Each arg passed to the ChepyCore class will be considered a state.

Type

dict

buffers

Contains all the current buffers if a buffer is saved.

Type

dict

state

The data in the current state. The state changes each time a Chepy method is called.

Type

Any

Returns

The Chepy object.

Return type

Chepy

_abs_path(path: str)

Returns the absolute path by expanding home dir

Parameters

path (str) – Path to expand

Returns

Path object

Return type

object

_bytes_to_str(s: bytes) str

Converts a bytes to str

Parameters

s (str) – String

Returns

String

Return type

str

_convert_to_bytearray() bytearray

Attempts to coerce the current state into a bytesarray object

_convert_to_bytes() bytes

This method is used to coerce the current object in the state variable into a bytes. The method should be called inside any method that operates on a string object instead of calling self.state directly to avoid errors.

Raises

NotImplementedError – If type coercian isn’t available for the current state type.

_convert_to_int() int

This method is used to coerce the current object in the state variable into an int. The method should be called inside any method that operates on a int types instead of calling self.state directly to avoid errors.

Raises

NotImplementedError – If type coercian isn’t available for the current state type.

_convert_to_str() str

This method is used to coerce the current object in the state variable into bytes. The method should be called inside any method that operates on a bytes object instead of calling self.state directly to avoid errors.

Raises

NotImplementedError – If type coercian isn’t available for the current state type.

_error_logger(data: str) None

Just a binding for logger.error

Parameters

data (str) – Message to log

Returns

The Chepy object.

Return type

Chepy

_get_nested_value(data, key, split_by='.')

Get a dict value based on a string key with dot notation. Supports array indexing. If split_by is None or “”, returns only the first key

Parameters
  • data (dict) – Data

  • key (str) – Dict key in a dot notation and array

  • split_by (str, optional) – Chars to split key by. Defaults to “.”.

_info_logger(data: str) None

Just a binding for logger.info

Parameters

data (str) – Message to log

Returns

The Chepy object.

Return type

Chepy

_load_as_file() object

This method is used when a function or a method expects a file path to load a file. Instead of passing a file path, this method allows passing an io.BytesIO object instead.

Returns

io.BytesIO object

Return type

object

_pickle_class(obj: Any) Any

This method takes another object as an argument and pickels that into a json object using jsonpickel. The return value is a dictionary

Parameters

obj (Any) – Any object

Returns

unpickeled JSON as a python object.

Return type

Any

_str_to_bytes(s: str) bytes

Converts a str to bytes

Parameters

s (str) – String

Returns

Bytes

Return type

bytes

_to_bytes(data: Any) bytes

This method is used to coerce data to bytes. The method should be called inside any method that operates on a string object instead of calling self.state directly to avoid errors.

Raises

NotImplementedError – If type coercian isn’t available for the current state type.

_warning_logger(data: str) None

Just a binding for logger.warning

Parameters

data (str) – Message to log

Returns

The Chepy object.

Return type

Chepy

callback(callback_function: Callable[[Any], Any])

Run any user defined python function against the state. This method is not recorded in the recipes

Parameters

callback_function (Callable[[Any], Any]) – The function to run. The function should take one argument (the state is passed to it). It can return Any

Examples

from chepy import Chepy

def cb(data):

return data * 2

c = Chepy(‘abc’).callback(cb) # state is now abcabc

Returns

The Chepy object.

Return type

Chepy

change_state(index: int)

Change current state by index

Same behaviour as switch_state

Parameters

index (int) – Index of new state

Raises

TypeError – If specified index does not exist

Returns

The Chepy object.

Return type

Chepy

copy() None

Copy to clipboard

Copy the final output to the clipboard. If an error is raised, refer to the documentation on the error.

Returns

Copies final output to the clipboard

Return type

None

copy_state(index: int = None)

Copy the current state to a new state

Parameters

index (int) – Index of new state. Defaults to next available.

Returns

The Chepy object.

Return type

Chepy

copy_to_clipboard() None

Copy to clipboard

Copy the final output to the clipboard. If an error is raised, refer to the documentation on the error.

Returns

Copies final output to the clipboard

Return type

None

create_state()

Create a new empty state

Returns

The Chepy object.

Return type

Chepy

debug(verbose: bool = False)

Debug the current instance of Chepy

This method does not change the state.

Parameters

verbose (bool, optional) – Show verbose info. Defaults to False.

Returns

The Chepy object.

Return type

Chepy

delete_buffer(index: int)

Delete a buffer item

Parameters

index (int) – Key of buffer item

Returns

The Chepy object.

Return type

Chepy

delete_state(index: int)

Delete a state specified by the index

Parameters

index (int) – Index of state

Returns

The Chepy object.

Return type

Chepy

for_each(methods: List[Tuple[Union[str, object], dict]], merge: Optional[Union[str, bytes]] = None)

Run multiple methods on current state if it is a list

Method names in a list of tuples. If using in the cli, this should not contain any spaces.

Parameters
  • methods (List[Tuple[Union[str, object], dict]]) – Required. List of tuples

  • merge (Union[str, bytes, None]) – Merge data with. Defaults to None

Returns

The Chepy object.

Return type

Chepy

Examples

This method takes an array of method names and their args as an list of tuples; the first value of the tuple is the method name as either a string, or as an object, and the second value is a ditionary of arguments. The keys of in the dictionary are method argument names, while the values are argument values.

>>> from chepy import Chepy
>>> c = Chepy(['41', '42'])
>>> c.for_each([("from_hex",), ("to_hex",)])
>>> # this is how to use fork methods with a string
>>> c.for_each([(c.from_hex,), (c.to_hex,)])
>>> # This is how to use fork using methods
>>> print(c)
['41', '42']
fork(methods: List[Tuple[Union[str, object], dict]])

Run multiple methods on all available states

Method names in a list of tuples. If using in the cli, this should not contain any spaces.

Parameters

methods (List[Tuple[Union[str, object], dict]]) – Required. List of tuples

Returns

The Chepy object.

Return type

Chepy

Examples

This method takes an array of method names and their args as an list of tuples; the first value of the tuple is the method name as either a string, or as an object, and the second value is a ditionary of arguments. The keys of in the dictionary are method argument names, while the values are argument values.

>>> from chepy import Chepy
>>> c = Chepy("some", "data")
>>> c.fork([("to_hex",), ("hmac_hash", {"secret_key": "key"})])
>>> # this is how to use fork methods with a string
>>> c.fork([(c.to_hex,), (c.hmac_hash, {"secret_key": "key"})])
>>> # This is how to use fork using methods
>>> print(c.states)
{0: 'e46dfcf050c0a0d135b73856ab8e3298f9cc4105', 1: '1863d1542629590e3838543cbe3bf6a4f7c706ff'}
get_by_index(index: int)

Get an item by specifying an index

Parameters

index (int) – Index number to get

Returns

The Chepy object.

Return type

Chepy

get_by_key(key: str, split_key: str = '.')

Get value from a dict. Supports nested keys and arrays.

Parameters
  • key (Union[Hashable, None]) – Keys to extract.

  • split_key (str, optional) – Split nested keys. Defaults to “.”

  • nested (bool, optional) – If the specified keys are nested. Supports array indexing. Defaults to True

Returns

The Chepy object.

Return type

Chepy

get_register(key: str) Union[str, bytes]

Get a value from registers by key

Parameters

key (str) – Key

Raises

ValueError – If key does not exist

Returns

Value of register

Return type

Union[str, bytes]

get_state(index: int) Any

Returns the value of the specified state.

This method does not chain with other methods of Chepy

Parameters

index (int) – The index of the state

Returns

Any value that is in the specified state

Return type

Any

http_request(method: str = 'GET', params: dict = {}, json: dict = None, headers: dict = {}, cookies: dict = {})

Make a http/s request

Make a HTTP/S request and work with the data in Chepy. Most common http methods are supported; but some methods may not provide a response body.

Parameters
  • method (str, optional) – Request method. Defaults to ‘GET’.

  • params (dict, optional) – Query Args. Defaults to {}.

  • json (dict, optional) – Request payload. Defaults to None.

  • headers (dict, optional) – Headers for request. Defaults to {}.

  • cookies (dict, optional) – Cookies for request. Defaults to {}.

Raises
  • NotImplementedError – If state is not a string or dictionary

  • requests.RequestException – If response status code is not 200

Returns

A dictionary containing body, status and headers. The Chepy object.

Return type

Chepy

Examples

By default, this methed with make a GET request, But supports most common methods.

>>> c = Chepy("http://example.com").http_request()
>>> c.get_by_key("headers")

This method can also be used to make more complex requests by specifying headers, cookies, body data etc.

>>> c = Chepy("https://en4qpftrmznwq.x.pipedream.net")
>>> c.http_request(
>>>    method="POST",
>>>    headers={"My-header": "some header"},
>>>    json={"some": "data"}
>>> )
>>> print(c.get_by_key("body"))
{"success": true}
load_buffer(index: int)

Load the specified buffer into state

Parameters

index (int) – Index key of an existing buffer

Returns

The Chepy object.

Return type

Chepy

Examples

>>> c = Chepy("A").save_buffer()
>>> # this saves the current value of state to a new buffer
>>> c.to_hex()
>>> # operate on a state, in this case, convert to hex.
>>> c.state
"41"
>>> c.buffers
{0: "A"}
>>> c.load_buffer(0)
>>> # loads the content of the buffer back into the current state.
>>> c.state
"A"
load_command()

Run the command in state and get the output

Returns

The Chepy object.

Return type

Chepy

Examples

This method can be used to interface with the shell and Chepy directly by ingesting a commands output in Chepy.

>>> c = Chepy("ls -l").shell_output().o
test.html
...
test.py
load_dir(pattern: str = '*')

Load all file paths in a directory

Parameters

pattern (str, optional) – File pattern to match. Defaults to “*”.

Returns

The Chepy object.

Return type

Chepy

load_file(binary_mode: bool = False)

If a path is provided, load the file

Parameters

binary_mode (bool, optional) – Force load in binary mode.

Returns

The Chepy object.

Return type

Chepy

Examples

>>> c = Chepy("/path/to/file")
>>> # at the moment, the state only contains the string "/path/to/file"
>>> c.load_file() # this will load the file content into the state
load_from_url(method: str = 'GET', params: dict = {}, json: dict = None, headers: dict = {}, cookies: dict = {})

Load binary content from a url

Most common http methods are supported; but some methods may not provide a response body.

Parameters
  • method (str, optional) – Request method. Defaults to ‘GET’.

  • params (dict, optional) – Query Args. Defaults to {}.

  • json (dict, optional) – Request payload. Defaults to None.

  • headers (dict, optional) – Headers for request. Defaults to {}.

  • cookies (dict, optional) – Cookies for request. Defaults to {}.

Raises
  • NotImplementedError – If state is not a string or dictionary

  • requests.RequestException – If response status code is not 200

Returns

A bytearray of the response content. The Chepy object.

Return type

Chepy

Examples

By default, this methed with make a GET request, But supports most common methods.

>>> c = Chepy("http://example.com/file.png").load_from_url()
>>> b'\x89PNG...'
load_recipe(path: str)

Load and run a recipe

Parameters

path (str) – Path to recipe file

Returns

The Chepy object.

Return type

Chepy

Examples

>>> c = Chepy("some data").load_recipe("/path/to/recipe").out
NzM2ZjZkNjUyMDY0NjE3NDYx
loop(iterations: int, callback: str, args: dict = {})

Loop and apply callback n times

Parameters
  • iterations (int) – Number of iterations to loop

  • callback (str) – The Chepy method to loop over

  • args (dict, optional) – Optional arguments for the callback. Defaults to {}.

Returns

The Chepy object.

Return type

Chepy

Examples

>>> c = Chepy("VmpGb2QxTXhXWGxTYmxKV1lrZDRWVmx0ZEV0alZsSllaVWRHYWxWVU1Eaz0=")
>>> c.loop(iterations=6, callback='hmac_hash', args={'key': 'secret'})
securisec
loop_dict(keys: list, callback: str, args: dict = {})

Loop over a dictionary and apply the callback to the value

Parameters
  • keys (list) – List of keys to match. If in cli, dont use spaces.

  • callback (str) – Chepy method as string

  • args (dict, optional) – Dictionary of args. If in cli, dont use spaces. Defaults to {}.

Returns

The Chepy object.

Return type

Chepy

Examples

>>> c = Chepy({'some': 'hahahaha', 'lol': 'aahahah'})
>>> c.loop_dict(['some'], 'hmac_hash', {'key': 'secret'}).o
{'some': '99f77ec06a3c69a4a95371a7888245ba57f47f55', 'lol': 'aahahah'}

We can combine loop_list and loop_dict to loop over a list of dictionaries.

>>> data = [{"some": "val"}, {"some": "another"}, {"lol": "lol"}, {"another": "aaaa"}]
>>> c = Chepy(data)
>>> c.loop_list("loop_dict", {"keys": ["some", "lol"], "callback": "to_upper_case"})
[
    {"some": "VAL"},
    {"some": "ANOTHER"},
    {"lol": "LOL"},
    {"another": "aaaa"},
]
loop_list(callback: str, args: dict = {})

Loop over an array and run a Chepy method on it

Parameters
  • callback (str) – Chepy method as string

  • args (dict, optional) – Dictionary of args. If in cli, dont use spaces. Defaults to {}.

Returns

The Chepy object

Return type

Chepy

Examples

This method is capable of running a callable from either a string, or a chepy method.

>>> c = Chepy(["an", "array"])
>>> c.loop_list('to_hex').loop_list('hmac_hash', {'key': 'secret'})
['5cbe6ca2a66b380aec1449d4ebb0d40ac5e1b92e', '30d75bf34740e8781cd4ec7b122e3efd8448e270']
plugins(enable: str) None

Use this method to enable or disable Chepy plugins.

Valid options are true or false. Once this method completes, it does call sys.exit().

Parameters

enable (str) – Set to true or false

Returns

None

pretty(indent: int = 2)

Prettify the state.

Parameters

indent (int, optional) – Indent level. Defaults to 2.

Returns

The Chepy object.

Return type

Chepy

register(pattern: Union[str, bytes], ignore_case: bool = False, multiline: bool = False, dotall: bool = False, unicode: bool = False, extended: bool = False)

Extract data from the input and store it in registers. Regular expression capture groups are used to select the data to extract.

Parameters
  • pattern (Union[str, bytes]) – Required. The regex pattern to search by

  • ignore_case (bool, optional) – Set case insensitive flag. Defaults to False.

  • multiline (bool, optional) – ^/$ match start/end. Defaults to False.

  • dotall (bool, optional) – . matches newline. Defaults to False.

  • unicode (bool, optional) – Match unicode characters. Defaults to False.

  • extended (bool, optional) – Ignore whitespace. Defaults to False.

Returns

The Chepy object.

Return type

Chepy

Examples

>>> c = Chepy("hello world")
>>> c.register("(hello)\s(world)")
>>> c._registers
{'$R0': 'hello', '$R1': 'world'}
reset()

Reset states back to their initial values

Returns

The Chepy object.

Return type

Chepy

run_recipe(recipes: List[Mapping[str, Union[str, Mapping[str, Any]]]])

Run a recipe on the state. All arguments including optional needs to be specified for a recipe.

Parameters

recipes (List[Mapping[str, Union[str, Mapping[str, Any]]]]) – An array of recipes. Recipes are in the format {‘function’: ‘function_name’, ‘args’: {‘arg_name’: ‘arg_val’}}

Returns

The Chepy object.

Return type

Chepy

Examples

>>> c = Chepy('bG9sCg==').run_recipe([{"function":"base64_decode","args":{"custom":None}}]])
>>> lol
In this example, we are calling the base64 decode method on the state.
run_script(path: str, save_state: bool = False)

Inject and run a custom script on the state. The custom script must have a function called cpy_script which must take one argument. The state is passed as the argument.

Parameters
  • path (str) – Path to custom script

  • save_state (bool, optional) – Save script output to the state. Defaults to False.

Returns

The Chepy object.

Return type

Chepy

Examples

>>> c = Chepy("A").to_hex().run_script('tests/files/script.py', True)
b'4141'
save_buffer(index: int = None)

Save current state in a buffer

Buffers are temporary holding areas for anything that is in the state. The state can change, but the buffer does not. Can be chained with other methods. Use in conjunction with load_buffer to load buffer back into the state.

Parameters

index (int, optional) – The index to save the state in, defaults to next index if None

Returns

The Chepy object.

Return type

Chepy

save_recipe(path: str)

Save the current recipe

A recipe will be all the previous methods called on the chepy instance along with their args

Parameters

path (str) – The path to save the recipe

Returns

The Chepy object.

Return type

Chepy

Examples

>>> c = Chepy("some data").to_hex().base64_encode()
>>> c.save_recipe("/path/to/recipe)
>>> c.out
NzM2ZjZkNjUyMDY0NjE3NDYx
set_plugin_path(path: str) None

Use this method to set the path for Chepy plugins.

Parameters

path (str) – Path to plugins directory

Returns

None

set_register(key: str, val: Union[str, bytes])

Set the value of a register

Parameters
  • key (str) – Key

  • val (Union[str, bytes]) – Value

Returns

The Chepy object.

Return type

Chepy

set_state(data: Any)

Set any arbitrary values in the current state

This method is simply changing the value of the instantiated state with an arbitrary value.

Parameters

data (Any) – Any data type

Returns

The Chepy object.

Return type

Chepy

Examples

>>> c = Chepy("some data")
>>> print(c.state)
some data
>>> c.set_state("New data")
>>> print(c.state)
New data
subsection(pattern: Union[str, bytes], methods: List[Tuple[Union[str, object], dict]], group: int = 0)

Run specified methods over a subsection of the state. This method will always treat the state as bytes.

Parameters
  • pattern (Union[str, bytes]) – Regex pattern to match against.

  • methods (List[Tuple[Union[str, object], dict]]) – Required. List of tuples. The first value of the tuple is the method name, the second value is a dictionary of arguments.

  • group (int, optional) – Matching group. Defaults to 0.

Returns

_description_

Return type

_type_

substring(pattern: str, group: int = 0)

Choose a substring from current state as string

The preceding methods will only run on the substring and not the original state. Group capture is supported.

Parameters
  • pattern (str) – Pattern to match.

  • group (int, optional) – Group to match. Defaults to 0.

Returns

The Chepy object.

Return type

Chepy

switch_state(index: int)

Switch current state by index

Same behaviour as change_state

Parameters

index (int) – Index of new state

Raises

TypeError – If specified index does not exist

Returns

The Chepy object.

Return type

Chepy

web(magic: bool = False, cyberchef_url: str = 'https://gchq.github.io/CyberChef/') None

Opens the current string in CyberChef on the browser as hex

Parameters
  • magic (bool, optional) – Start with the magic method in CyberChef

  • cyberchef_url (string, optional) – Base url for Cyberchef

Returns

Opens the current data in CyberChef

Return type

None

write_binary(path: str) None

Save the state to disk. Return None.

Parameters

path (str) – The file path to save in.

Returns

Returns None

Return type

None

Examples

>>> c = Chepy("some data").write_binary('/some/path/file')
write_to_file(path: str) None

Save the state to disk. Return None.

Parameters

path (str) – The file path to save in.

Returns

Returns None

Return type

None

Examples

>>> c = Chepy("some data").write_to_file('/some/path/file', as_binary=True)
_current_index

Value of the initial state

_initial_states

Holder for the initial state

_registers

Holds register values

_stack

Holds all the methods that are called/chained and their args

bake

Alias for out

cyberchef

Alias for web

log_format

Log format message

log_level

Log level

property o

Get the final output

Returns

Final output

Return type

Any

property out: Any

Get the final output

Returns

Final output

Return type

Any

read_file

Alias for load_file

property recipe: List[Dict[str, Union[str, Dict[str, Any]]]]

Returns the current recipe. This is a list of dictionaries that contains the method name and the arguments.

Returns

The recipe.

Return type

List[Dict[str, Union[str, Dict[str, Any]]]]

property state
write

Alias for write_to_file

class chepy.core.ChepyDecorators

A class to house all the decorators for Chepy

static call_stack(func)

This decorator is used to get the method name and arguments and save it to self.stack. The data from self.stack is predominantly used to save recepies.

static is_stdout(func)

Detect if method is being called from the cli