-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
65 lines (47 loc) · 2.31 KB
/
main.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
from os import environ
from re import search
from os import mkdir
from typing import Dict
ENV_VARIABLE_PREFIX: str = "TOR_HIDDEN_SERVICE_"
KEY_REGEX: str = "^" + ENV_VARIABLE_PREFIX + "([a-zA-Z0-9]+)$"
ADDRESS_REGEX: str = "^([0-9]{1,5}) [a-zA-Z0-9.]+:([0-9]{1,5})$"
PRIVATE_KEY_REGEX: str = r"-{3,}BEGIN RSA PRIVATE KEY-{3,}\n([\s\S]*?)\n-{3,}END RSA PRIVATE KEY-{3,}"
def check_port(port_to_check: int) -> bool:
return 0 < port_to_check < 2 ** 16
TOR_CONF_DIRECTORY: str = "/etc/torrc.d/"
TOR_DATA_DIRECTORY: str = "/var/lib/tor/hidden_services/"
if __name__ == "__main__":
try:
mkdir(TOR_DATA_DIRECTORY)
except OSError:
pass
services: Dict[str, str] = {result.group(1): str(value) for key, value in environ.items() if
(result := search(KEY_REGEX, key))}
for key, value in services.items():
print("[" + key + "] generating configuration...")
service_id: str = key
print("[" + key + "] calculated service id:", service_id)
private_key_key: str = ENV_VARIABLE_PREFIX + key + "_PRIVATE_KEY"
with open(TOR_CONF_DIRECTORY + service_id, "w") as config_file:
config_file_content: str = "HiddenServiceDir " + TOR_DATA_DIRECTORY + service_id + "/\n"
for port_forwarding in value.split(";"):
port_forwarding = port_forwarding.strip()
if not (result := search(ADDRESS_REGEX, port_forwarding)):
print("[" + key + "] address does not match:", port_forwarding)
continue
try:
for port in result.groups():
if not check_port(int(port)):
print("[" + key + "] port not valid:", port)
continue
except ValueError:
print("[" + key + "] port not found.")
continue
config_file_content += "HiddenServicePort " + port_forwarding + "\n"
config_file.write(config_file_content)
print("[" + key + "] hostname will appear in", TOR_DATA_DIRECTORY + service_id + "/hostname")
try:
mkdir(TOR_DATA_DIRECTORY + service_id)
except OSError:
print("[" + key + "] data already exists.")
continue