-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtoroxy
executable file
·241 lines (192 loc) · 6.24 KB
/
toroxy
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#!/usr/bin/python
import os
import sys
import commands
import time
import urllib2
import signal
from commands import getoutput
from stem import Signal
from stem.control import Controller
class Strings:
TORRC_CONFIG = """
VirtualAddrNetwork 10.0.0.0/10
AutomapHostsOnResolve 1
TransPort 9040
DNSPort 53
ControlPort 9051
"""
IPTABLES_STOP_RULES = """
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -t nat -F
iptables -t mangle -F
iptables -F
iptables -X
ip6tables -F
"""
IPTABLES_START_RULES = """
NON_TOR="192.168.1.0/24 192.168.0.0/24"
TOR_UID=%s
TRANS_PORT="9040"
iptables -F
iptables -t nat -F
iptables -t nat -A OUTPUT -m owner --uid-owner $TOR_UID -j RETURN
iptables -t nat -A OUTPUT -p udp --dport 53 -j REDIRECT --to-ports 53
for NET in $NON_TOR 127.0.0.0/9 127.128.0.0/10; do
iptables -t nat -A OUTPUT -d $NET -j RETURN
done
iptables -t nat -A OUTPUT -p tcp --syn -j REDIRECT --to-ports $TRANS_PORT
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
for NET in $NON_TOR 127.0.0.0/8; do
iptables -A OUTPUT -d $NET -j ACCEPT
done
iptables -A OUTPUT -m owner --uid-owner $TOR_UID -j ACCEPT
iptables -A OUTPUT -j REJECT
ip6tables -A OUTPUT -j REJECT
"""
DUMP_TOROXY_IPTTABLES_RULES_CMD = """
iptables-save > /etc/iptables/rules.v4
ip6tables-save > /etc/iptables/rules.v6
netfilter-persistent start && netfilter-persistent save
"""
TOROXY_SETUP_SERVICES_CMD = """
cp ./toroxy.service /etc/systemd/system/toroxy.service
chmod 644 /etc/systemd/system/toroxy.service
systemctl daemon-reload
systemctl stop toroxy
systemctl start toroxy
systemctl enable toroxy
systemctl stop tor
systemctl start tor
systemctl enable tor
systemctl stop netfilter-persistent
systemctl start netfilter-persistent
systemctl enable netfilter-persistent
"""
TOROXY_NOTIFICATION_CMD = """
# root UI
eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ)"
export DISPLAY=:0
for USR in `ls /home && echo root`
do
# ubuntu gnome + root UI
export XAUTHORITY=/home/$USR/.Xauthority
notify-send -u {0} '{1}' '{2}'
# ubuntu parallels
for UID in `ls /run/user/`
do
su $USR -c "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$UID/bus notify-send -u {0} '{1}' '{2}'"
done
done
"""
RULES_CHECKSUM_CMD = "{ iptables-save && ip6tables-save; } | sed s/\-\-uid\-owner\\\\s[0-9]\\\\+\\\\s//g | grep -viE '^#' | grep -viE '^\:' | sort | uniq | sha256sum | cut -d' ' -f 1"
IP_OBTAIN_CMD = 'wget -qO- https://check.torproject.org | grep -Po "(?<=strong>)[\d\.]+(?=</strong)"'
RULES_CHECKSUM_CORRECT_HASH = "dd152ac82159c1d0a04e4c95034f32f1ec12d49408faae4b9182b576954d018f"
TOR_DNS = "nameserver 127.0.0.1"
TOR_TORRC = "/etc/tor/torrc"
RESOLV_FILE = "/etc/resolv.conf"
class Toroxy:
lastSnapshotFileName = None
def ip(self):
try:
return commands.getstatusoutput(Strings.IP_OBTAIN_CMD)[1]
except :
return '';
def getStartRules(self):
return Strings.IPTABLES_START_RULES%(getoutput("id -ur debian-tor"))
def rulesOk(self):
checkSum = getoutput(Strings.RULES_CHECKSUM_CMD).strip()
alright = checkSum == Strings.RULES_CHECKSUM_CORRECT_HASH
if not alright:
rules = getoutput('iptables-save && ip6tables-save')
self.lastSnapshotFileName = "/tmp/broken-rules-%s.log" % time.strftime("%d-%m-%Y_%I-%M-%S")
open(self.lastSnapshotFileName, "w").write(rules)
return False
else:
return True
def changeResolveConf(self):
os.system('sudo cp -p %s %s.toroxy.bak' % (Strings.RESOLV_FILE, Strings.RESOLV_FILE))
if not Strings.TOR_DNS in open(Strings.RESOLV_FILE).read():
with open(Strings.RESOLV_FILE, "w") as resolvConf:
resolvConf.write(Strings.TOR_DNS)
def unchangeResolveConf(self):
os.system('sudo mv %s.toroxy.bak %s' % (Strings.RESOLV_FILE, Strings.RESOLV_FILE))
os.system("service network-manager restart")
def changeTorrc(self):
os.system('sudo cp -p %s %s.toroxy.bak' % (Strings.TOR_TORRC, Strings.TOR_TORRC))
if not Strings.TORRC_CONFIG in open(Strings.TOR_TORRC).read():
with open(Strings.TOR_TORRC, "a") as torrc:
torrc.write(Strings.TORRC_CONFIG)
def unchangeTorrc(self):
os.system('sudo mv %s.toroxy.bak %s' % (Strings.TOR_TORRC, Strings.TOR_TORRC))
def changeFirewall(self):
iptables_rules = """
%s
%s
""" % (Strings.IPTABLES_STOP_RULES, self.getStartRules())
os.system(iptables_rules)
def unchangeFirewall(self):
os.system(Strings.IPTABLES_STOP_RULES)
def restart(self):
self.changeTorrc()
self.changeResolveConf()
os.system("service tor start")
self.changeFirewall()
def stop(self):
self.unchangeFirewall()
self.unchangeResolveConf()
self.unchangeTorrc()
def switch(self):
time.sleep(7)
with Controller.from_port(port = 9051) as controller:
controller.authenticate()
controller.signal(Signal.NEWNYM)
def install(self):
os.system("cp '%s' /usr/bin/toroxy" % (sys.argv[0]))
self.restart()
os.system(Strings.DUMP_TOROXY_IPTTABLES_RULES_CMD)
self.stop()
os.system(Strings.TOROXY_SETUP_SERVICES_CMD)
def notify(self, title, text='Toroxy', level='critical'):
os.system(Strings.TOROXY_NOTIFICATION_CMD.format(level, title, text))
def service(self):
ipPrev = ''
self.restart()
while True:
if not self.rulesOk():
self.restart()
msg = 'IpTables integrity violation detected!\nSnapshot in %s.\nFixed.' % self.lastSnapshotFileName
self.notify('Toroxy', msg, 'critical')
try:
ipCurr = self.ip().strip()
if not ipCurr:
raise Exception()
if not ipCurr == ipPrev:
ipPrev = ipCurr
self.notify('Toroxy', 'Ip changed: '+ipCurr, 'low')
except:
self.switch()
time.sleep(1)
class Signals:
def shutdown(self):
sys.exit()
def sigint_handler(self, signum, frame):
shutdown()
def setup(self):
signal.signal(signal.SIGINT, self.sigint_handler)
############################################################################
if __name__ == "__main__":
Signals().setup()
if len(sys.argv) > 1:
if sys.argv[1] == "stop":
Toroxy().stop()
elif sys.argv[1] == "switch":
Toroxy().switch()
elif sys.argv[1] == "service":
Toroxy().service()
elif sys.argv[1] == "install":
Toroxy().install()
else:
print "Use: toroxy stop|switch|service|install"