def handle(self, data): shutdown = False http = HTTP(data) if http.name == 'HTTP 1': httpr = http.payload if httpr.name == 'HTTP Request': print() print("=== Request ===") print(httpr.summary()) payload = "" if httpr.Path.decode('ascii') == "/Metrics": with self.lock: payload = dumps(dict(self.faasMetrics)) # elif httpr.Path.decode('ascii') == "/Shutdown": # payload = str(time()) # shutdown = True elif httpr.Path.decode('ascii') == "/Run": payload = str(time()) else: print("Bad Path") return bytes(HTTP() / HTTPResponse(Status_Code='200') / Raw(load=payload)), shutdown else: return bytes(HTTP / HTTPResponse(Status_Code='405')), shutdown else: return bytes(HTTP / HTTPResponse(Status_Code='400')), shutdown
def test_proxy_behaviour(self): with requests_mock.Mocker() as m: m.get( "http://foo.svc", status_code=200, headers={"Content-Type": "application/json"}, text="success", ) raw = dump.dump_response( requests.get("http://foo.svc"), request_prefix="", response_prefix="@@@", ) split = raw.split(b"@@@") raw_request = split[0] expected_response = HTTPResponse(b"".join(split[1:])) raw_request handler = TestableHandler(raw_request, (0, 0), None) write_file = io.BytesIO() handler.test(write_file) write_file.seek(0) response = HTTPResponse(write_file.read()) self.assertEqual(response.Status_Code, expected_response.Status_Code) self.assertEqual(response.Content_Type, expected_response.Content_Type) self.assertEqual(response.load, expected_response.load)
def __init__(self, port, rprob=0.07): """Constructor""" self.s = RstegSocket(rprob=rprob, sport=port) self.s.bind('', port) # Load in memory the html responses index_data = open('./index.html', 'rb').read() upload_data = open('./upload.html', 'rb').read() # Load the HTTP Response data structure self.res = HTTP() / HTTPResponse() self.index = HTTP() / HTTPResponse(Content_Length=str( len(index_data)).encode(), ) / index_data self.upload = HTTP() / HTTPResponse(Content_Length=str( len(upload_data)).encode(), ) / upload_data self.not_found = HTTP() / HTTPResponse(Status_Code=b'404', Reason_Phrase=b'Not Found')
def handle(self, data): http = HTTP(data) if http.name == 'HTTP 1': httpr = http.payload if httpr.name == 'HTTP Request': s = httpr.Path.decode('ascii') n = s.rindex("/") faasIP = self.decide(s[n + 1:]) print() print("=== Redirection ===") print(httpr.summary(), " --> ", faasIP) if faasIP: global response if httpr.Method.decode('ascii') == 'POST': response = post( url="http://" + faasIP + ':' + str(self.Port) + httpr.Path.decode('ascii'), data=httpr.payload.load.decode('ascii')) elif http.Method.decode('ascii') == 'GET': response = get(url="http://" + faasIP + ':' + str(self.Port) + httpr.Path.decode('ascii'), data=httpr.payload.load.decode('ascii')) else: print("Other request method") response = None if response: return bytes( HTTP() / HTTPResponse(Status_Code=str(response.status_code)) / Raw(load=response.content.decode('ascii'))) else: return bytes(HTTP / HTTPResponse(Status_Code='405') / Raw()) else: return bytes(HTTP / HTTPResponse(Status_Code='400') / Raw()) else: return bytes(HTTP / HTTPResponse(Status_Code='400') / Raw()) else: return bytes(HTTP / HTTPResponse(Status_Code='400') / Raw())
def handle(self, data, address): shutdown = False http = HTTP(data) if http.name == 'HTTP 1': httpr = http.payload if httpr.name == 'HTTP Request': print() print("=== Request ===") print(httpr.summary(), address) payload = "" if httpr.Method.decode('ascii') == 'POST': with self.lock: self.hosts[address] = time() elif httpr.Method.decode('ascii') == 'GET': if httpr.Path.decode('ascii') == "/Hosts": with self.lock: for host in self.hosts.keys(): payload += host + ' ' # elif httpr.Path.decode('ascii') == "/Shutdown": # payload = str(time()) # shutdown = True else: payload = str(time()) else: print(">>> Other request method") return bytes(HTTP() / HTTPResponse(Status_Code='200') / Raw(load=payload)), shutdown else: return bytes(HTTP / HTTPResponse(Status_Code='405')), shutdown else: return bytes(HTTP / HTTPResponse(Status_Code='400')), shutdown
def check_protocol_on_port(_socket) -> str: try: _socket.send(HTTPRequest().build()) pkt_response = _socket.recv(BYTES_BUFFER_SIZE) if HTTPResponse(_pkt=pkt_response).Status_Code != 0: return 'http' except: pass try: _socket.send('HELO'.encode()) pkt_response = _socket.recv(BYTES_BUFFER_SIZE) data = pkt_response.decode() int(data[:3]) return 'smtp' except: pass try: _socket.send('USER mrose'.encode()) pkt_response = _socket.recv(BYTES_BUFFER_SIZE) data = pkt_response.decode() if any(['+OK' in data, '-ERR' in data]): return 'pop3' except: pass try: _socket.send(DNS(qr=0, qd=DNSQR()).build()) pkt_response = _socket.recv(BYTES_BUFFER_SIZE) if DNS(_pkt=pkt_response).qr == 1: return 'dns' except: pass try: _socket.send(NTPHeader().build()) pkt_response = _socket.recv(BYTES_BUFFER_SIZE) if NTPHeader(_pkt=pkt_response).recv != 0: return 'ntp' except: pass return ''
def request(self, req, host): """Send the request to host and return response. :param req: HTTP request :param host: host ip addr :return res: HTTP response """ self.s.connect(host, 80) self.s.send(req) res = self.s.recv(1024, self.timeout) http_response = HTTPResponse(res) length = http_response[HTTPResponse].Content_Length while len(res) < int(length): buf = self.s.recv(1500) if buf: res += buf self.s.close() return res
def test_saga_behaviour(self): configuration = { "host": "productpage.svc", "matchRequest": { "method": "GET", "url": "http://localhost:3001/", "headers": { "Start-Faking": "True" }, }, "onMatchedRequest": [ { "method": "GET", "url": "http://ratings.svc/add/${parent.headers.Product-Id}", "isSuccessIfReceives": [{ "status-code": 200, "headers": { "Content-type": "application/json" }, }], "onFailure": [{ "method": "GET", "url": "http://ratings.svc/delete/${root.headers.Product-Id}", "timeout": 3, "maxRetriesOnTimeout": 1, "isSuccessIfReceives": [{ "status-code": 200, "headers": { "Content-type": "application/json" }, }], }], "timeout": 30, "maxRetriesOnTimeout": 3, }, { "method": "GET", "url": "http://details.svc/details/add/${root.headers.Product-Id}", "isSuccessIfReceives": [{ "status-code": 200, "headers": { "Content-type": "application/json" }, }], "onFailure": [{ "method": "GET", "url": "http://details.svc/details/remove/${root.headers.Product-Id}", "timeout": 3, "maxRetriesOnTimeout": 1, "isSuccessIfReceives": [{ "status-code": 200, "headers": { "Content-type": "application/json" }, }], }], "timeout": 30, "maxRetriesOnTimeout": 3, }, ], "onAllSucceeded": { "status-code": 200, "body": "Ratings: ${transaction[0].response.body}\nDetails: ${transaction[1].response.body}\n", }, "onAnyFailed": { "status-code": 500, "body": "Ratings: ${transaction[0].response.body}\nDetails: ${transaction[1].response.body}\n", }, } with requests_mock.Mocker() as m: m.get( "http://ratings.svc/add/12", status_code=200, headers={"Content-type": "application/json"}, text="success", ) m.get( "http://details.svc/details/add/12", status_code=200, headers={"Content-type": "application/json"}, text="success again", ) raw_request = b"GET / HTTP/1.1\r\nHost: http://localhost:3001\r\nUser-Agent: python-requests/2.9.1\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\nStart-Faking: True\r\nProduct-Id: 12\r\n\r\n" with patch("builtins.open", mock_open( read_data=yaml.dump(configuration))) as mock_file: with patch("os.path.exists") as os_mock: os_mock.return_value = True handler = TestableHandler(raw_request, (0, 0), None) write_file = io.BytesIO() handler.test(write_file) write_file.seek(0) response = HTTPResponse(write_file.read()) self.assertEqual(response.Status_Code, b"200") self.assertEqual( response.load, b"Ratings: success\nDetails: success again\n")
from scapy import * from scapy.layers.http import HTTPRequest,HTTPResponse,HTTP,http_request from scapy.all import load_layer from scapy.all import sr1,IP,ICMP,TCPSession,sr,srp,srp1,send,sendp,sendpfast,RandShort from scapy.layers.inet import TCP_client,TCP,Ether,UDP ans,unans = sr(IP(dst="8.8.8.8")/TCP(dport=[80,443],flags="S"),timeout=1) p=sr1(IP(dst='8.8.8.8')/ICMP()) if p: p.show() dir(scapy.layers.http) HTTPRequest().show() HTTPResponse().show() load_layer("http") req = HTTP()/HTTPRequest( Accept_Encoding=b'gzip, deflate', Cache_Control=b'no-cache', Connection=b'keep-alive', Host=b'www.secdev.org', Pragma=b'no-cache' ) a = TCP_client.tcplink(HTTP, "secdev.org", 80) answser = a.sr1(req,timeout=3) a.close() with open("www.secdev.org.html", "wb") as file: file.write(answser.load)