Example #1
0
def main():
    """Run AFL repeatedly with externally supplied generated packet from STDIN."""
    application = faucet.Faucet(dpset=dpset.DPSet())
    application.start()

    # make sure dps are running
    if application.valves_manager is not None:
        for valve in list(application.valves_manager.valves.values()):
            state = valve.dp.dyn_finalized
            valve.dp.dyn_finalized = False
            valve.dp.running = True
            valve.dp.dyn_finalized = state

    while afl.loop(ROUNDS):  # pylint: disable=c-extension-no-member
        # receive input from afl
        rcv = sys.stdin.read()
        data = None
        try:
            data = bytearray.fromhex(rcv)  # pytype: disable=missing-parameter,wrong-arg-types
        except (ValueError, TypeError):
            continue

        # create fake packet
        _dp = fake_packet.Datapath(1)
        msg = fake_packet.Message(datapath=_dp,
                                  cookie=15243729,
                                  port=1,
                                  data=data,
                                  in_port=1)
        pkt = fake_packet.RyuEvent(msg)

        # send fake packet to faucet
        application.packet_in_handler(pkt)
Example #2
0
def main():
    """Run AFL repeatedly with externally supplied generated packet from STDIN."""
    application = faucet.Faucet(
        dpset=dpset.DPSet(),
        faucet_experimental_api=faucet_experimental_api.FaucetExperimentalAPI())
    application.start()

    # make sure dps are running
    if application.valves_manager is not None:
        for valve in list(application.valves_manager.valves.values()):
            valve.dp.running = True

    while afl.loop(ROUNDS):
        # receive input from afl
        rcv = sys.stdin.read()
        data = None
        try:
            data = bytearray.fromhex(rcv) # pytype: disable=missing-parameter
        except (ValueError, TypeError):
            continue

        # create fake packet
        dp = Fake.Datapath(1)
        msg = Fake.Message(datapath=dp, cookie=1524372928, port=1, data=data, in_port=1)
        pkt = Fake.RyuEvent(msg)

        # send fake packet to faucet
        application.packet_in_handler(pkt)
Example #3
0
def main():
    application = faucet.Faucet(
        dpset=dpset.DPSet(),
        faucet_experimental_api=faucet_experimental_api.FaucetExperimentalAPI(
        ))
    application.start()

    # make sure dps are running
    if application.valves_manager is not None:
        for valve in list(application.valves_manager.valves.values()):
            valve.dp.running = True

    while afl.loop(ROUNDS):
        # receive input from afl
        rcv = sys.stdin.read()
        data = None
        try:
            data = bytearray.fromhex(rcv)  # pytype: disable=missing-parameter
        except (ValueError, TypeError):
            continue

        # create fake packet
        dp = Fake.Datapath(1)
        msg = Fake.Message(datapath=dp,
                           cookie=1524372928,
                           port=1,
                           data=data,
                           in_port=1)
        pkt = Fake.RyuEvent(msg)

        # send fake packet to faucet
        application.packet_in_handler(pkt)
Example #4
0
def main():
    logging.disable(logging.CRITICAL)
    while afl.loop(ROUNDS):  # pylint: disable=c-extension-no-member
        config = sys.stdin.read()
        file_name = create_config_file(config)
        try:
            cp.dp_parser(file_name, LOGNAME)
        except cp.InvalidConfigError:
            pass
Example #5
0
def main():
    logging.disable(logging.CRITICAL)
    while afl.loop(ROUNDS): # pylint: disable=c-extension-no-member
        config = sys.stdin.read()
        file_name = create_config_file(config)
        try:
            cp.dp_parser(file_name, LOGNAME)
        except cp.InvalidConfigError:
            pass
Example #6
0
def main():
    """Runs the py-AFL fuzzer with the faucet config parser"""
    logging.disable(logging.CRITICAL)
    while afl.loop(ROUNDS):  # pylint: disable=c-extension-no-member
        config = sys.stdin.read()
        file_name = create_config_file(config)
        try:
            cp.dp_parser(file_name, LOGNAME)
        except InvalidConfigError:
            pass
Example #7
0
def main():
    run_all(b"smoke test")

    buffer = sys.stdin.buffer
    while afl.loop(1000):
        data = buffer.read()
        try:
            run_all(data)
        finally:
            buffer.seek(0)
Example #8
0
def main(eap):
    """Run AFL repeatedly with externally supplied generated packet from STDIN."""

    while afl.loop(ROUNDS):
        # receive input from afl
        rcv = sys.stdin.read()
        data = None
        try:
            data = bytearray.fromhex(rcv)  # pytype: disable=missing-parameter
        except (ValueError, TypeError):
            return
        if eap:
            test_one_x_parse(data)
        else:
            test_radius_parse(data)
Example #9
0
def main():
    global swarm, showActions, noCheck, alwaysSave, noSave, sut

    if "--help" in sys.argv:
        print(
            "Usage:  tstl_afl [--noCheck] [--swarm] [--verbose] [--showActions] [--noSave] [--alwaysSave]"
        )
        print("Options:")
        print(" --noCheck:      do not run property checks")
        print(
            " --swarm         use first four bytes to determine a swarm configuration"
        )
        print(" --verbose:      make actions verbose")
        print(" --showActions:  show actions in test")
        print(
            " --noSave:       don't save failing tests as standard TSTL tests")
        print(" --alwaysSave:   save even non-failing tests")
        sys.exit(0)

    sut = SUT.sut()

    try:
        sut.stopCoverage()
    except BaseException:
        pass

    sut.restart()

    swarm = "--swarm" in sys.argv
    showActions = "--showActions" in sys.argv
    if "--verbose" in sys.argv:
        sut.verbose(True)
    noSave = "--noSave" in sys.argv
    alwaysSave = "--alwaysSave" in sys.argv
    noCheck = "--noCheck" in sys.argv
    persist = "--persist" in sys.argv

    if not persist:
        afl.init()
        runTest()
    else:
        while afl.loop():
            runTest()
            sut.restart()

    os._exit(0)
Example #10
0
def _test_persistent(n, *args, **kwargs):
    os.environ['PYTHON_AFL_PERSISTENT'] = '1'
    n_max = 1000
    k = [0]
    def kill(pid, sig):
        assert_equal(pid, os.getpid())
        assert_equal(sig, signal.SIGSTOP)
        k[0] += 1
    os.kill = kill
    x = 0
    while afl.loop(*args, **kwargs):
        x += 1
        if x == n_max:
            break
    if n is None:
        n = n_max
    assert_equal(x, n)
    assert_equal(k[0], n - 1)
Example #11
0
def _test_persistent(n, *args, **kwargs):
    os.environ['PYTHON_AFL_PERSISTENT'] = '1'
    n_max = 1000
    k = [0]

    def kill(pid, sig):
        assert_equal(pid, os.getpid())
        assert_equal(sig, signal.SIGSTOP)
        k[0] += 1

    os.kill = kill
    x = 0
    while afl.loop(*args, **kwargs):
        x += 1
        if x == n_max:
            break
    if n is None:
        n = n_max
    assert_equal(x, n)
    assert_equal(k[0], n - 1)
Example #12
0
File: cli.py Project: tgbugs/sxpyr
def main():
    options, *ad = Options.setup(__doc__, version='sxpyr 0.0.0')

    main = Main(options)

    if main.options.debug:
        print(main.options)

    if options.fuzz:
        import os
        import sys
        import afl
        #afl.init()
        while afl.loop(55555):
            out = main()
            #sys.stdin.seek(0)

        os._exit(0)
    else:
        out = main()
Example #13
0
def prefix_fuzzing(fd, lfd, args=None, **kwargs):
    """
    Original forking fuzzer with AFL without TCP binding.
    Only for demo purposes. Did not work well with libpcsc and forking.

    :param fd:
    :param args:
    :return:
    """

    global stdin_compat
    in_afl = os.getenv('PYTHON_AFL_PERSISTENT', None)

    # reader = get_reader()
    # card = connect_card(reader)

    llog(fd, 'init1')
    fwd = FileWriter(fd=lfd)
    sys.settrace(None)
    llog(fd, 'init2, in afl: %s' % in_afl)

    # Call our fuzzer
    try:
        while afl.loop(3):  # afl.init()
            sys.settrace(None)

            stdin_compat.seek(0)
            buffer = stdin_compat.read()
            buffer = form_buffer(buffer)
            if buffer is None:
                continue

            llog(fd, 'init4, buffer: %s' % binascii.hexlify(bytes(buffer)))
            ln = int(buffer[4]) if len(buffer) >= 5 else 0
            test_elem = FuzzerObject(int(buffer[0]), int(buffer[1]),
                                     int(buffer[2]), int(buffer[3]), ln,
                                     list(bytearray(buffer[5:])))

            if args.dry:
                elem = test_elem
                sw1 = 0
                sw2 = 0
                out = bytes()

            else:
                card_interactor = CardInteractor(CARD_READER_ID)
                llog(fd, 'reader: %s' % (card_interactor, ))

                elem = card_interactor.send_element(test_elem)
                sw1 = elem.out['sw1']
                sw2 = elem.out['sw2']
                out = elem.out['data']

            statuscode = (sw1 << 8) + sw2
            time_bin = int(test_elem.misc['timing'] // 10)
            if time_bin < 0:
                time_bin = 0

            serialized_element = elem.serialize()
            fwd.print_to_file("%s" % json.dumps(serialized_element))

            llog(fd, 'status: %04x timing: %s' % (statuscode, time_bin))
            if in_afl:
                afl.trace_offset(hashxx(bytes([sw1, sw2])))
                afl.trace_offset(hashxx(bytes(time_bin.to_bytes(2, 'big'))))
                afl.trace_offset(hashxx(out))
            os._exit(0)

    except Exception as e:
        llog(fd, 'Exc: %s\n' % e)
        traceback.print_exc(file=fd)
        fd.flush()

    finally:
        fd.close()
        os._exit(0)
Example #14
0
def client_fuzzer(fd, lfd, args=None, **kwargs):
    """
    Client AFL fuzzer. Executed by AFL, fed to STDIN.
    Communicates with the fuzzer server, reads response, changes SHM.

    :param fd:
    :param lfd:
    :param args:
    :return:
    """
    global stdin_compat
    in_afl = os.getenv('PYTHON_AFL_PERSISTENT', None)

    llog(fd, 'init1')
    sys.settrace(None)
    llog(fd, 'init2, in afl: %s' % in_afl)

    # Argument processing
    tpler = Templater(args)
    llog(fd, 'templater: %s' % tpler)

    # by default, start with 4byte input - fuzz instruction with empty data
    tpler.gen_inputs()

    # Call our fuzzer
    try:
        # s = csock()  # Pre-fork connection. needs more sophisticated reconnect if socket is broken.
        while afl.loop(3):
            sys.settrace(None)
            stdin_compat.seek(0)
            buffer = stdin_compat.read()
            buffer = tpler.transform(buffer)
            if buffer is None:
                continue

            llog(fd, 'init4, buffer: %s' % binascii.hexlify(bytes(buffer)))

            s = SockComm(server=False)
            s.connect()
            s.send(bytes([0]) + bytes(buffer))

            resp = s.read()
            llog(fd, 'Recv: %s' % binascii.hexlify(resp))
            if resp[0] != 0:
                llog(fd, 'Invalid response code: %s' % resp[0])
                continue

            sw1 = resp[1]
            sw2 = resp[2]
            timing = resp[3:5]
            data = resp[5:]
            statuscode = (sw1 << 8) + sw2

            llog(fd, 'status: %04x timing: %s' % (statuscode, timing))
            if in_afl:
                afl.trace_offset(hashxx(bytes([sw1, sw2])))
                afl.trace_offset(hashxx(timing))
                afl.trace_offset(hashxx(bytes(data)))

    except Exception as e:
        llog(fd, 'Exc: %s\n' % e)
        traceback.print_exc(file=fd)
        fd.flush()

    except KeyboardInterrupt:
        return

    finally:
        fd.close()
        os._exit(0)
Example #15
0
    mock.patch.object(socketserver.TCPServer, 'serve_forever').start()
    mock.patch('socketserver.ThreadingMixIn').start()
    mock.patch('multiprocessing.Pool').start()
    mock.patch('concurrent.futures.ThreadPoolExecutor').start()
    mock.patch.object(threading, 'current_thread', ThreadMock).start()
    mock.patch.object(workers.Workers, 'start_thread', lambda _, func, *args, **kwargs: func(*args, **kwargs)).start()
    mock.patch.object(workers.Workers, 'run_pool', new=lambda func, *args: func(*args)).start()
    mock.patch.object(workers.Workers, 'defer').start()


def setup_bot():
    confdir = join(dirname(__file__), '..')
    bot = core.IrcBot(confdir)
    bot.handler.channels = {'#test-channel': mock.MagicMock()}
    bot.handler.is_ignored = mock.MagicMock(return_value=False)
    bot.handler.db = mock.MagicMock()
    # We don't actually connect to an irc server, so fake the event loop
    with mock.patch.object(irc.client.Reactor, 'process_forever'):
        bot.start()
    return bot

setup_mocks()
bot = setup_bot()
e = irc.client.Event('privmsg', irc.client.NickMask('dankmemes'), '#test-channel')
while afl.loop(5):
    try:
        e.arguments = [stdin.readline()]
    except UnicodeDecodeError:
        continue
    bot.handler.handle_msg(bot.connection, e)
Example #16
0
def _test_docile(*args, **kwargs):
    os.environ.pop('PYTHON_AFL_PERSISTENT', None)
    x = 0
    while afl.loop(*args, **kwargs):
        x += 1
    assert_equal(x, 1)
Example #17
0
#!/usr/bin/env python3

import logging
import tempfile
import os
import sys
from faucet import config_parser as cp

LOGNAME = 'FAUCETLOG'

logging.disable(logging.CRITICAL)
tmpdir = tempfile.mkdtemp()

def create_config_file(config):
    conf_file_name = os.path.join(tmpdir, 'faucet.yaml')
    with open(conf_file_name, 'w') as conf_file:
        conf_file.write(config)
    return conf_file_name

import afl
while afl.loop(500):
    data = sys.stdin.read()
    file_name = create_config_file(data)
    try:
        cp.dp_parser(file_name, LOGNAME)
    except cp.InvalidConfigError as err:
        pass
os._exit(0)
Example #18
0
def test_double_init():
    afl.init()
    with assert_raises_regex(RuntimeError, '^AFL already initialized$'):
        while afl.loop():
            pass
Example #19
0
def main():
    while afl.loop(max=1000):
        s = sys.stdin.buffer.read()  # pylint: disable=no-member
        s = s.decode('UTF-8', 'replace')
        test(s)
    os._exit(0)  # pylint: disable=protected-access
Example #20
0
# -*- coding: utf-8; -*-

import os
import sys

import httpolice.cli

if __name__ == '__main__':
    args = httpolice.cli.parse_args(sys.argv)
    import afl
    while afl.loop(100):
        httpolice.cli.run_cli(args, sys.stdout, sys.stderr)
    # As suggested by python-afl docs.
    os._exit(0)         # pylint: disable=protected-access
Example #21
0
def test_double_init():
    afl.init()
    with assert_raises_regex(RuntimeError, '^AFL already initialized$'):
        while afl.loop():
            pass
Example #22
0
from faucet import faucet_experimental_api

logging.disable(logging.CRITICAL)

# run faucet
application = faucet.Faucet(
    dpset=dpset.DPSet(),
    faucet_experimental_api=faucet_experimental_api.FaucetExperimentalAPI())
application.start()

# make sure dps are running
for dp_id, valve in list(application.valves.items()):
    valve.dp.running = True

import afl
while afl.loop(1000):
    # receive input from afl
    rcv = sys.stdin.read()
    data = None
    try:
        data = bytearray.fromhex(rcv)
    except (ValueError, TypeError):
        pass

    if data is not None:
        # create fake packet
        dp = Fake.Datapath(1)
        msg = Fake.Message(datapath=dp,
                           cookie=1524372928,
                           port=1,
                           data=data,
Example #23
0
def main():
    while afl.loop(max=1000):
        data = sys.stdin.buffer.read()  # pylint: disable=no-member
        test(data)
    os._exit(0)  # pylint: disable=protected-access
Example #24
0
def _test_docile(*args, **kwargs):
    os.environ.pop('PYTHON_AFL_PERSISTENT', None)
    x = 0
    while afl.loop(*args, **kwargs):
        x += 1
    assert_equal(x, 1)
Example #25
0
def fuzz():
    data = open(sys.argv[1], errors="surrogateescape").read()
    parser_basic = configparser.ConfigParser(
        interpolation=configparser.BasicInterpolation())
    try:
        parser_basic.read_string(data)
        for name, proxy in parser_basic.items():
            for option, value in parser_basic.items(name):
                pass
            repr(proxy)
        repr(parser_basic)
    except configparser.Error:
        pass

    parser_extended = configparser.ConfigParser(
        interpolation=configparser.ExtendedInterpolation())
    try:
        parser_extended.read_string(data)
        for name, proxy in parser_extended.items():
            for option, value in parser_extended.items(name):
                pass
            repr(proxy)
        repr(parser_extended)
    except configparser.Error:
        pass


while afl.loop():
    fuzz()
Example #26
0
    #open write pipe
    wrPipe = ipc.open_wr_fifo_pipe(pipeName)
    if wrPipe is None:
        logger("Open write pipe error.")
        return False
    else:
        logger("Open write pipe successful.")

    pipeAlive = True
    return True


##############################################################################
#start at here
while afl.loop(99999999):
    #open write pipe
    if pipeAlive is False:
        if open_pipe() is False:
            os.kill(0 - os.getppid(), signal.SIGKILL)
            os.kill(0 - os.getpid(), signal.SIGKILL)
        else:
            pipeAlive = True

    #read from input file
    try:
        input = open(sys.argv[1], "r")
        payload = ""
        while True:
            try:
                chunk = input.read(65535)