def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect(('gunicorn.org', 80))
        s.send("GET / HTTP/1.1\r\nHost: gunicorn.org\r\n\r\n")
        p = HttpStream(SocketReader(s))
        print p.headers()
        print p.body_file().read()
    finally:
        s.close()
Esempio n. 2
0
def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect(('gunicorn.org', 80))
        s.send("GET / HTTP/1.1\r\nHost: gunicorn.org\r\n\r\n")
        p = HttpStream(SocketReader(s))
        print p.headers()
        print p.body_file().read()
    finally:
        s.close()
Esempio n. 3
0
    def get_response(self, request, connection):
        """ return final respons, it is only accessible via peform
        method """
        if log.isEnabledFor(logging.DEBUG):
            log.debug("Start to parse response")

        p = HttpStream(SocketReader(connection.socket()), kind=1,
                decompress=self.decompress)

        if log.isEnabledFor(logging.DEBUG):
            log.debug("Got response: %s %s" % (p.version(), p.status()))
            log.debug("headers: [%s]" % p.headers())

        location = p.headers().get('location')

        if self.follow_redirect:
            should_close = not p.should_keep_alive()
            if p.status_code() in (301, 302, 307,):

                # read full body and release the connection
                p.body_file().read()
                connection.release(should_close)

                if request.method in ('GET', 'HEAD',) or \
                        self.force_follow_redirect:
                    if hasattr(self.body, 'read'):
                        try:
                            self.body.seek(0)
                        except AttributeError:
                            raise RequestError("Can't redirect %s to %s "
                                    "because body has already been read"
                                    % (self.url, location))
                    return self.redirect(location, request)

            elif p.status_code() == 303 and self.method == "POST":
                # read full body and release the connection
                p.body_file().read()
                connection.release(should_close)

                request.method = "GET"
                request.body = None
                return self.redirect(location, request)

        # create response object
        resp = self.response_class(connection, request, p)

        # apply response filters
        for f in self.response_filters:
            f.on_response(resp, request)

        if log.isEnabledFor(logging.DEBUG):
            log.debug("return response class")

        # return final response
        return resp
Esempio n. 4
0
    def get_response(self, request, connection):
        """ return final respons, it is only accessible via peform
        method """
        if log.isEnabledFor(logging.DEBUG):
            log.debug("Start to parse response")

        p = HttpStream(SocketReader(connection.socket()), kind=1,
                decompress=self.decompress)

        if log.isEnabledFor(logging.DEBUG):
            log.debug("Got response: %s %s" % (p.version(), p.status()))
            log.debug("headers: [%s]" % p.headers())

        location = p.headers().get('location')

        if self.follow_redirect:
            should_close = not p.should_keep_alive()
            if p.status_code() in (301, 302, 307,):

                # read full body and release the connection
                p.body_file().read()
                connection.release(should_close)

                if request.method in ('GET', 'HEAD',) or \
                        self.force_follow_redirect:
                    if hasattr(self.body, 'read'):
                        try:
                            self.body.seek(0)
                        except AttributeError:
                            raise RequestError("Can't redirect %s to %s "
                                    "because body has already been read"
                                    % (self.url, location))
                    return self.redirect(location, request)

            elif p.status_code() == 303 and self.method == "POST":
                # read full body and release the connection
                p.body_file().read()
                connection.release(should_close)

                request.method = "GET"
                request.body = None
                return self.redirect(location, request)

        # create response object
        resp = self.response_class(connection, request, p)

        # apply response filters
        for f in self.response_filters:
            f.on_response(resp, request)

        if log.isEnabledFor(logging.DEBUG):
            log.debug("return response class")

        # return final response
        return resp
Esempio n. 5
0
    def recv(self, wsgi=False):
        try:
            stream = HttpStream(self.reader, kind=HTTP_REQUEST, parser_class=HttpParser, decompress=True)

            if bool(wsgi):
                environ = stream.wsgi_environ()
                environ['wsgi.url_scheme'] = guess_scheme(environ)
                environ['wsgi.input'] = stream.body_file()
                environ['wsgi.socket'] = self.socket
                return environ

            # BUG:
            # http-parser has an issue here, if we call 'method' before 'headers'
            # and invalid method name is returned...
            fields  = stream.headers()
            method  = stream.method()
            url     = stream.url()
            version = stream.version()
            content = stream.body_file()

            url      = urlparse(url)
            path     = url.path
            query    = parse_qs(url.query, keep_blank_values=True)
            fragment = url.fragment

            for k, v in six.iteritems(dict(query)):
                query[k] = parse_query_value(v)

            self.version = 'HTTP/%s.%s' % version
            return method, path, query, fragment, fields, content
        except NoMoreData:
            pass
Esempio n. 6
0
 def read_get(self):
     reader = SocketReader(self.sock)
     resp = HttpStream(reader)
     status_code = resp.status_code()
     headers = dict(resp.headers())
     body = resp.body_string()
     return {"status_code": status_code, "headers": headers, "body": body}
Esempio n. 7
0
def test_parse_from_real_socket():
    # would fail on python2.6 before the recv_into hack
    sock, sink = socket.socketpair()
    sink.send(complete_request)
    reader = SocketReader(sock)
    stream = HttpStream(reader)
    assert stream.headers()
Esempio n. 8
0
    def _handle_client(self, client, address):
        try:

            r = SocketReader(client)
            p = HttpStream(r)
            headers = p.headers()
            body = ""
            if "CONTENT-LENGTH" in headers and int(
                    headers["CONTENT-LENGTH"]) > 0:
                body = p.body_string(binary=False)

            # System requests
            if p.path() == "/alive":
                self._respond(client, "ok")
                return

            # User requests
            req = IpcServer.Request(self._respond, client, p.path(),
                                    p.method(), headers, body)
            if p.path() == "/message":
                req.respond()

            self.requests.put(req)

        except Exception as e:
            client.close()
            raise e
def test_parse_from_real_socket():
    # would fail on python2.6 before the recv_into hack
    sock, sink = socket.socketpair()
    sink.send(complete_request)
    reader = SocketReader(sock)
    stream = HttpStream(reader)
    assert stream.headers()
Esempio n. 10
0
    def get_response(self, request, connection):
        """ return final respons, it is only accessible via peform
        method """
        if log.isEnabledFor(logging.DEBUG):
            log.debug("Start to parse response")

        p = HttpStream(SocketReader(connection.socket()), kind=1, decompress=self.decompress)

        if log.isEnabledFor(logging.DEBUG):
            log.debug("Got response: %s" % p.status())
            log.debug("headers: [%s]" % p.headers())

        location = p.headers().get("location")

        if self.follow_redirect:
            if p.status_code() in (301, 302, 307):
                if request.method in ("GET", "HEAD") or self.force_follow_redirect:
                    if hasattr(self.body, "read"):
                        try:
                            self.body.seek(0)
                        except AttributeError:
                            connection.release()
                            raise RequestError(
                                "Can't redirect %s to %s " "because body has already been read" % (self.url, location)
                            )
                    connection.release()
                    return self.redirect(p, location, request)

            elif p.status_code() == 303 and self.method == "POST":
                connection.release()
                request.method = "GET"
                request.body = None
                return self.redirect(p, location, request)

        # create response object
        resp = self.response_class(connection, request, p)

        # apply response filters
        for f in self.response_filters:
            f.on_response(resp, request)

        if log.isEnabledFor(logging.DEBUG):
            log.debug("return response class")

        # return final response
        return resp
Esempio n. 11
0
 def send_downstream(self, p, rhost, rport, method, url, upsock):
     with self.connect_downstream(rhost, rport) as downsock:
         request = '{method} {url} HTTP/{version[0]}.{version[1]}\r\n{headers}\r\n\r\n'.format(method=method.decode(), url=url, version=p.version(), headers='\r\n'.join(['{0}: {1}'.format(name, value) for name, value in p.headers().items()]))
         self.logger.debug('sending request {0!r}'.format(request))
         downsock.send(request.encode())
         downstream = HttpStream(SocketReader(downsock))
         self.logger.debug('response: header={0}'.format(downstream.headers()))
         upsock.send('HTTP/{version[0]}.{version[1]} {code} {status}\r\n{headers}\r\n\r\n'.format(version=downstream.version(), code=downstream.status_code(), status=downstream.status(), headers='\r\n'.join(['{0}: {1}'.format(name, value) for name, value in downstream.headers().items()])).encode())
         upsock.send(downstream.body_string())
Esempio n. 12
0
    def send(self, protocol ,host, header):
        h = Http()
        h.build_header()
        data = header
        str_response_body=""
        str_response_header=""

        if protocol == "http":
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((host,80))
            s.send(data.encode('utf-8'))
            """
            response = b""
            while True:
                d = client.recv(1024)
                response = response + d
                if not d:
                    break
            #print(response)
            """
            p = HttpStream(SocketReader(s))

        elif protocol == "https":
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((host, 443))
            s = ssl.wrap_socket(s, keyfile=None, certfile=None, server_side=False, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_SSLv23)
            s.sendall(data.encode('utf-8'))
            """
            response = b""
            while True:
                d = s.recv(4096)
                response = response + d
                if not d:
                    break
            """
            p = HttpStream(SocketReader(s))
        #return html.escape(str(response, errors='replace'))
        # Transfer-Encoding: chunked の対処をする。
        
        str_response_header += p.status()+"\n"
        for h in p.headers():
            str_response_header += h+": "+p.headers()[h]+"\n"
        str_response_body += str(p.body_file().read(),  errors='replace')
        return {"body":str_response_body, "header":str_response_header}
Esempio n. 13
0
 def recv(self):
     try:
         stream  = HttpStream(self.reader, kind=HTTP_RESPONSE, parser_class=HttpParser, decompress=True)
         status  = stream.status_code()
         version = stream.version()
         fields  = stream.headers()
         content = stream.body_file()
         self.version = 'HTTP/%s.%s' % version
         return status, fields, content
     except NoMoreData:
         pass
Esempio n. 14
0
def recPOSTheader(HOST, request_headerPOST):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST, PORT))
        try:
            s.sendall(request_headerPOST.encode('utf-8'))
        except:
            print("An error has occured while trying to send the POST request")
        dataReceived = SocketReader(s)
        parsed = HttpStream(dataReceived)
        header = parsed.headers()
        return header
Esempio n. 15
0
def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect(('baike.baidu.com', 80))
        s.send(b("GET /view/262.htm HTTP/1.1\r\nHost: baike.baidu.com\r\n\r\n"))
        p = HttpStream(SocketReader(s), decompress=True)
        print(p.headers())

        print(p.body_file().read())
    finally:
        s.close()
Esempio n. 16
0
def GETverbose(HOST, request_headerGET):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST, 80))
        try:
            s.sendall(request_headerGET.encode('utf-8'))
        except:
            print("An error has occured while trying to send the GET request")
        dataReceived = SocketReader(s)
        parsed = HttpStream(dataReceived)
        body = parsed.body_file().read().decode('utf-8')
        header = parsed.headers()
        return pprint.pformat(header) + body
Esempio n. 17
0
def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect(('baike.baidu.com', 80))
        s.send(
            b("GET /view/262.htm HTTP/1.1\r\nHost: baike.baidu.com\r\n\r\n"))
        p = HttpStream(SocketReader(s), decompress=True)
        print(p.headers())

        print(p.body_file().read())
    finally:
        s.close()
Esempio n. 18
0
def processData(newsocketconn, fromaddr, context, ipaddr, q):
    if useSSL:
        connstreamout = context.wrap_socket(newsocketconn, server_side=True)
    else:
        connstreamout = newsocketconn
    try:
        try:
            ### Read the json response using Socket Reader and split header and body
            r = SocketReader(connstreamout)
            p = HttpStream(r)
            headers = p.headers()
            q.put(makeLogMessage("INFO", "idrac", "ProcessData"))

            if p.method() == 'POST':
                bodydata = p.body_file().read()
                bodydata = bodydata.decode("utf-8", errors='ignore')

                ### Read the json response and print the output
                # outdata = dict()
                try:
                    with open(f"{ipaddr[3]}/output/{ipaddr[2]}", "a+") as fd:
                        fd.write(bodydata)
                        fd.write("\n")
                except Exception as ex:
                    print("Exception Occured =", ex)

                StatusCode = """HTTP/1.1 200 OK\r\n\r\n"""
                connstreamout.send(bytes(StatusCode, 'UTF-8'))

            # if p.method() == 'GET':

            #     res = "HTTP/1.1 200 OK\n" \
            #           "Content-Type: application/json\n" \
            #           "\n" + json.dumps(data_buffer)
            #     connstreamout.send(res.encode())
            #     data_buffer.clear()

        except Exception as err:
            outdata = connstreamout.read()
            traceback.print_exc()
            print("Data needs to read in normal Text format.")

    finally:
        connstreamout.shutdown(socket.SHUT_RDWR)
        connstreamout.close()
Esempio n. 19
0
    def rewrite_response(self, resp, extra):
        try:
            if extra.get('rewrite_response', False):
                parser = HttpStream(resp, decompress=True)

                rw = RewriteResponse(parser, resp, extra)
                rw.execute()

            else:
                parser = HttpStream(resp)
                headers = parser.headers()
                headers['connection'] = 'close'

                new_headers = headers_lines(parser, headers)
                resp.writeall("".join(new_headers) + "\r\n")

                body = parser.body_file()
                send_body(resp, body, parser.is_chunked())
        except (socket.error, NoMoreData, ParserError):
            pass
Esempio n. 20
0
    def rewrite_response(self, resp, extra):
        try:
            if extra.get('rewrite_response', False):
                parser = HttpStream(resp, decompress=True)
                
                rw = RewriteResponse(parser, resp, extra)
                rw.execute()

            else:
                parser = HttpStream(resp)
                headers = parser.headers()
                headers['connection'] = 'close'
                
                new_headers = headers_lines(parser, headers)
                resp.writeall("".join(new_headers) + "\r\n")

                body = parser.body_file()
                send_body(resp, body, parser.is_chunked())
        except (socket.error, NoMoreData, ParserError):
            pass
Esempio n. 21
0
def test_upgrade_header():
    stream = io.BytesIO(b'GET /test HTTP/1.1\r\nConnection: keep-alive, upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Key: hojIvDoHedBucveephosh8==\r\nSec-WebSocket-Version: 13\r\n\r\n')
    hdr = HttpStream(stream)
    hdr.headers()
    assert hdr.parser.is_upgrade() == 1

    stream = io.BytesIO(b'GET /test HTTP/1.1\r\nConnection: upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Key: hojIvDoHedBucveephosh8==\r\nSec-WebSocket-Version: 13\r\n\r\n')
    hdr = HttpStream(stream)
    hdr.headers()
    assert hdr.parser.is_upgrade() == 1

    stream = io.BytesIO(b'GET /test HTTP/1.1\r\nConnection: shenanigans\r\n\r\n')
    hdr = HttpStream(stream)
    hdr.headers()
    assert hdr.parser.is_upgrade() == 0
Esempio n. 22
0
def join_data(request: HttpStream, type_: str):
    assert type_ in ('Request', 'Response')
    # try:
    major, minor = request.version()
    # except ParserError:
    #     raise
    if type_ == 'Request':
        url = request.url()
        start_line = f'{request.method()} {url} HTTP/{major}.{minor}'
    else:
        start_line = f'HTTP/{major}.{minor} {request.status()}'

    body = request.body_string(binary=True)
    headers = request.headers()
    setcookies = headers['Set-Cookie'] if 'Set-Cookie' in headers else None
    if "Content-Encoding" in headers:
        assert headers["Content-Encoding"] == "br"
        body = brotli.decompress(body)

    for key in ['Transfer-Encoding', 'Content-Encoding', 'Content-Length', 'Set-Cookie']:
        if key in headers:
            del headers[key]

    headers['Content-Length'] = len(body)
    headers = [f'{key}: {value}' for key, value in headers.items()]
    if setcookies is not None:
        setcookies = setcookies.split(",")
        ind = 0
        while ind < len(setcookies):
            if setcookies[ind].lower()[:-4].endswith('expires'):
                headers.append(f"Set-Cookie: {setcookies[ind]}, {setcookies[ind + 1]}")
                ind += 2
            else:
                headers.append(f"Set-Cookie: {setcookies[ind]}")
                ind += 1
    headers = END_ONE_HEADER.join(headers)

    return (start_line + END_ONE_HEADER + headers + END_HEADERS).encode('ISO-8859-1') + body
Esempio n. 23
0
class CuilRecord(object):
    def __init__(self, host, ip, port, path, response_code, response, original_header):
        self.host = host
        self.ip = ip
        self.port = port
        self.path = path
        self.response_code = response_code
        self.response = response
        self.decompressed_response = self.decompress(response)
        self.parsed_response = HttpStream(StringReader(self.decompressed_response))
        self.original_header = original_header
        self.arc1_record = None
        try:
            self.arc1_record = self.create_arc1_record()
        except NoMoreData:
            logging.warning("  HTTP parser failed on empty header '%s'", self.decompressed_response)
        except ParserError:
            logging.warning("  HTTP parser failed on '%s'", self.decompressed_response)
        except KeyError, k:
            logging.warning("  Couldn't find key %s in %s", k, self.parsed_response.headers().keys())
            logging.warning("  " + self.decompressed_response)
        except AttributeError, e:
            logging.warning("  Unexpected problem", exc_info=True)
Esempio n. 24
0
def rewrite_request(req):
    try:
        while True:
            parser = HttpStream(req)
            headers = parser.headers()

            parsed_url = urlparse.urlparse(parser.url())

            is_ssl = parsed_url.scheme == "https"

            host = get_host(parse_address(parsed_url.netloc, 80),
                            is_ssl=is_ssl)
            headers['Host'] = host
            headers['Connection'] = 'close'

            if 'Proxy-Connection' in headers:
                del headers['Proxy-Connection']

            location = urlparse.urlunparse(
                ('', '', parsed_url.path, parsed_url.params, parsed_url.query,
                 parsed_url.fragment))

            httpver = "HTTP/%s" % ".".join(map(str, parser.version()))

            new_headers = [
                "%s %s %s\r\n" % (parser.method(), location, httpver)
            ]

            new_headers.extend(["%s: %s\r\n" % (hname, hvalue) \
                    for hname, hvalue in headers.items()])

            req.writeall(bytes("".join(new_headers) + "\r\n"))
            body = parser.body_file()
            send_body(req, body, parser.is_chunked())

    except (socket.error, NoMoreData, ParserError):
        pass
Esempio n. 25
0
def rewrite_request(req):
    try:
        while True:
            parser = HttpStream(req)
            headers = parser.headers()

            parsed_url = urlparse.urlparse(parser.url())

            is_ssl = parsed_url.scheme == "https"

            host = get_host(parse_address(parsed_url.netloc, 80),
                is_ssl=is_ssl)
            headers['Host'] = host
            headers['Connection'] = 'close'

            if 'Proxy-Connection' in headers:
                del headers['Proxy-Connection']


            location = urlparse.urlunparse(('', '', parsed_url.path,
                parsed_url.params, parsed_url.query, parsed_url.fragment))

            httpver = "HTTP/%s" % ".".join(map(str, 
                        parser.version()))

            new_headers = ["%s %s %s\r\n" % (parser.method(), location, 
                httpver)]

            new_headers.extend(["%s: %s\r\n" % (hname, hvalue) \
                    for hname, hvalue in headers.items()])

            req.writeall(bytes("".join(new_headers) + "\r\n"))
            body = parser.body_file()
            send_body(req, body, parser.is_chunked())

    except (socket.error, NoMoreData, ParserError):
            pass
Esempio n. 26
0
    def http_proxy(self, connectreq: HttpStream):
        reqheaders = connectreq.headers()
        # if ":" in connectreq.path():
        parsed_url = connectreq.url().split('//')[1].split(':')
        if len(parsed_url) > 1:
            host = parsed_url[0]
            port = parsed_url[1].split('/')[0]
        else:
            host, port = reqheaders['host'], 80
        if 'Proxy-Connection' in reqheaders:
            del reqheaders['Proxy-Connection']
        elif 'proxy-connection' in reqheaders:
            del reqheaders['proxy-connection']

        # request to mail.ru as client
        sock_server = socket.create_connection((host, port))
        try:
            clientreq = join_data(connectreq, 'Request')
        except (http_parser.http.ParserError, http_parser.http.BadStatusLine, ConnectionResetError):
            return

        sock_server.sendall(clientreq)

        # request from mail.ru to localhost as client
        if connectreq.method() == 'HEAD':
            return
        server_reader = SocketReader(sock_server)
        server_resp = HttpStream(server_reader, decompress=True)
        try:
            server_resp_tosend = join_data(server_resp, 'Response')
        except (http_parser.http.ParserError, http_parser.http.BadStatusLine, ConnectionResetError):
            return
        self.request.sendall(server_resp_tosend)

        req = Request(connectreq.method(), server_resp.status_code(), clientreq, host)
        self.add_date_base(connectreq, req)
def process_data(newsocketconn, fromaddr):
    if useSSL:
        connstreamout = context.wrap_socket(newsocketconn, server_side=True)
    else:
        connstreamout = newsocketconn
    ### Output File Name
    outputfile = "Events_" + str(fromaddr[0]) + ".txt"
    logfile = "TimeStamp.log"
    global event_count, data_buffer
    outdata = headers = HostDetails = ""
    try:
        try:
            ### Read the json response using Socket Reader and split header and body
            r = SocketReader(connstreamout)
            p = HttpStream(r)
            headers = p.headers()
            my_logger.info("headers: %s", headers)

            if p.method() == 'POST':
                bodydata = p.body_file().read()
                bodydata = bodydata.decode("utf-8")
                my_logger.info("\n")
                my_logger.info("bodydata: %s", bodydata)
                data_buffer.append(bodydata)
                for eachHeader in headers.items():
                    if eachHeader[0] == 'Host' or eachHeader[0] == 'host':
                        HostDetails = eachHeader[1]

                ### Read the json response and print the output
                my_logger.info("\n")
                my_logger.info("Server IP Address is %s", fromaddr[0])
                my_logger.info("Server PORT number is %s", fromaddr[1])
                my_logger.info("Listener IP is %s", HostDetails)
                my_logger.info("\n")
                outdata = json.loads(bodydata)
                if 'Events' in outdata and config['verbose']:
                    event_array = outdata['Events']
                    for event in event_array:
                        my_logger.info("EventType is %s", event['EventType'])
                        my_logger.info("MessageId is %s", event['MessageId'])
                        if 'EventId' in event:
                            my_logger.info("EventId is %s", event['EventId'])
                        if 'EventGroupId' in event:
                            my_logger.info("EventGroupId is %s", event['EventGroupId'])
                        if 'EventTimestamp' in event:
                            my_logger.info("EventTimestamp is %s", event['EventTimestamp'])
                        if 'Severity' in event:
                            my_logger.info("Severity is %s", event['Severity'])
                        if 'MessageSeverity' in event:
                            my_logger.info("MessageSeverity is %s", event['MessageSeverity'])
                        if 'Message' in event:
                            my_logger.info("Message is %s", event['Message'])
                        if 'MessageArgs' in event:
                            my_logger.info("MessageArgs is %s", event['MessageArgs'])
                        if 'Context' in outdata:
                            my_logger.info("Context is %s", outdata['Context'])
                        my_logger.info("\n")
                if 'MetricValues' in outdata and config['verbose']:
                    metric_array = outdata['MetricValues']
                    my_logger.info("Metric Report Name is: %s", outdata.get('Name'))
                    for metric in metric_array:
                        my_logger.info("Member ID is: %s", metric.get('MetricId'))
                        my_logger.info("Metric Value is: %s", metric.get('MetricValue'))
                        my_logger.info("TimeStamp is: %s", metric.get('Timestamp'))
                        if 'MetricProperty' in metric:
                            my_logger.info("Metric Property is: %s", metric['MetricProperty'])
                        my_logger.info("\n")

                ### Check the context and send the status OK if context matches
                if config['contextdetail'] is not None and outdata.get('Context', None) != config['contextdetail']:
                    my_logger.info("Context ({}) does not match with the server ({})."
                          .format(outdata.get('Context', None), config['contextdetail']))
                StatusCode = """HTTP/1.1 200 OK\r\n\r\n"""
                connstreamout.send(bytes(StatusCode, 'UTF-8'))
                with open(logfile, 'a') as f:
                    if 'EventTimestamp' in outdata:
                        receTime = datetime.now()
                        sentTime = datetime.strptime(outdata['EventTimestamp'], "%Y-%m-%d %H:%M:%S.%f")
                        f.write("%s    %s    %sms\n" % (
                            sentTime.strftime("%Y-%m-%d %H:%M:%S.%f"), receTime, (receTime - sentTime).microseconds / 1000))
                    else:
                        f.write('No available timestamp.')

                try:
                    if event_count.get(str(fromaddr[0])):
                        event_count[str(fromaddr[0])] = event_count[str(fromaddr[0])] + 1
                    else:
                        event_count[str(fromaddr[0])] = 1

                    my_logger.info("Event Counter for Host %s = %s" % (str(fromaddr[0]), event_count[fromaddr[0]]))
                    my_logger.info("\n")
                    fd = open(outputfile, "a")
                    fd.write("Time:%s Count:%s\nHost IP:%s\nEvent Details:%s\n" % (
                        datetime.now(), event_count[str(fromaddr[0])], str(fromaddr), json.dumps(outdata)))
                    fd.close()
                except Exception as err:
                    my_logger.info(traceback.print_exc())

            if p.method() == 'GET':
                # for x in data_buffer:
                #     my_logger.info(x)
                res = "HTTP/1.1 200 OK\n" \
                      "Content-Type: application/json\n" \
                      "\n" + json.dumps(data_buffer)
                connstreamout.send(res.encode())
                data_buffer.clear()

        except Exception as err:
            outdata = connstreamout.read()
            my_logger.info("Data needs to read in normal Text format.")
            my_logger.info(outdata)

    finally:
        connstreamout.shutdown(socket.SHUT_RDWR)
        connstreamout.close()
Esempio n. 28
0
 def add_date_base(self, request: HttpStream, row_request: Request):
     if 'Content-Type' in request.headers() or 'content-type' in request.headers():
         if request.headers()['Content-Type'].lower().startswith(config.CONTENT_TYPES):
             self.session.add(row_request)
             self.session.commit()
Esempio n. 29
0
def read_output_data(newsocketconn, fromaddr):
    if useSSL:
        connstreamout = context.wrap_socket(newsocketconn, server_side=True)
    else:
        connstreamout = newsocketconn
    ### Output File Name
    outputfile = "Events_" + str(fromaddr[0]) + ".txt"
    global event_count
    outdata = headers = HostDetails = ""
    try:
        try:
            ### Read the json response using Socket Reader and split header and body
            r = SocketReader(connstreamout)
            p = HttpStream(r)
            headers = p.headers()
            print("headers: ", headers)
            bodydata = p.body_file().read()
            bodydata = bodydata.decode("utf-8")
            print("bodydata: ", bodydata)
            for eachHeader in headers.items():
                if eachHeader[0] == 'Host' or eachHeader[0] == 'host':
                    HostDetails = eachHeader[1]

            ### Read the json response and print the output
            print("\n")
            print("Server IP Address is ", fromaddr[0])
            print("Server PORT number is ", fromaddr[1])
            print("Listener IP is ", HostDetails)
            outdata = json.loads(bodydata)
            event_array = outdata['Events']
            for event in event_array:
                print("EventType is ", event['EventType'])
                print("MessageId is ", event['MessageId'])
                if 'EventId' in event:
                    print("EventId is ", event['EventId'])
                if 'EventTimestamp' in event:
                    print("EventTimestamp is ", event['EventTimestamp'])
                if 'Severity' in event:
                    print("Severity is ", event['Severity'])
                if 'Message' in event:
                    print("Message is ", event['Message'])
                if 'MessageArgs' in event:
                    print("MessageArgs is ", event['MessageArgs'])
                if 'Context' in outdata:
                    print("Context is ", outdata['Context'])
                print("\n")

        except Exception as err:
            outdata = connstreamout.read()
            print("Data needs to read in normal Text format.")
            print(outdata)

        ### Check the context and send the status OK if context matches
        if outdata.get('Context', None) != ContextDetail:
            print("Context ({}) does not match with the server ({}).".format(
                outdata.get('Context', None), ContextDetail))
        StatusCode = """HTTP/1.1 200 OK\r\n\r\n"""
        connstreamout.send(bytes(StatusCode, 'UTF-8'))

        try:
            if event_count.get(str(fromaddr[0])):
                event_count[str(
                    fromaddr[0])] = event_count[str(fromaddr[0])] + 1
            else:
                event_count[str(fromaddr[0])] = 1

            print("Event Counter for Host %s is %s" %
                  (str(fromaddr[0]), event_count[fromaddr[0]]))
            print("\n")
            fd = open(outputfile, "a")
            fd.write("Time:%s Count:%s\nHost IP:%s\nEvent Details:%s\n" %
                     (time.ctime(), event_count[str(
                         fromaddr[0])], str(fromaddr), outdata))
            fd.close()
        except Exception as err:
            print(traceback.print_exc())

    finally:
        connstreamout.shutdown(socket.SHUT_RDWR)
        connstreamout.close()
Esempio n. 30
0
 def handle(self, upsock, peer):
     with closing(upsock) as upsock:
         origaddr = upsock.getsockname()
         self.logger.debug('intercepted connection from {0} to {1}'.format(peer, origaddr))
         p = HttpStream(SocketReader(upsock))
         self.logger.debug('request: method={0} url={1} version={2} headers={3}'.format(p.method(), p.url(), p.version(), p.headers()))
         url = None
         if p.method() == b'CONNECT':
             self.handle_connect(p, upsock)
         elif p.url()[0] == '/':
             self.handle_transparent(p, upsock)
         else:
             self.handle_proxy(p, upsock)
Esempio n. 31
0
def process_data(newsocketconn, fromaddr, threads):
    if useSSL:
        connstreamout = context.wrap_socket(newsocketconn, server_side=True)
    else:
        connstreamout = newsocketconn
    ### Output File Name
    outputfile = "Events_" + str(fromaddr[0]) + ".txt"
    logfile = "TimeStamp.log"
    global event_count, data_buffer
    outdata = headers = HostDetails = ""
    try:
        try:
            ### Read the json response using Socket Reader and split header and body
            r = SocketReader(connstreamout)
            p = HttpStream(r)
            headers = p.headers()
            #print("headers: ", headers)

            if p.method() == 'POST':
                bodydata = p.body_file().read()
                bodydata = bodydata.decode("utf-8", errors='ignore')
                for eachHeader in headers.items():
                    if eachHeader[0] == 'Host' or eachHeader[0] == 'host':
                        HostDetails = eachHeader[1]

                ### Read the json response and print the output
                #logging.info(f"Server IP Address is {}".format(fromaddr[0])
                outdata = dict()
                current_date = DT.now().strftime("%Y%m%d")
                folder_suffix = "-{}".format(
                    listenerport) if listenerport != '443' else ''
                directory = '{}{}/{}/{}'.format(report_location, folder_suffix,
                                                fromaddr[0], current_date)
                try:
                    outdata = json.loads(bodydata)
                except json.decoder.JSONDecodeError:
                    raw_invalid_file_thread = threading.Thread(
                        target=writeInvalidJason,
                        args=(directory, outdata),
                        name="{}_F".format(fromaddr[0]))
                    threads.append(raw_invalid_file_thread)
                    raw_invalid_file_thread.start()
                if outdata:
                    #writeRawJson(directory, outdata)
                    raw_file_thread = threading.Thread(
                        target=writeRawJson,
                        args=(directory, outdata, fromaddr[0]),
                        name="{}_F".format(fromaddr[0]))
                    threads.append(raw_file_thread)
                    raw_file_thread.start()

                StatusCode = """HTTP/1.1 200 OK\r\n\r\n"""
                connstreamout.send(bytes(StatusCode, 'UTF-8'))
                try:
                    if event_count.get(str(fromaddr[0])):
                        event_count[str(
                            fromaddr[0])] = event_count[str(fromaddr[0])] + 1
                    else:
                        event_count[str(fromaddr[0])] = 1
                    logging.info("Event Counter for Host %s = %s" %
                                 (str(fromaddr[0]), event_count[fromaddr[0]]))
                except Exception as err:
                    logging.error(err)
                    #print(traceback.print_exc())
                for th in threads:
                    th.join()

            if p.method() == 'GET':
                res = "HTTP/1.1 200 OK\n" \
                      "Content-Type: application/json\n" \
                      "\n" + json.dumps(data_buffer)
                connstreamout.send(res.encode())
                data_buffer.clear()
        except Exception as err:
            outdata = connstreamout.read()
            traceback.print_exc()
            #logging.exception(f"Data needs to read in normal Text format.{err}. Message is : {str(outdata)}")
    finally:
        connstreamout.shutdown(socket.SHUT_RDWR)
        connstreamout.close()
        logging.debug("Connection closed")
Esempio n. 32
0
def processData(newsocketconn, fromaddr, context):
    if useSSL:
        connstreamout = context.wrap_socket(newsocketconn, server_side=True)
    else:
        connstreamout = newsocketconn
    global event_count, data_buffer
    outdata = headers = HostDetails = ""
    try:
        try:
            ### Read the json response using Socket Reader and split header and body
            r = SocketReader(connstreamout)
            p = HttpStream(r)
            headers = p.headers()

            if p.method() == 'POST':
                bodydata = p.body_file().read()
                bodydata = bodydata.decode("utf-8", errors='ignore')
                for eachHeader in headers.items():
                    if eachHeader[0] == 'Host' or eachHeader[0] == 'host':
                        HostDetails = eachHeader[1]

                ### Read the json response and print the output
                print("Server IP Address is ", fromaddr[0])
                outdata = dict()
                # current_date = DT.now().strftime("%Y%m%d")
                # folder_suffix = "-{}".format(listenerport)  if listenerport != '443' else ''
                # directory = '{}{}/{}/{}'.format(report_location,folder_suffix,fromaddr[0],current_date)
                try:
                    print(bodydata)
                    with open("output.json", "a+") as f:
                        f.write(bodydata)
                        f.write("\n")
                except json.decoder.JSONDecodeError:
                    print("Exception occurred while processing report")

                # influx_thread = threading.Thread(target=writeReportToInflux, args=(fromaddr[0],directory, outdata))
                # threads.append(influx_thread)
                # influx_thread.start()

                StatusCode = """HTTP/1.1 200 OK\r\n\r\n"""
                connstreamout.send(bytes(StatusCode, 'UTF-8'))
                # try:
                #    if event_count.get(str(fromaddr[0])):
                #        event_count[str(fromaddr[0])] = event_count[str(fromaddr[0])] + 1
                #    else:
                #        event_count[str(fromaddr[0])] = 1
                #    # logger.info("Event Counter for Host %s = %s" % (str(fromaddr[0]), event_count[fromaddr[0]]))
                # except Exception as err:
                #    print(traceback.print_exc())
                # for th in threads:
                #     th.join()   

            if p.method() == 'GET':
                
                res = "HTTP/1.1 200 OK\n" \
                      "Content-Type: application/json\n" \
                      "\n" + json.dumps(data_buffer)
                connstreamout.send(res.encode())
                data_buffer.clear()

        except Exception as err:
            outdata = connstreamout.read()
            traceback.print_exc()
            print("Data needs to read in normal Text format.")
            print(outdata)

    finally:
        connstreamout.shutdown(socket.SHUT_RDWR)
        connstreamout.close()
Esempio n. 33
0
def processData(newsocketconn, fromaddr, context, ipaddr):
    if useSSL:
        connstreamout = context.wrap_socket(newsocketconn, server_side=True)
    else:
        connstreamout = newsocketconn
    global event_count, data_buffer
    outdata = headers = HostDetails = ""
    try:
        try:
            ### Read the json response using Socket Reader and split header and body
            r = SocketReader(connstreamout)
            p = HttpStream(r)
            headers = p.headers()

            if p.method() == 'POST':
                bodydata = p.body_file().read()
                bodydata = bodydata.decode("utf-8", errors='ignore')

                ### Read the json response and print the output
                # outdata = dict()
                try:
                    old_time = getTimestampfromFilename(ipaddr[2])
                    new_time = (datetime.strptime(old_time, "%Y%m%d%H%M%S") +
                                timedelta(seconds=int(ipaddr[4]))
                                ).strftime("%Y%m%d%H%M%S")
                    cur_time = datetime.now().strftime("%Y%m%d%H%M%S")
                    a = np.where(
                        int(cur_time) > int(new_time), new_time, False)
                    fd = ipaddr[2]
                    if eval(a.item(0)):
                        filename = fd.name.split("/")[-1]
                        # print(filename, "<--test")

                        os.system(f"gzip {ipaddr[3]}/output/{filename}")
                        shutil.move(f"{ipaddr[3]}/output/{filename}.gz",
                                    f"{ipaddr[3]}/complete/")

                        fd.close()

                        filename = ipaddr[0] + '_' + ipaddr[
                            1] + '_' + fromaddr[0] + '_' + new_time + ".jsonl"
                        try:
                            fd = open(f"{ipaddr[3]}/output/{filename}", "a+")
                        except FileNotFoundError as ex:
                            if not os.path.exists(f"{file_collection_path}"):
                                os.makedirs(file_collection_path)
                        ipaddr[2] = open(f"{ipaddr[3]}/output/{filename}",
                                         "a+")
                    # print(bodydata, type(bodydata), "<---bodydata")
                    fd.write(bodydata)
                    fd.write("\n")
                except Exception as ex:
                    print("Exception Occured =", ex)

                StatusCode = """HTTP/1.1 200 OK\r\n\r\n"""
                connstreamout.send(bytes(StatusCode, 'UTF-8'))
                # try:
                #    if event_count.get(str(fromaddr[0])):
                #        event_count[str(fromaddr[0])] = event_count[str(fromaddr[0])] + 1
                #    else:
                #        event_count[str(fromaddr[0])] = 1
                #    # logger.info("Event Counter for Host %s = %s" % (str(fromaddr[0]), event_count[fromaddr[0]]))
                # except Exception as err:
                #    print(traceback.print_exc())
                # for th in threads:
                #     th.join()

            if p.method() == 'GET':

                res = "HTTP/1.1 200 OK\n" \
                      "Content-Type: application/json\n" \
                      "\n" + json.dumps(data_buffer)
                connstreamout.send(res.encode())
                data_buffer.clear()

        except Exception as err:
            outdata = connstreamout.read()
            traceback.print_exc()
            print("Data needs to read in normal Text format.")
            print(outdata)

    finally:
        connstreamout.shutdown(socket.SHUT_RDWR)
        connstreamout.close()
Esempio n. 34
0
async def processData(newsocketconn, fromaddr, context, ipaddr):
    if useSSL:
        connstreamout = context.wrap_socket(newsocketconn, server_side=True)
    else:
        connstreamout = newsocketconn
    global event_count, data_buffer
    outdata = headers = HostDetails = ""
    try:
        try:
            ### Read the json response using Socket Reader and split header and body
            r = SocketReader(connstreamout)
            p = HttpStream(r)
            headers = p.headers()

            if p.method() == 'POST':
                bodydata = p.body_file().read()
                bodydata = bodydata.decode("utf-8", errors='ignore')
                for eachHeader in headers.items():
                    if eachHeader[0] == 'Host' or eachHeader[0] == 'host':
                        HostDetails = eachHeader[1]

                ### Read the json response and print the output
                outdata = dict()
                try:
                    # get Current fd Timestamp
                    timestamp = getTimestampfromFilename(ipaddr)
                    # createJsonFile(ipaddr)
                    fd = ipaddr[2]
                    newFile = canGernerateNewJsonFile(timestamp, ipaddr[4])
                    if newFile:
                        print(f"newfile Creates for iDRAC {fromaddr[0]}")
                        fd = createJsonFile(ipaddr, fromaddr[0])
                        ipaddr[2] = fd
                    fd.write(bodydata)
                    fd.write("\n")

                except Exception as ex:
                    print("Exception occurred while processing report", ex)

                # influx_thread = threading.Thread(target=writeReportToInflux, args=(fromaddr[0],directory, outdata))
                # threads.append(influx_thread)
                # influx_thread.start()

                StatusCode = """HTTP/1.1 200 OK\r\n\r\n"""
                connstreamout.send(bytes(StatusCode, 'UTF-8'))
                # try:
                #    if event_count.get(str(fromaddr[0])):
                #        event_count[str(fromaddr[0])] = event_count[str(fromaddr[0])] + 1
                #    else:
                #        event_count[str(fromaddr[0])] = 1
                #    # logger.info("Event Counter for Host %s = %s" % (str(fromaddr[0]), event_count[fromaddr[0]]))
                # except Exception as err:
                #    print(traceback.print_exc())
                # for th in threads:
                #     th.join()

            if p.method() == 'GET':

                res = "HTTP/1.1 200 OK\n" \
                      "Content-Type: application/json\n" \
                      "\n" + json.dumps(data_buffer)
                connstreamout.send(res.encode())
                data_buffer.clear()

        except Exception as err:
            outdata = connstreamout.read()
            traceback.print_exc()
            print("Data needs to read in normal Text format.")
            print(outdata)

    finally:
        connstreamout.shutdown(socket.SHUT_RDWR)
        connstreamout.close()