Created
November 1, 2020 13:41
-
-
Save EvelynSubarrow/5baaa27661706aa986bbe2c49a168d1d to your computer and use it in GitHub Desktop.
UDP broadcast with hmac and sequence ID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import socket, hashlib, struct | |
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) # UDP | |
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) | |
client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) | |
client.bind(("", 37700)) | |
def receive(hmac): | |
data, addr = client.recvfrom(1024) | |
if len(data) < 45: return | |
magic = data[:2] | |
hash = data[3:35] | |
full_body = data[36:] | |
seq_id = struct.unpack(">Q", full_body[:8]) | |
body = full_body[9:] | |
comp_hash = hashlib.sha256(hmac.encode("utf8") + full_body).digest() | |
if comp_hash == hash: | |
return (seq_id, body.decode("utf8")) | |
while True: | |
print(receive("Jeger")) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from socket import * | |
import time, hashlib, struct, datetime | |
cs = socket(AF_INET, SOCK_DGRAM) | |
cs.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1) | |
cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) | |
def send_message(message, hmac): | |
# sequence + LF + message | |
message_body = struct.pack(">Q", int(datetime.datetime.now().timestamp())) + b"\n" + message.encode("utf8") | |
# digest of hmac + full message hash | |
message_digest = hashlib.sha256(hmac.encode("utf8") + message_body).digest() | |
# "DN" + LF + digest + LF + body (sequence + LF + message) | |
composed_message = b"DN\n" + message_digest + b"\n" + message_body | |
# broadcast defaults to 255.255.255.255 which is technically not correct for this net but it works idk | |
cs.sendto(composed_message, ('<broadcast>', 37700)) | |
send_message('{"value": 105}', "Jeger") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment