Exemple #1
0
def process_with_pcap_file(options):
    pcap = PcapHandler(options.pcap)
    ret = pcap.prepare_comparison_response()
    if ret is False:
        return 1

    response_data = []
    for stream in getattr(pcap, "request_data", []):
        parser = RequestParser(stream[PAYLOAD])
        if parser.run() is False:
            return 1

        session = Session()
        session.update_connection_info(method=getattr(parser, "method", "GET"))
        headers = getattr(parser, "headers", CaseInsensitiveDict())
        session.update_headers(headers)
        session.update_body(getattr(parser, "body", ""))

        host = make_host(headers, stream[DST_IP])
        request_url = make_request_url(host, 80, getattr(parser, "uri", ""))
        if session.send(request_url, verbose=False) is False:
            continue

        response = getattr(session, "response", None)
        start_line = ["HTTP/1.1", response.status_code]
        start_line += response.reason.split(" ")
        response_data.append((stream[DST_IP], stream[SRC_IP], start_line,
                              response.headers, response.text))

    pcap.comparison_response(response_data, options.verbose)
    return 0
Exemple #2
0
def stream_random_bytes(n):
    """Streams n random bytes generated with given seed, at given chunk size per packet."""
    n = min(n, 100 * 1024)  # set 100KB limit

    params = CaseInsensitiveDict(request.args.items())
    if 'seed' in params:
        random.seed(int(params['seed']))

    if 'chunk_size' in params:
        chunk_size = max(1, int(params['chunk_size']))
    else:
        chunk_size = 10 * 1024

    def generate_bytes():
        chunks = bytearray()

        for i in xrange(n):
            chunks.append(random.randint(0, 255))
            if len(chunks) == chunk_size:
                yield (bytes(chunks))
                chunks = bytearray()

        if chunks:
            yield (bytes(chunks))

    headers = {'Content-Type': 'application/octet-stream'}

    return Response(generate_bytes(), headers=headers)
Exemple #3
0
def process_with_request_file(options):
    session = Session()

    if options.file is None:
        method = "GET"
        headers = None
        body = ""
        uri = ""
    else:
        parser = RequestFileParser(options.file)
        if parser.run() is False:
            return 1

        method = getattr(parser, "method", "GET")
        headers = getattr(parser, "headers", CaseInsensitiveDict())
        body = getattr(parser, "body", "")
        uri = getattr(parser, "uri", "")

    # If dumy_body_byte is present, add dumy data.
    body += make_dumy_body(options.dumy_body_byte)

    session.update_connection_info(method=method)
    session.update_headers(headers)
    session.update_body(body)

    request_url = make_request_url(options.host, options.port, uri)
    session.send(request_url, verbose_detail=options.verbose)
    return 0
Exemple #4
0
    def __init__(self, stream=""):
        self.start_line = []
        self.headers = CaseInsensitiveDict()

        self.method = ""
        self.uri = ""
        self.version = ""
        self.body = ""
        self.stream = stream
Exemple #5
0
    def parse_response_data_in_pcap(self):
        for data in self.response_data_raw:
            parser = ResponseParser(data[PAYLOAD])
            parser.run()

            data_tuple = (data[SRC_IP], data[DST_IP],
                          getattr(parser, "start_line", []),
                          getattr(parser, "headers", CaseInsensitiveDict()),
                          getattr(parser, "body", ""))
            self.response_data.append(data_tuple)
Exemple #6
0
def get_headers(hide_env=True):
    '''Return headers dict from request context'''

    headers = dict(request.headers.items())
    if hide_env and ("show_env" not in request.args):
        for key in ENV_HEADERS:
            try:
                del headers[key]
            except KeyError:
                pass

    return CaseInsensitiveDict(headers.items())
Exemple #7
0
def drip():
    """Drips data over a duration after an optional initial delay."""
    args = CaseInsensitiveDict(request.args.items())
    duration = float(args.get('duration', 2))
    numbytes = min(int(args.get('numbytes', 10)),
                   (10 * 1024 * 1024))  # set 10MB limit
    code = int(args.get('code', 200))
    pause = duration / numbytes

    delay = float(args.get('delay', 0))
    if delay > 0:
        time.sleep(delay)

    def generate_bytes():
        for i in xrange(numbytes):
            yield u"*".encode('utf-8')
            time.sleep(pause)

    response = Response(generate_bytes(),
                        headers={
                            "Content-Type": "application/octet-stream",
                            "Content-Length": str(numbytes),
                        })

    response.status_code = code

    return response
Exemple #8
0
def random_bytes(n):
    """Returns n random bytes generated with given seed."""
    n = min(n, 100 * 1024)  # set 100KB limit

    params = CaseInsensitiveDict(request.args.items())
    if 'seed' in params:
        random.seed(int(params['seed']))

    response = make_response()

    # Note: can't just use os.urandom here because it ignores the seed
    response.data = bytearray(random.randint(0, 255) for i in range(n))
    response.content_type = 'application/octet-stream'
    return response
Exemple #9
0
def redirect_to():
    """302/3XX Redirects to the given URL."""

    args = CaseInsensitiveDict(request.args.items())

    # We need to build the response manually and convert to UTF-8 to prevent
    # werkzeug from "fixing" the URL. This endpoint should set the Location
    # header to the exact string supplied.
    response = app.make_response('')
    response.status_code = 302
    if 'status_code' in args:
        status_code = int(args['status_code'])
        if status_code >= 300 and status_code < 400:
            response.status_code = status_code
    response.headers['Location'] = args['url'].encode('utf-8')

    return response
Exemple #10
0
def get_headers(hide_env=True):
    """Returns headers dict from request context."""

    #print(request.headers.items())
    headers = dict(request.headers.items())
    #print('headers:',headers)
    if hide_env and ('show_env' not in request.args):
        print('node1')
        for key in ENV_HEADERS:
            print('node2')
            try:
                print('node3')
                del headers[key]
            except KeyError:
                print('node4')
                pass
    print('headers:',headers)
    return CaseInsensitiveDict(headers.items())
Exemple #11
0
    def __init__(self, stream):
        self.start_line = []
        self.headers = CaseInsensitiveDict()

        self.body = ""
        self.stream = stream
Exemple #12
0
def range_request(numbytes):
    """Streams n random bytes generated with given seed, at given chunk size per packet."""

    if numbytes <= 0 or numbytes > (100 * 1024):
        response = Response(headers={
            'ETag': 'range%d' % numbytes,
            'Accept-Ranges': 'bytes'
        })
        response.status_code = 404
        response.data = 'number of bytes must be in the range (0, 10240]'
        return response

    params = CaseInsensitiveDict(request.args.items())
    if 'chunk_size' in params:
        chunk_size = max(1, int(params['chunk_size']))
    else:
        chunk_size = 10 * 1024

    duration = float(params.get('duration', 0))
    pause_per_byte = duration / numbytes

    request_headers = get_headers()
    first_byte_pos, last_byte_pos = get_request_range(request_headers,
                                                      numbytes)

    if first_byte_pos > last_byte_pos or first_byte_pos not in xrange(
            0, numbytes) or last_byte_pos not in xrange(0, numbytes):
        response = Response(
            headers={
                'ETag': 'range%d' % numbytes,
                'Accept-Ranges': 'bytes',
                'Content-Range': 'bytes */%d' % numbytes
            })
        response.status_code = 416
        return response

    def generate_bytes():
        chunks = bytearray()

        for i in xrange(first_byte_pos, last_byte_pos + 1):

            # We don't want the resource to change across requests, so we need
            # to use a predictable data generation function
            chunks.append(ord('a') + (i % 26))
            if len(chunks) == chunk_size:
                yield (bytes(chunks))
                time.sleep(pause_per_byte * chunk_size)
                chunks = bytearray()

        if chunks:
            time.sleep(pause_per_byte * len(chunks))
            yield (bytes(chunks))

    content_range = 'bytes %d-%d/%d' % (first_byte_pos, last_byte_pos,
                                        numbytes)
    response_headers = {
        'Content-Type': 'application/octet-stream',
        'ETag': 'range%d' % numbytes,
        'Accept-Ranges': 'bytes',
        'Content-Range': content_range
    }

    response = Response(generate_bytes(), headers=response_headers)

    if (first_byte_pos == 0) and (last_byte_pos == (numbytes - 1)):
        response.status_code = 200
    else:
        response.status_code = 206

    return response