Skip to content

Commit

Permalink
Add all files (0.1.0)
Browse files Browse the repository at this point in the history
  • Loading branch information
tsundokul committed Jul 6, 2020
0 parents commit 0e38d0a
Show file tree
Hide file tree
Showing 15 changed files with 355 additions and 0 deletions.
39 changes: 39 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
*.py[cod]
.python-version

# C extensions
*.so

# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
lib
lib64
.cache

# Installer logs
pip-log.txt

# Unit test / coverage reports
.coverage
coverage.*
.tox
nosetests.xml
htmlcov

# Translations
*.mo

# Mr Developer
.mr.developer.cfg
.project
.pydevproject
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "libradamsa"]
path = libradamsa
url = https://github.com/andreafioraldi/libradamsa
23 changes: 23 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
The MIT License (MIT)

Copyright (c) 2020 Daniel Timofte
Copyright (c) 2019 Andrea Fioraldi
Copyright (c) 2013 Aki Helin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
recursive-include pyradamsa/lib *
75 changes: 75 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
pyradamsa
==========================

`pyradamsa` provides an interface for calling libradamsa methods from within Python, allowing one to perform mutations on byte blocks (aka fuzzing). For more details see [radamsa](https://gitlab.com/akihe/radamsa) (a general-purpose fuzzer) and [libradamsa](https://github.com/andreafioraldi/libradamsa) (precompiled radamsa library).

## Usage
```python
import pyradamsa

rad = pyradamsa.Radamsa()

mydata = b'GET /auth?pass=HelloWorld HTTP1.1'
fuzzed = rad.fuzz(mydata, seed=1337)
print(fuzzed)

> b'GET /auth?pass=HelloWorld HTTP\xc0\xb1.1'

# seed is randomly set if not provided
rad.fuzz(mydata)
> b'\tG\xf3\xa0\x81\x9c\xf7dLET \xe2\x81/aut\xf3\xa0\x80\xafHTTP2.rld HTTP2.rld HTTP3.2\xe1\xa0\x8e9'
rad.fuzz(mydata)
> b'GET /auth?pass=HelloWorld HTTP1.340282366920938463463374607431768211455'
etc.

# enforce static seed on initialization
rad = pyradamsa.Radamsa(seed=0)

# max_mut enforces a maximum length for returned data
# it defaults to (data length + an offset of 4096 bytes)
fuzzed = rad.fuzz(mydata, seed=1337, max_mut=10)
> b'GET /auth?'

# the offset may be overwritten on init
rad = pyradamsa.Radamsa(mut_offset=2048)
```

## Building
Currently wheels are available for linux i686 and x86_64
```sh
# Clone the repo
git clone --recurse-submodules https://github.com/tsundokul/pyradamsa.git
cd pyradamsa

# patch memory leak when reinitializing owl vm
patch libradamsa/libradamsa.c realloc.patch

# OPTIONAL: when using manylinux (https://github.com/pypa/manylinux)
docker run --rm -it -v `pwd`:/io quay.io/pypa/manylinux2010_x86_64 /bin/bash
cd /io && alias python='/opt/python/cp35-cp35m/bin/python3.5'
export PATH="/opt/python/cp35-cp35m/bin/:${PATH}"

# Install requirements
python -m pip install -r requirements.txt

# Build C extension (libradamsa.so)
python setup.py build_ext

# Run tests
./run_tests

# Build wheel
python setup.py bdist_wheel
```

## Contributing
* Fork the repo
* Check out a feature or bug branch
* Add your changes
* Update README when needed
* Submit a pull request to upstream repo
* Add description of your changes
* Ensure tests are passing
* Ensure branch is mergeable

_MIT License, 2020_ [@tim17d](https://twitter.com/tim17d)
1 change: 1 addition & 0 deletions libradamsa
Submodule libradamsa added at 578bd7
2 changes: 2 additions & 0 deletions pyradamsa/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from .pyradamsa import Radamsa
from .version import __version__
85 changes: 85 additions & 0 deletions pyradamsa/pyradamsa.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@

from ctypes import *
from glob import glob
from os import path
from random import randint
from sys import maxsize

class Radamsa():

def __init__(self, seed=None, mut_offset=4096):
self.seed = seed
self.mut_offset = mut_offset

# Load shared library
self.LIB = CDLL(self.lib_path())

# Set word size and max value for seeds
self.MAX_WORD = maxsize * 2 + 1
_is_64 = self.MAX_WORD.bit_length() // 64
self.C_WORD = c_uint64 if _is_64 else c_uint32

# Declare ctypes interfaces for functions
self._declare_sigs()


def _declare_sigs(self):
"""C signatures for libradamsa functions
extern void init()
extern size_t radamsa(uint8_t * ptr, size_t len, uint8_t * target,
size_t max, unsigned int seed)
extern size_t radamsa_inplace(uint8_t * ptr, size_t len,
size_t max, unsigned int seed)"""
self.LIB.init.argtypes = []
self.LIB.init.restype = None

self.LIB.radamsa.restype = c_size_t
self.LIB.radamsa.argtypes = [POINTER(c_uint8), c_size_t,
POINTER(c_uint8), c_size_t, self.C_WORD]

self.LIB.radamsa_inplace.restype = c_size_t
self.LIB.radamsa_inplace.argtypes = [
POINTER(c_uint8), c_size_t, c_size_t, self.C_WORD]

def fuzz(self, data, seed=None, max_mut=None):
# (re) initialize OWL/Scheme VM to ensure output repeatability,
# otherwise the VM's heap will get corrupted
self.LIB.init()

if seed is None:
if self.seed is None:
seed = randint(0, self.MAX_WORD)
else:
seed = self.seed

seed = self.C_WORD(seed & self.MAX_WORD)
data_len = len(data)
data_to_mutate = (c_uint8 * data_len)(*data)

length = c_size_t(data_len)
_max_mut = max_mut or data_len + self.mut_offset
max_mut = c_size_t(_max_mut)

# Adjust destination buffer in regard to max_mut
buffer = (c_uint8 * _max_mut)()

self.LIB.radamsa(
data_to_mutate,
length,
buffer,
max_mut,
seed
)

return c_char_p(addressof(buffer)).value

@staticmethod
def lib_path():
mod_dir = path.dirname(path.realpath(__file__))
lib_dir = path.join(mod_dir, 'lib', 'libradamsa*')
so_list = glob(lib_dir)

if len(so_list) != 1:
raise Exception('No shared library found in module tree')

return so_list[0]
1 change: 1 addition & 0 deletions pyradamsa/version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = '0.1.0'
11 changes: 11 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[pytest]
norecursedirs = venv* .*
addopts =
-r fEsxXw
-vvv
--doctest-modules
--ignore setup.py
--cov-report=term-missing
--cov-report=html
--cov=pyradamsa
--maxfail=1
19 changes: 19 additions & 0 deletions realloc.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
--- libradamsa.c 2020-07-05 14:57:45.515792769 +0300
+++ libradamsa2.c 2020-07-05 15:03:20.383799887 +0300
@@ -4854,13 +4854,15 @@
#include <radamsa.h>

void init() {
+ if (memstart != NULL)
+ free(memstart);
int nobjs=0, nwords=0;
hp = (byte *) &heap; /* builtin heap */
state = IFALSE;
heap_metrics(&nwords, &nobjs);
max_heap_mb = (W == 4) ? 4096 : 65535;
nwords += nobjs + INITCELLS;
- memstart = genstart = fp = (word *) realloc(NULL, (nwords + MEMPAD)*W);
+ memstart = genstart = fp = (word *) malloc((nwords + MEMPAD)*W);
if (!memstart) return;
memend = memstart + nwords - MEMPAD;
state = (word) load_heap(nobjs);
3 changes: 3 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pytest
pytest-cov
setuptools
11 changes: 11 additions & 0 deletions run_tests
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/bin/bash

find . \( \
-name '__pycache__' -or \
-name '*.pyc' -or \
-name '.pytest_cache' -or \
-name 'build' -or \
-name 'htmlcov' -or \
-name '.eggs' \) | xargs rm -rf

pytest
40 changes: 40 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@

from setuptools import setup, Extension, find_packages
from pyradamsa.version import __version__

libradamsa = Extension('libradamsa',
sources=['libradamsa/libradamsa.c'],
include_dirs=['libradamsa'],
py_limited_api=True,
extra_compile_args=['-O3', '-lrt']
)

setup(name='pyradamsa',
version=__version__,
description='Python bindings for radamsa fuzzing library.',
long_description_content_type='text/markdown',
long_description=open('README.md').read().strip(),
author='Daniel Timofte @tim17d',
author_email='timofte.daniel@tuta.io',
url='https://github.com/tsundokul/pyradamsa',
py_modules=['pyradamsa'],
install_requires=[],
license='MIT License',
zip_safe=False,
keywords='radamsa fuzzing libradamsa',
packages=['pyradamsa'],
include_package_data=True,
setup_requires=["wheel"],
classifiers=[
"Development Status :: 4 - Beta",
"Topic :: Security",
"Operating System :: POSIX :: Linux",
"License :: OSI Approved :: MIT License",
'Programming Language :: Python :: 3',
],
ext_modules=[libradamsa],
options={
'bdist_wheel': {'python_tag': 'cp30', 'py_limited_api': 'cp32'},
'build_ext': {'build_lib': 'pyradamsa/lib'}
}
)
41 changes: 41 additions & 0 deletions tests/test_lib.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import ctypes
import pytest
import pyradamsa
import sys
import unittest

def test_lib_present():
assert len(pyradamsa.Radamsa.lib_path()) > 0, 'library not found'

def test_lib_symbols():
lib = ctypes.CDLL(pyradamsa.Radamsa.lib_path())
assert hasattr(lib, 'init')
assert hasattr(lib, 'radamsa')
assert hasattr(lib, 'radamsa_inplace')

def test_default_attrs():
assert pyradamsa.Radamsa().mut_offset == 4096

r = pyradamsa.Radamsa(17, 2048)
assert r.seed == 17
assert r.mut_offset == 2048

r = pyradamsa.Radamsa(mut_offset=19)
assert r.mut_offset == 19
assert r.seed == None

@pytest.fixture
def data():
return b'GET /auth?pass=HelloWorld HTTP1.1'

def test_seed_arg(data):
assert pyradamsa.Radamsa().fuzz(
data, seed=1337) == b'GET /auth?pass=HelloWorld HTTP\xc0\xb1.1'

def test_seed_wraparound(data):
r = pyradamsa.Radamsa()
assert r.fuzz(data, -1) == r.fuzz(data, sys.maxsize * 2 + 1)

def test_seed_static(data):
r = pyradamsa.Radamsa(1337)
assert r.fuzz(data) == r.fuzz(data)

0 comments on commit 0e38d0a

Please sign in to comment.