def testString(self): if sys.version_info[0] >= 3: fdp = atheris.FuzzedDataProvider(ASCII_BYTEMARK + b"abc" + ASCII_BYTEMARK + b"123") self.assertEqual("abc", fdp.ConsumeString(3)) self.assertEqual("123", fdp.ConsumeString(atheris.ALL_REMAINING)) else: fdp = atheris.FuzzedDataProvider(b"abc123") self.assertEqual("abc", fdp.ConsumeString(3)) self.assertEqual("123", fdp.ConsumeString(atheris.ALL_REMAINING))
def start_testing(data): events = [] for i in range(1, random.randint(1, 100)): # random events count fdp = atheris.FuzzedDataProvider(data) # each event has only 5 args, and events values can be only positive event = fdp.ConsumeIntListInRange(5, 0, 100000) events.append(event) meter = atheris.FuzzedDataProvider(data).ConsumeIntInRange(0, 10) beat = atheris.FuzzedDataProvider(data).ConsumeIntInRange(500, 4000) cadence_minimum = atheris.FuzzedDataProvider(data).ConsumeIntInRange( 1000, 20000) intervals_off = atheris.FuzzedDataProvider(data).ConsumeIntInRange(0, 10) measures = atheris.FuzzedDataProvider(data).ConsumeIntInRange(0, 10) threshold = atheris.FuzzedDataProvider(data).ConsumeIntInRange(0, 10) pattern_size = atheris.FuzzedDataProvider(data).ConsumeIntInRange(2, 10) amount_off = atheris.FuzzedDataProvider(data).ConsumeIntInRange(0, 10) matching_line = atheris.FuzzedDataProvider(data).ConsumeIntInRange(0, 10) speac_settings = SpeacSettings() speac_settings.set_beat(beat) speac_settings.set_cadence_minimum(cadence_minimum) speac_settings.set_intervals_off(intervals_off) speac_settings.set_measures(measures) speac_settings.set_threshold(threshold) speac_settings.set_pattern_size(pattern_size) speac_settings.set_amount_off(amount_off) speac_settings.set_matching_line(matching_line) test = BindingsTest() try: test.test_get_the_levels(events, meter, speac_settings) except Exception as get_the_levels_exception: print("\n") for i in range(1, 50): print(emoji.emojize(":tired_face:"), end="") print("\nERROR!!! Data aren't equal:\nPython and LISP input = ", events) variables = [ "*METER*", "*BEAT*", "*CADENCE-MINIMUM*", "*INTERVALS-OFF*", "*MEASURES*", "*THRESHOLD*", "*PATTERN-SIZE*", "*AMOUNT-OFF*", "*MATCHING-LINE*" ] for variable in variables: print("Lisp variable " + variable.upper() + " = ", lisp.eval(cl4py.Symbol(variable.upper()))) for i in range(1, 50): print(emoji.emojize(":tired_face:"), end="") print("\n") raise get_the_levels_exception
def TestOneInput(data): fdp = atheris.FuzzedDataProvider(data) hashes = [ SHA224, SHA256, SHA384, SHA512, MD2, MD4, MD5, RIPEMD160 ] for f in hashes: h = f.new() h.update(data) h.digest h = HMAC.new(fdp.ConsumeBytes(9)) h.update(data) h.digest try: cobj = CMAC.new(fdp.ConsumeBytes(16), ciphermod=AES) cobj.update(data) except ValueError as e: if "Key cannot be the null string" not in str(e): raise e
def TestInput(input_bytes): fdp = atheris.FuzzedDataProvider(input_bytes) default_args = { 'owner': fdp.ConsumeString(8), 'depends_on_past': fdp.ConsumeBool(), 'start_date': airflow.utils.dates.days_ago(fdp.ConsumeIntInRange(1, 5)), 'email': [fdp.ConsumeString(8)], 'email_on_failure': fdp.ConsumeBool(), 'email_on_retry': fdp.ConsumeBool(), 'retries': fdp.ConsumeIntInRange(1, 5), 'retry_delay': timedelta(minutes=fdp.ConsumeIntInRange(1, 5)), } try: with DAG(fdp.ConsumeString(8), schedule_interval='@daily', default_args=default_args) as dag: dummy_task = DummyOperator(task_id=fdp.ConsumeString(8), retries=fdp.ConsumeIntInRange(1, 5)) python_task = PythonOperator(task_id=fdp.ConsumeString(8), python_callable=py_func) dummy_task >> python_task except AirflowException: pass
def TestOneInput(data): if len(data) < 40: return fdp = atheris.FuzzedDataProvider(data) key = fdp.ConsumeBytes(16) IV = fdp.ConsumeBytes(16) enc_data = fdp.ConsumeBytes(atheris.ALL_REMAINING) # All modes: https://github.com/pycrypto/pycrypto/blob/7acba5f3a6ff10f1424c309d0d34d2b713233019/lib/Crypto/Cipher/AES.py#L183 # minus CTR, ECB, PGP (not supported) modes = [ AES.MODE_CBC, AES.MODE_CFB, AES.MODE_OFB, AES.MODE_OPENPGP, AES.MODE_CCM, AES.MODE_EAX, AES.MODE_SIV, AES.MODE_GCM ] for mode in modes: try: obj = AES.new(key, mode, IV) except ValueError as e: if not ("Key cannot be the null string" in str(e) or "Length of parameter" in str(e)): raise e return try: ciphertext = obj.encrypt(enc_data) except ValueError as e: if not "Input strings must be a multiple of 16 in length" in str( e): raise e
def TestInput(data): if len(data) < 10: pass fdp = atheris.FuzzedDataProvider(data) db_str = 'sqlite:///fuzz.db' metadata = MetaData() fuzz_table = Table('fuzz_table', metadata, Column('id', Integer, primary_key=True), Column('Col1', String)) engine = create_engine(db_str) metadata.create_all(engine) if not utils.database_exists(db_str): utils.create_database(db_str) assert utils.database_exists(db_str) try: with engine.connect() as conn: conn.execute(text(fdp.ConsumeString(100))) except (SQLAlchemyError, UnicodeEncodeError) as e: pass except ValueError as e: if "the query contains a null character" not in str(e): raise e utils.drop_database(db_str) assert not utils.database_exists(db_str)
def TestOneInput(data): fdp = atheris.FuzzedDataProvider(data) isp2 = isp.InputSplitter() isp2.push(fdp.ConsumeUnicode(sys.maxsize)) isp2.push_accepts_more() isp2.get_indent_spaces()
def TestOneInput(data): fdp = atheris.FuzzedDataProvider(data) s1 = fdp.ConsumeString(sys.maxsize) tokens = list(Lexer(s1)) if len(tokens) == 0: return lexer = Lexer(s1) parser = Parser(lexer) try: parser.input_line() except ParseError: pass lexer = Lexer(s1) parser = Parser(lexer) try: parser.collection_items() except QueryParamsParseError: pass lexer = Lexer(s1) parser = Parser(lexer) try: parser.dict_items() except QueryParamsParseError: pass
def TestInput(data): fdp = atheris.FuzzedDataProvider(data) try: ftfy.fix_text(fdp.ConsumeString(1000)) ftfy.fix_text(fdp.ConsumeUnicode(1000)) plan1 = ftfy.fix_and_explain(fdp.ConsumeString(1000))[1] plan2 = ftfy.fix_and_explain(fdp.ConsumeUnicode(1000))[1] ftfy.apply_plan(fdp.ConsumeString(1000), plan1) ftfy.apply_plan(fdp.ConsumeString(1000), plan2) ftfy.apply_plan(fdp.ConsumeUnicode(1000), plan1) ftfy.apply_plan(fdp.ConsumeUnicode(1000), plan2) ftfy.fix_text_segment(fdp.ConsumeString(1000)) ftfy.fix_text_segment(fdp.ConsumeUnicode(1000)) f = open("temp.txt", "w") f.write(fdp.ConsumeString(1000)) f.write(fdp.ConsumeUnicode(1000)) f.close() f = open("temp.txt", "r") ftfy.fix_file(f) f.close() ftfy.guess_bytes(fdp.ConsumeBytes(1000)) except UnicodeError as e: if "Hey wait, this isn't Unicode." not in str(e): raise e
def TestOneInput(data): fdp = atheris.FuzzedDataProvider(data) app = FuzzFlask("flask_test", root_path=os.path.dirname(__file__)) app.config["DEBUG"] = True app.config["TRAP_BAD_REQUEST_ERRORS"] = False @app.route("/json", methods=["POST"]) def post_json(): flask.request.get_json() return None parse_set_header(fdp.ConsumeUnicode(sys.maxsize)) client = app.test_client() try: app.add_url_rule( fdp.ConsumeUnicode(sys.maxsize), endpoint = "randomendpoint" ) except ValueError: None try: client.post( "/json", data=fdp.ConsumeUnicode(sys.maxsize), content_type="application/json" ) except (TypeError, UnicodeEncodeError): None
def TestOneInput(input_bytes): fdp = atheris.FuzzedDataProvider(input_bytes) original = fdp.ConsumeUnicode(sys.maxsize) try: ujson_data = ujson.loads(original) json_data = json.loads(original) except Exception as e: # It would be interesting to enforce that if one of the libraries throws an # exception, the other does too. However, uJSON accepts many invalid inputs # that are uninteresting, such as "00". So, that is not done. return # Uncomment these lines to ignore the errors described in the docstring of # this file. json_data = ClearAllIntegers(json_data) ujson_data = ClearAllIntegers(ujson_data) json_dumped = json.dumps(json_data) ujson_dumped = json.dumps(ujson_data) if json_dumped != ujson_dumped: raise RuntimeError( "Decoding/encoding disagreement!\nInput: %s\nJSON data: %s\nuJSON data: %s\nJSON-dumped: %s\nuJSON-dumped: %s\n" % (original, json_data, ujson_data, json_dumped, ujson_dumped))
def TestInput(data): fdp = atheris.FuzzedDataProvider(data) try: cell.absolute_coordinate(fdp.ConsumeString(20)) cell.cols_from_range(fdp.ConsumeString(20)) cell.column_index_from_string(fdp.ConsumeString(20)) cell.coordinate_from_string(fdp.ConsumeString(20)) cell.coordinate_to_tuple(fdp.ConsumeString(20)) cell.get_column_interval(fdp.ConsumeInt(10),fdp.ConsumeInt(10)) cell.get_column_letter(fdp.ConsumeInt(10)) cell.quote_sheetname(fdp.ConsumeString(20)) cell.range_boundaries(fdp.ConsumeString(20)) cell.range_to_tuple(fdp.ConsumeString(20)) cell.rows_from_range(fdp.ConsumeString(20)) except ValueError as e: error_list = [ "is not a valid coordinate range", "Invalid column index", "is not a valid column name", "is not a valid coordinate or range", "Value must be of the form sheetname!A1:E4" ] expected_error = False for error in error_list: if error in str(e): expected_error = True if not expected_error: raise e except CellCoordinatesException: pass
def test_etree_xml(data): fdp = atheris.FuzzedDataProvider(data) try: etree.XML(fdp.ConsumeUnicode(sys.maxsize)) except etree.XMLSyntaxError: pass return
def TestInput(input_bytes): if len(input_bytes) < 32: return fdp = atheris.FuzzedDataProvider(input_bytes) cache = TokenCache() client_id = fdp.ConsumeString(32) try: token = build_token(oid=fdp.ConsumeString(10), preferred_username=fdp.ConsumeString(10), id=client_id) cache.add( { "client_id": client_id, "scope": ["s2", "s1", "s3"], "token_endpoint": "https://%s" % fdp.ConsumeString(20), "response": build_response(token_type=fdp.ConsumeString(5), uid=fdp.ConsumeString(5), utid=fdp.ConsumeString(5), expires_in=3600, access_token=fdp.ConsumeString(10), id_token=token, refresh_token=fdp.ConsumeString(10)), }, now=1000) except ValueError as e: error_list = [ "netloc", "Invalid IPv6 URL", "should consist of an https url with a minimum of one segment in a path" ] if not is_expected(error_list, str(e)): raise e
def TestInput(data): if len(data) < 10: pass fdp = atheris.FuzzedDataProvider(data) cast_if(FuzzTable.id, Integer) cast_if(FuzzTable.name, Integer) cast_if(FuzzTable.id, String) cast_if(FuzzTable.name, String) cast_if(fdp.ConsumeInt(10), Integer) cast_if(fdp.ConsumeString(10), Integer) cast_if(fdp.ConsumeInt(10), String) cast_if(fdp.ConsumeString(10), String) db_str = 'sqlite:///fuzz.db' engine = create_engine(db_str) Base.metadata.create_all(engine) try: with Session(engine) as session: name_str = fdp.ConsumeString(20) session.query(FuzzTable).filter( FuzzTable.name.ilike(escape_like(name_str))).all() except SQLAlchemyError as e: pass
def TestInput(input_bytes): if len(input_bytes) < 12: return fdp = atheris.FuzzedDataProvider(input_bytes) choice = fdp.ConsumeIntInRange(1, 4) if choice == 1: cipher = aead.ChaCha20Poly1305(aead.ChaCha20Poly1305.generate_key()) if choice == 2: cipher = aead.AESGCM(aead.AESGCM.generate_key(bit_length=128)) if choice == 3: cipher = aead.AESOCB3(aead.AESOCB3.generate_key(bit_length=128)) if choice == 4: cipher = aead.AESCCM(aead.AESCCM.generate_key(bit_length=128)) msg = fdp.ConsumeBytes(32) authentext = fdp.ConsumeBytes(32) nonce = fdp.ConsumeBytes(12) if len(nonce) < 12: return ciphertext = cipher.encrypt(nonce, msg, authentext) plaintext = cipher.decrypt(nonce, ciphertext, authentext) assert (plaintext == msg), "Encryption/Decrption error!"
def TestOneInput(data: bytes) -> int: fdp = atheris.FuzzedDataProvider(data) random_lexer = pygments.lexers.get_lexer_by_name( fdp.PickValueInList(LEXERS)) str_data = fdp.ConsumeUnicode(atheris.ALL_REMAINING) pygments.highlight(str_data, random_lexer, formatter) return 0
def TestOneInput(data): fdp = atheris.FuzzedDataProvider(data) original = fdp.ConsumeUnicode(sys.maxsize) try: httplib2.urlnorm(original) except httplib2.RelativeURIError: return return
def TestOneInput(data): fdp = atheris.FuzzedDataProvider(data) original = fdp.ConsumeUnicode(sys.maxsize) try: simplejson.loads(original) except simplejson.JSONDecodeError: None return
def TestOneInput(data): fdp = atheris.FuzzedDataProvider(data) whttp.parse_content_range_header(fdp.ConsumeUnicode(100)) whttp.parse_range_header(fdp.ConsumeUnicode(100)) whttp.parse_set_header(fdp.ConsumeUnicode(100)) whttp.parse_etags(fdp.ConsumeUnicode(100)) whttp.parse_if_range_header(fdp.ConsumeUnicode(100)) whttp.parse_dict_header(fdp.ConsumeUnicode(100))
def TestInput(data): fdp = atheris.FuzzedDataProvider(data) #Initial tokenizer for random string and process it Tokenizer(fdp.ConsumeString(200)) #Translate random string formulae Translator(fdp.ConsumeString(200), origin="A1").translate_formula("B2")
def TestOneInput(data): fdp = atheris.FuzzedDataProvider(data) original = fdp.ConsumeUnicode(sys.maxsize) try: urllib3.util.parse_url(original) except urllib3.exceptions.LocationParseError: None return
def TestOneInput(input_bytes): fdp = atheris.FuzzedDataProvider(input_bytes) data = fdp.ConsumeUnicode(atheris.ALL_REMAINING) try: lexer = pygments.lexers.guess_lexer(data) except ValueError: return pygments.highlight(data, lexer, pygments.formatters.HtmlFormatter())
def TestOneInput(data): fdp = atheris.FuzzedDataProvider(data) s = fdp.ConsumeString(sys.maxsize) try: parse(s) except PSqlParseError as e: None except UnicodeEncodeError as e: None
async def fuzz_bodypart_reader(data): newline = b'\n' fdp = atheris.FuzzedDataProvider(data) obj = aiohttp.BodyPartReader(b"--:", {CONTENT_TYPE: fdp.ConsumeUnicode(30)}, FuzzStream( fdp.ConsumeBytes(atheris.ALL_REMAINING)), _newline=newline) if not obj.at_eof(): await obj.form()
def TestInput(data): if len(data) < 10: pass fdp = atheris.FuzzedDataProvider(data) metadata = MetaData() fuzz_table = Table( 'fuzz_table', metadata, Column('id', Integer, Sequence('id_seq'), primary_key=True), Column('Col1', String), Column('Col2', ArrowType), Column('Col3', ChoiceType([(u'c1', u'Choice 1'), (u'c2', u'Choice 2')])), Column('Col4', ColorType), Column('Col5', CountryType), Column('Col6', EmailType), Column('Col7', JSONType), Column('Col8', IPAddressType), Column('Col9', ScalarListType(int)), Column('Col10', URLType), Column('Col11', UUIDType(binary=False)), Column('Col12', WeekDaysType)) engine = create_engine('sqlite:///fuzz.db') metadata.create_all(engine) try: with engine.connect() as conn: conn.execute(text(fdp.ConsumeString(100))) ins = fuzz_table.insert().values( Col1=fdp.ConsumeString(100), Col2=utcnow(), Col3=u'c1' if fdp.ConsumeBool() else u'c2', Col4=Color("#{:02x}{:02x}{:02x}".format( fdp.ConsumeIntInRange(0, 255), fdp.ConsumeIntInRange(0, 255), fdp.ConsumeIntInRange(0, 255))), Col5=Country('US'), Col6=fdp.ConsumeString(20), Col7={ fdp.ConsumeString(2): fdp.ConsumeString(10), fdp.ConsumeString(2): fdp.ConsumeString(10), fdp.ConsumeString(2): fdp.ConsumeString(10) }, Col8="%d.%d.%d.%d" % (fdp.ConsumeIntInRange(0, 255), fdp.ConsumeIntInRange(0, 255), fdp.ConsumeIntInRange(0, 255), fdp.ConsumeIntInRange(0, 255)), Col9=[fdp.ConsumeInt(8), fdp.ConsumeInt(8), fdp.ConsumeInt(8)], Col10=fdp.ConsumeUnicode(20), Col11=uuid4(), Col12=WeekDays("{0:07b}".format(fdp.ConsumeIntInRange(0, 31)))) ins.compile() conn.execute(ins) except (SQLAlchemyError, UnicodeEncodeError) as e: pass except ValueError as e: if "the query contains a null character" not in str(e): raise e
def testUnicode16(self): fdp = atheris.FuzzedDataProvider(UTF16_BYTEMARK + b"abc123\0\x7f" + HIGH_SURROGATE + LOW_SURROGATE + b"\xd1") expected = str() expected += b"abc123\0\x7f".decode("utf-16") expected += codepoint(0xDAA1) + codepoint(0xDD03) actual = fdp.ConsumeUnicode(atheris.ALL_REMAINING) self.assertEqual(expected, actual)
def TestOneInput(data): fdp = atheris.FuzzedDataProvider(data) try: fuzzed_dict = json.loads(fdp.ConsumeString(sys.maxsize)) except json.JSONDecodeError: return if type(fuzzed_dict) is not dict: return serialized = serialize(fuzzed_dict) config = deserialize(serialized)
def fuzz_request(data, wsgi_app): fdp = atheris.FuzzedDataProvider(data) method = fdp.PickValueInList(["GET", "POST", "PUT", "HEAD", "DELETE", "OPTIONS", "TRACE", "PATCH"]) url_length = fdp.ConsumeUInt(2) url = urllib.parse.quote(fdp.ConsumeBytes(url_length), safe='/?&=%') c = Client(wsgi_app, BaseResponse) resp = c.open(path=url, method=method) assert not (500 <= resp.status_code <= 599)
def TestOneInput(data): fdp = atheris.FuzzedDataProvider(data) env = jinja2.Environment() try: v1 = env.compile_expression(fdp.ConsumeString(sys.maxsize)) except jinja2.TemplateSyntaxError: return except SyntaxError: return except RecursionError: return return