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 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
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)
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 handle(self): self.logger = logging.getLogger("proxy") self.session = Session() try: request = HttpStream(SocketReader(self.request)) _ = request.status() except http_parser.http.BadStatusLine: return self.logger.warning(request.path()) if 'CONNECT' == request.method(): self.https_proxy(request) else: self.http_proxy(request) self.session.close()
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()
def https_proxy(self, connectreq: HttpStream): self.request.sendall(CON_ESTABLISH) host, port = connectreq.path().split(':') cert_path = self.generate_cert(host) # request to localhost as server try: sock_client = ssl.wrap_socket(self.request, keyfile="cert.key", certfile=cert_path, ssl_version=ssl.PROTOCOL_TLS, server_side=True) sock_server = socket.create_connection((host, port)) sock_server = ssl.create_default_context().wrap_socket(sock_server, server_hostname=host) except OSError: return client_reader = SocketReader(sock_client) server_reader = SocketReader(sock_server) while True: # request to mail.ru as client clientreq = HttpStream(client_reader, decompress=True) try: clientreq_tosend = join_data(clientreq, 'Request') except (http_parser.http.ParserError, http_parser.http.BadStatusLine, ConnectionResetError): return sock_server.sendall(clientreq_tosend) # request from mail.ru to localhost as client 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 try: sock_client.sendall(server_resp_tosend) except BrokenPipeError: return req = Request(clientreq.method(), server_resp.status_code(), clientreq_tosend, host) self.add_date_base(clientreq, req)
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
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
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()
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()
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()
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()
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")