forked from daftaupe/munin-tor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtor_.py
More file actions
executable file
·337 lines (270 loc) · 11 KB
/
tor_.py
File metadata and controls
executable file
·337 lines (270 loc) · 11 KB
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#!/usr/bin/python2
from __future__ import print_function
import os
import sys
try:
import stem
from stem.control import Controller
except ImportError:
print('no (tor-munin requires the stem library from https://stem.torproject.org.)')
sys.exit()
import circuits_by_country
'''
Here be dragons
'''
#%# family=auto
#%# capabilities=autoconf suggest
class ConnectionError(Exception):
"""Error connecting to the controller"""
class AuthError(Exception):
"""Error authenticating to the controller"""
def authenticate(controller):
try:
controller.authenticate()
return
except stem.connection.MissingPassword:
pass
try:
password = os.environ['torpassword']
except KeyError:
raise AuthError("Please configure the 'torpassword' "
"environment variable")
try:
controller.authenticate(password=password)
except stem.connection.PasswordAuthFailed:
print("Authentication failed (incorrect password)")
def gen_controller():
connect_method = os.environ.get('connectmethod', 'port')
if connect_method == 'port':
return Controller.from_port(port=os.environ.get('port', 9051))
elif connect_method == 'socket':
return Controller.from_socket_file(path=os.environ.get('socket', '/var/run/tor/control'))
else:
print("env.connectmethod contains an invalid value. Please specify either 'port' or 'socket'.", file=sys.stderr)
sys.exit(-1)
#########################
# Base Class
#########################
class TorPlugin(object):
def __init__(self):
raise NotImplementedError
def conf(self):
raise NotImplementedError
@staticmethod
def conf_from_dict(graph, labels):
# header
for key, val in graph.iteritems():
print('graph_{} {}'.format(key, val))
# values
for label, attributes in labels.iteritems():
for key, val in attributes.iteritems():
print('{}.{} {}'.format(label, key, val))
@staticmethod
def autoconf():
try:
with gen_controller() as controller:
try:
authenticate(controller)
print('yes')
except stem.connection.AuthenticationFailure as e:
print('no (Authentication failed: {})'.format(e))
except stem.connection:
print('no (Connection failed)')
@staticmethod
def suggest():
options = ['connections', 'traffic', 'dormant', 'bandwidth', 'flags']
tc = circuits_by_country.TorCountries()
if tc.available:
options.append('countries')
for option in options:
print(option)
def fetch(self):
raise NotImplementedError
##########################
# Child Classes
##########################
class TorConnections(TorPlugin):
def __init__(self):
pass
def conf(self):
graph = {'title': 'Connections',
'args': '-l 0 --base 1000',
'vlabel': 'connections',
'category': 'Tor',
'info': 'OR connections by state'}
labels = {'new': {'label': 'new', 'min': 0, 'max': 25000, 'type': 'GAUGE'},
'launched': {'label': 'launched', 'min': 0, 'max': 25000, 'type': 'GAUGE'},
'connected': {'label': 'connected', 'min': 0, 'max': 25000, 'type': 'GAUGE'},
'failed': {'label': 'failed', 'min': 0, 'max': 25000, 'type': 'GAUGE'},
'closed': {'label': 'closed', 'min': 0, 'max': 25000, 'type': 'GAUGE'}}
TorPlugin.conf_from_dict(graph, labels)
def fetch(self):
with gen_controller() as controller:
try:
authenticate(controller)
response = controller.get_info('orconn-status', None)
if response is None:
print("No response from Tor daemon in TorConnection.fetch()", file=sys.stderr)
sys.exit(-1)
else:
connections = response.split('\n')
states = dict((state, 0) for state in stem.ORStatus)
for connection in connections:
states[connection.rsplit(None, 1)[-1]] += 1
for state, count in states.iteritems():
print('{}.value {}'.format(state.lower(), count))
except stem.connection.AuthenticationFailure as e:
print('Authentication failed ({})'.format(e))
class TorDormant(TorPlugin):
def __init__(self):
pass
def conf(self):
graph = {'title': 'Dormant',
'args': '-l 0 --base 1000',
'vlabel': 'dormant',
'category': 'Tor',
'info': 'Is Tor not building circuits because it is idle?'}
labels = {'dormant': {'label': 'dormant', 'min': 0, 'max': 1, 'type': 'GAUGE'}}
TorPlugin.conf_from_dict(graph, labels)
def fetch(self):
with gen_controller() as controller:
try:
controller.authenticate()
response = controller.get_info('dormant', None)
if response is None:
print("Error while reading dormant state from Tor daemon", file=sys.stderr)
sys.exit(-1)
print('dormant.value {}'.format(response))
except stem.connection.AuthenticationFailure as e:
print('Authentication failed ({})'.format(e))
class TorTraffic(TorPlugin):
def __init__(self):
pass
def conf(self):
graph = {'title': 'Traffic',
'args': '-l 0 --base 1024',
'vlabel': 'data',
'category': 'Tor',
'info': 'bytes read/written'}
labels = {'read': {'label': 'read', 'min': 0, 'type': 'DERIVE'},
'written': {'label': 'written', 'min': 0, 'type': 'DERIVE'}}
TorPlugin.conf_from_dict(graph, labels)
def fetch(self):
with gen_controller() as controller:
try:
authenticate(controller)
except stem.connection.AuthenticationFailure as e:
print('Authentication failed ({})'.format(e))
return
response = controller.get_info('traffic/read', None)
if response is None:
print("Error while reading traffic/read from Tor daemon", file=sys.stderr)
sys.exit(-1)
print('read.value {}'.format(response))
response = controller.get_info('traffic/written', None)
if response is None:
print("Error while reading traffic/write from Tor daemon", file=sys.stderr)
sys.exit(-1)
print('written.value {}'.format(response))
class TorBandwidth(TorPlugin):
def __init__(self):
pass
def conf(self):
graph = {'title': 'Observed bandwidth',
'args': '-l 0 --base 1000',
'vlabel': 'bytes/s',
'category': 'Tor',
'info': 'estimated capacity based on usage in bytes/s'}
labels = {'bandwidth': {'label': 'bandwidth', 'min': 0, 'type': 'GAUGE'}}
TorPlugin.conf_from_dict(graph, labels)
def fetch(self):
with gen_controller() as controller:
try:
authenticate(controller)
except stem.connection.AuthenticationFailure as e:
print('Authentication failed ({})'.format(e))
return
# Get fingerprint of our own relay to look up the descriptor for.
# In Stem 1.3.0 and later, get_server_descriptor() will fetch the
# relay's own descriptor if no argument is provided, so this will
# no longer be needed.
fingerprint = controller.get_info('fingerprint', None)
if fingerprint is None:
print("Error while reading fingerprint from Tor daemon", file=sys.stderr)
sys.exit(-1)
response = controller.get_server_descriptor(fingerprint, None)
if response is None:
print("Error while getting server descriptor from Tor daemon", file=sys.stderr)
sys.exit(-1)
print('bandwidth.value {}'.format(response.observed_bandwidth))
class TorFlags(TorPlugin):
def __init__(self):
pass
def conf(self):
graph = {'title': 'Relay flags',
'args': '-l 0 --base 1000',
'vlabel': 'flags',
'category': 'Tor',
'info': 'Flags active for relay'}
labels = {flag: {'label': flag, 'min': 0, 'max': 1, 'type': 'GAUGE'} for flag in stem.Flag}
TorPlugin.conf_from_dict(graph, labels)
def fetch(self):
with gen_controller() as controller:
try:
authenticate(controller)
except stem.connection.AuthenticationFailure as e:
print('Authentication failed ({})'.format(e))
return
# Get fingerprint of our own relay to look up the status entry for.
# In Stem 1.3.0 and later, get_network_status() will fetch the
# relay's own status entry if no argument is provided, so this will
# no longer be needed.
fingerprint = controller.get_info('fingerprint', None)
if fingerprint is None:
print("Error while reading fingerprint from Tor daemon", file=sys.stderr)
sys.exit(-1)
response = controller.get_network_status(fingerprint, None)
if response is None:
print("Error while getting server descriptor from Tor daemon", file=sys.stderr)
sys.exit(-1)
for flag in stem.Flag:
if flag in response.flags:
print('{}.value 1'.format(flag))
else:
print('{}.value 0'.format(flag))
def main():
if len(sys.argv) > 1:
param = sys.argv[1].lower()
else:
param = 'fetch'
if param == 'autoconf':
TorPlugin.autoconf()
sys.exit()
elif param == 'suggest':
TorPlugin.suggest()
sys.exit()
else:
# detect data provider
if __file__.endswith('_connections'):
provider = TorConnections()
elif __file__.endswith('_dormant'):
provider = TorDormant()
elif __file__.endswith('_traffic'):
provider = TorTraffic()
elif __file__.endswith('_countries'):
provider = circuits_by_country.TorCountries()
elif __file__.endswith('_bandwidth'):
provider = TorBandwidth()
elif __file__.endswith('_flags'):
provider = TorFlags()
else:
print('Unknown plugin name, try "suggest" for a list of possible ones.')
sys.exit()
if param == 'config':
provider.conf()
elif param == 'fetch':
provider.fetch()
else:
print('Unknown parameter "{}"'.format(param))
if __name__ == '__main__':
main()