Skip to content
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
8316e8d
Add basic fuzz tests for a few common builtin functions.
ssbr Jul 21, 2017
f47f875
Remove fuzzing of hash() per comment by kcc / oss-fuzz-team.
ssbr Jul 25, 2017
d112252
Move LLVMFuzzerTestOneInput into cpython and tweak how test discovery…
ssbr Jul 25, 2017
cb9cdc0
Move the fuzzer to C++ so that it builds.
ssbr Jul 25, 2017
7028614
Run the fuzz smoke tests on a little more input, just for kicks.
ssbr Jul 26, 2017
2b34f07
Make the _fuzz module optional.
ssbr Jul 26, 2017
f77be65
Actually run the fuzz tests...
ssbr Jul 26, 2017
778c827
Use unittest.main instead of test.support.
ssbr Jul 26, 2017
bc3d33f
Use C-style comments. (For porting to Python 2.7 and C89).
ssbr Jul 27, 2017
dee024f
Fix build break I accidentally introduced in f77be65.
ssbr Jul 27, 2017
9a00b23
Add a little detail on what the heck this stuff even is, in readme.
ssbr Jul 27, 2017
d542130
s/fuzzer.c/fuzzer.cpp/
ssbr Jul 27, 2017
9f16dd4
fuzzer.cpp -> fuzzer.c in faith that I can make it build.
ssbr Aug 3, 2017
aa6d784
Make _fuzz required, so that tests never fail on a successful build.
ssbr Aug 23, 2017
fa0af73
Fix the windows test failure by just not testing on windows. :)
ssbr Aug 23, 2017
4af5c11
NEWS entry thingermajig.
ssbr Aug 24, 2017
fb017ed
Blacklist test_fuzz from coverage tests. It seems to fail with a Memo…
ssbr Aug 24, 2017
c4eda5d
Remove outdated comment.
ssbr Aug 24, 2017
83967f9
Fix incorrect mod for base (should be % 37), and document why we're t…
ssbr Aug 25, 2017
52dccc2
Use more idiomatic NULL checks rather than PyErr_Occurred().
ssbr Aug 25, 2017
4327fd9
Attempt to explain a little more why these exist / what the relations…
ssbr Aug 25, 2017
6da8e97
Renamed _fuzz to _xxtestfuzz and cleanup.
gpshead Sep 6, 2017
43620ae
don't skip test_fuzz (besides, it was renamed)
gpshead Sep 6, 2017
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: 3 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ matrix:
./venv/bin/python -m pip install -U coverage
script:
# Skip tests that re-run the entire test suite.
- ./venv/bin/python -m coverage run --pylib -m test -uall,-cpu -x test_multiprocessing_fork -x test_multiprocessing_forkserver -x test_multiprocessing_spawn
# Also skip test_fuzz, it seems to be broken sometimes, and the coverage
# results are not interesting.
- ./venv/bin/python -m coverage run --pylib -m test -uall,-cpu -x test_multiprocessing_fork -x test_multiprocessing_forkserver -x test_multiprocessing_spawn -x test_fuzz
after_script: # Probably should be after_success once test suite updated to run under coverage.py.
# Make the `coverage` command available to Codecov w/ a version of Python that can parse all source files.
- source ./venv/bin/activate
Expand Down
21 changes: 21 additions & 0 deletions Lib/test/test_fuzz.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import test.support
import unittest

_fuzz = test.support.import_module('_fuzz')

class TestFuzz(unittest.TestCase):

def test_fuzz(self):
"""Run the fuzz tests on sample input.

This isn't meaningful and only checks it doesn't crash.
"""
_fuzz.run(b"")
_fuzz.run(b"\0")
_fuzz.run(b"{")
_fuzz.run(b" ")
_fuzz.run(b"x")
_fuzz.run(b"1")

if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add fuzz tests for float(str), int(str), unicode(str); for oss-fuzz.
41 changes: 41 additions & 0 deletions Modules/_fuzz/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
Fuzz Tests for CPython
======================

These fuzz tests are designed to be included in Google's `oss-fuzz`_ project.

oss-fuzz works against a library exposing a function of the form
``int LLVMFuzzerTestOneInput(const uint8_t* data, size_t length)``. We provide
that library (``fuzzer.c``), and include a ``_fuzz`` module for testing with
some toy values -- no fuzzing occurs in Python's test suite.

Adding a new fuzz test
----------------------

Add the test name on a new line in ``fuzz_tests.txt``.

In ``fuzzer.c``, add a function to be run::

int $test_name (const char* data, size_t size) {
...
return 0;
}


And invoke it from ``LLVMFuzzerTestOneInput``::

#if _Py_FUZZ_YES(fuzz_builtin_float)
rv |= _run_fuzz(data, size, fuzz_builtin_float);
#endif

``LLVMFuzzerTestOneInput`` will run in oss-fuzz, with each test in
``fuzz_tests.txt`` run separately.

What makes a good fuzz test
---------------------------

Libraries written in C that might handle untrusted data are worthwhile. The
more complex the logic (e.g. parsing), the more likely this is to be a useful
fuzz test. See the existing examples for reference, and refer to the
`oss-fuzz`_ docs.

.. _oss-fuzz: https://github.com/google/oss-fuzz
52 changes: 52 additions & 0 deletions Modules/_fuzz/_fuzzmodule.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#include <Python.h>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we really need this module? It's only usage seems to be for the tests, and it looks like it has as much code as the fuzzers themselves!

@ssbr ssbr Jul 26, 2017 •

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.

Sure, but this would be like 2 lines in Cython. It's just the typical boilerplate of extension modules, nothing to write home about, right?

We don't need it. The thing we need is to make sure that the fuzz tests are maintained and don't break. That is, they need to be in CI for Python, not just run in the fuzz suite in oss-fuzz.

For most ways it could break, it would be enough just to build them, but not run them. I think it is a good idea to also run them. Although there's a cost: the macro silliness to make them runnable individually and collectively probably makes it easy to screw up, so I'm not happy about it. (Every fuzz test name is repeated like four times.) The strategy you mentioned above would make it less error prone, at the cost of losing the ability to call them from a unit test like this.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

To me what I see in this code is pretty standard CPython API calls. That raises the question of if there is a good reason to check these in and keep them working as part of CPython or if this code should be a stand alone module available on pypi that people could use to launch fuzz tests of any Python interpreter it is built with. The answer to that question likely comes from answering how oss-fuzz the fuzz testing service works. If it monitors our github repo and reruns fuzz tests as things change in cpython, including these here may make sense. I think a comment describing the situation and why this exists here with links to relevant oss-fuzz documentation (either in here or in the _fuzz/README.rst) would help that.

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.

I've added a little to README.rst, but to summarize and expand here:

You're correct that oss-fuzz regularly pulls from CPython and runs the fuzz tests locally.

oss-fuzz prefers to have the tests be a tested part of the upstream project so that they don't break. Certainly not all of these fuzz tests are using the public API (e.g._Py_HashBytes), and there will be more in the future. Those are more likely to they might break in the future -- having them here ensures that breaking them would break the tests, and they will always be good to run, hopefully.

We could keep the public-API-using fuzz tests separate in oss-fuzz, but they wouldn't really like that, and that actually splits up the tests in a confusing way -- some would be here, some would be in the oss-fuzz repo. I think they're better off all being here.

#include <stdlib.h>
#include <inttypes.h>

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size);

static PyObject* _fuzz_run(PyObject* self, PyObject* args) {
const char* buf;
size_t size;
if (!PyArg_ParseTuple(args, "s#", &buf, &size)) {
return NULL;
}
int rv = LLVMFuzzerTestOneInput((const uint8_t*)buf, size);
if (PyErr_Occurred()) {
return NULL;
}
if (rv != 0) {
// Nonzero return codes are reserved for future use.
PyErr_Format(
PyExc_RuntimeError, "Nonzero return code from fuzzer: %d", rv);
return NULL;
}
Py_RETURN_NONE;
}

static PyMethodDef module_methods[] = {
{"run", (PyCFunction)_fuzz_run, METH_VARARGS, ""},
{NULL},
};

static struct PyModuleDef _fuzzmodule = {
PyModuleDef_HEAD_INIT,
"_fuzz",
NULL,
0,
module_methods,
NULL,
NULL,
NULL,
NULL
};

PyMODINIT_FUNC
PyInit__fuzz(void)
{
PyObject *m = NULL;

if ((m = PyModule_Create(&_fuzzmodule)) == NULL) {
return NULL;
}
return m;
}
3 changes: 3 additions & 0 deletions Modules/_fuzz/fuzz_tests.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
fuzz_builtin_float
fuzz_builtin_int
fuzz_builtin_unicode
118 changes: 118 additions & 0 deletions Modules/_fuzz/fuzzer.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/* A fuzz test for CPython.

Unusually for CPython, this is written in C++ for the benefit of linking with

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Scanning though this, it looks like C to me (as the filename suggests).

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.

Oops. Fixed.

libFuzzer.

The only exposed function is LLVMFuzzerTestOneInput, which is called by
fuzzers and by the _fuzz module for smoke tests.

To build exactly one fuzz test, as when running in oss-fuzz etc.,
build with -D _Py_FUZZ_ONE and -D _Py_FUZZ_<test_name>. e.g. to build
LLVMFuzzerTestOneInput to only run "fuzz_builtin_float", build this file with
-D _Py_FUZZ_ONE -D _Py_FUZZ_fuzz_builtin_float.

See the source code for LLVMFuzzerTestOneInput for details. */

#include <Python.h>
#include <stdlib.h>
#include <inttypes.h>

/* Fuzz PyFloat_FromString as a proxy for float(str). */
static int fuzz_builtin_float(const char* data, size_t size) {
PyObject* s = PyBytes_FromStringAndSize(data, size);
if (s == NULL) return 0;
PyObject* f = PyFloat_FromString(s);
if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_ValueError)) {
PyErr_Clear();
}

Py_XDECREF(f);
Py_DECREF(s);
return 0;
}

/* Fuzz PyLong_FromUnicodeObject as a proxy for int(str). */
static int fuzz_builtin_int(const char* data, size_t size) {
int base = _Py_HashBytes(data, size) % 36;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Comment on what you are doing here. it looks like choosing a random base value in the 0..35 range based on the random input data. why that specific range?

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.

Uh. That range is a bug! It should be [0] union [2..36], not [0] union [2..35] >_<

Fixed and added comments.

if (base == 1) {
base = 0;
}
if (base == -1) {
return 0; // An error occurred, bail early.
}
if (base < 0) {
base = -base;
}

PyObject* s = PyUnicode_FromStringAndSize(data, size);
if (PyErr_Occurred()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I would ordinarily check if (s == NULL) rather than blindly calling PyErr_Occurred() on these.

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.

Done.

if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
PyErr_Clear();
}
return 0;
}
PyObject* l = PyLong_FromUnicodeObject(s, base);
if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_ValueError)) {
PyErr_Clear();
}
PyErr_Clear();
Py_XDECREF(l);
Py_DECREF(s);
return 0;
}

/* Fuzz PyUnicode_FromStringAndSize as a proxy for unicode(str). */
static int fuzz_builtin_unicode(const char* data, size_t size) {
PyObject* s = PyUnicode_FromStringAndSize(data, size);
if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
PyErr_Clear();
}
Py_XDECREF(s);
return 0;
}

/* Run fuzzer and abort on failure. */
static int _run_fuzz(const uint8_t *data, size_t size, int(*fuzzer)(const char* , size_t)) {
int rv = fuzzer((const char*) data, size);
if (PyErr_Occurred()) {
/* Fuzz tests should handle expected errors for themselves. */
PyErr_Print();
abort();
}
/* Someday the return value might mean something, propagate it. */
return rv;
}

/* CPython generates a lot of leak warnings for whatever reason. */
int __lsan_is_turned_off(void) { return 1; }

/* Fuzz test interface.
This returns the bitwise or of all fuzz test's return values.

All fuzz tests must return 0, as all nonzero return codes are reserved for
future use -- we propagate the return values for that future case.
(And we bitwise or when running multiple tests to verify that normally we
only return 0.) */
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
if (!Py_IsInitialized()) {
/* LLVMFuzzerTestOneInput is called repeatedly from the same process,
with no separate initialization phase, sadly, so we need to
initialize CPython ourselves on the first run. */
Py_InitializeEx(0);
}

int rv = 0;

#define _Py_FUZZ_YES(test_name) (defined(_Py_FUZZ_##test_name) || !defined(_Py_FUZZ_ONE))
#if _Py_FUZZ_YES(fuzz_builtin_float)
rv |= _run_fuzz(data, size, fuzz_builtin_float);
#endif
#if _Py_FUZZ_YES(fuzz_builtin_int)
rv |= _run_fuzz(data, size, fuzz_builtin_int);
#endif
#if _Py_FUZZ_YES(fuzz_builtin_unicode)
rv |= _run_fuzz(data, size, fuzz_builtin_unicode);
#endif
#undef _Py_FUZZ_YES
return rv;
}
6 changes: 6 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,12 @@ def detect_modules(self):
# syslog daemon interface
exts.append( Extension('syslog', ['syslogmodule.c']) )

# Fuzz tests.
exts.append( Extension(
'_fuzz',

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What prevents the _fuzz extension module from being installed and shipped with CPython? It seems like something needed only at build + test time in order to prevent bitrot of code that is primarily used outside of our own test suite. Not something to be distributed.

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.

Nothing. I don't think it should be distributed with Python, but I don't know how to stop that while still keeping it built for tests. Any suggestions?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm not sure the _fuzz module and it's corresponding test_fuzz.py add any real value. I expect you could make fuzzer.c be compile-only (with no attempt to link it into the main binary) with a Makefile.pre.in modification which should be good enough. At that point it could live in the Programs/ directory next to with _testembed.c with which it seems more akin to instead of under Modules/

A test that calling the fuzz function with a trivial input in our own test suite not crashing is not so important as the oss-fuzz project by its very nature is going to be doing that so we'd be notified. That we at least keep the code compiling is pretty good.

@ssbr ssbr Aug 29, 2017 •

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.

I mean, we can do this. It isn't ideal / isn't what oss-fuzz would like us to do. See e.g. this doc: https://github.com/google/oss-fuzz/blob/master/docs/ideal_integration.md#regression-testing

AIUI the oss-fuzz project doesn't want to be in the game of reporting broken tests, only of reporting actual security issues. (Unfortunately, I'm already deviating fairly substantially from what's ideal, but I'd like to be as close as possible).

(In particular, I think it is adding value: we should separate fuzz tests from unit tests / smoke tests so that reporting is easier and breakages less common.)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Alright, talking to @ncoghlan at the dev. sprint this week, we've got other modules that are built and effectively "shipped" but are really used for testing/development only. so this isn't the first, second, or even third such thing. _test_capi is one of them. xxlimited is another. so i'm going to propose _xx_test_fuzz as the name to "Use all the naming idioms!" . Python distribution creators are expected to realize that isn't needed in the main interpreter runtime package.

... let me rename things and look at this in whole again from that point of view.

['_fuzz/_fuzzmodule.c', '_fuzz/fuzzer.c'])
)

#
# Here ends the simple stuff. From here on, modules need certain
# libraries, are platform-specific, or present other surprises.
Expand Down