-
Notifications
You must be signed in to change notification settings - Fork 5
/
replicator.py
79 lines (60 loc) · 2.32 KB
/
replicator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python
from settings import *
import binascii
import re
import socket
import sys
import logging
import os
# https://regex101.com/r/2l8eJp/3
DGRAM_REGEX = re.compile(r'(?:^([fF]{12})(([0-9a-fA-F]{12}){16})([0-9a-fA-F]{12})?$)')
def is_allowed(address, password):
if address in FORCED_AUTH_HOSTS:
logger.debug("Enforcing authentication for %s" % address)
return password == FORCED_AUTH_HOSTS[address]
return True
def forward_packet(data):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.connect((TARGET_ADDRESS, TARGET_PORT))
sock.send(data)
sock.close()
def handle_packet(data):
payload = binascii.hexlify(data)
logger.debug("Received payload: %s" % payload)
if DGRAM_REGEX.match(payload):
search = DGRAM_REGEX.search(payload)
address = search.group(3)
password = search.group(4)
if is_allowed(address, password):
logger.debug("Forwarding the packet for %s to %s:%s" % (address, TARGET_ADDRESS, TARGET_PORT))
forward_packet(data)
else:
logger.debug("This request has been denied because the received password is not correct")
else:
logger.debug("Received payload is not valid, ignoring...")
def start_listener():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((BIND_ADDRESS, BIND_PORT))
while True:
data, addr = sock.recvfrom(108)
logger.debug("Received packet from %s:%s" % (addr[0], addr[1]))
handle_packet(data)
if __name__ == '__main__':
logFormatter = logging.Formatter("%(asctime)s [%(levelname)s] - %(message)s")
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
path = os.path.dirname(os.path.realpath(__file__))
file = os.path.join(path, "app.log")
fileHandler = logging.FileHandler(file)
fileHandler.setFormatter(logFormatter)
logger.addHandler(fileHandler)
consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(logFormatter)
logger.addHandler(consoleHandler)
try:
logger.debug("The application has now started listening for packets")
start_listener()
except KeyboardInterrupt:
logger.debug("Exiting because of keyboard interrupt")
sys.exit()