forked from thinkst/canarytokens
-
Notifications
You must be signed in to change notification settings - Fork 1
/
switchboard.py
79 lines (61 loc) · 2.97 KB
/
switchboard.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
"""
Class that receives alerts, and dispatches them to the registered endpoint.
"""
from twisted.logger import Logger
log = Logger()
from exception import DuplicateChannel, InvalidChannel
class Switchboard(object):
def __init__(self,):
"""Return a new Switchboard instance."""
self.input_channels = {}
self.output_channels = {}
log.info('Canarytokens switchboard started')
def add_input_channel(self, name=None, channel=None):
"""Register a new input channel with the switchboard.
Arguments:
name -- unique name for the input channel
formatters -- a dict in the form { TYPE: METHOD,...} used to lookup
the channel's format method depending on the alert type
"""
if self.input_channels.has_key(name):
raise DuplicateChannel()
self.input_channels[name] = channel
def add_output_channel(self, name=None, channel=None):
"""Register a new output channel with the switchboard.
Arguments:
name -- unique name for the input channel
formatters -- a dict in the form { TYPE: METHOD,...} used to lookup
the channel's format method depending on the alert type
"""
if self.output_channels.has_key(name):
raise DuplicateChannel()
self.output_channels[name] = channel
def dispatch(self, input_channel=None, canarydrop=None, **kwargs):
"""Calls the correct alerting method for the trigger and channel combination.
For now it prints to stdout.
TODO: this spawns threads to actually do the alerting
Arguments:
input_channel -- name of the channel on which the alert originated
canarydrop -- a Canarydrop instance
**kwargs -- passed to the channel instance's formatter methods
"""
try:
if not self.input_channels.has_key(input_channel):
raise InvalidChannel()
canarydrop.add_canarydrop_hit(input_channel=input_channel, **kwargs)
if not canarydrop.alertable():
log.warn('Token {token} is not alertable at this stage.'\
.format(token=canarydrop.canarytoken.value()))
return
#update accounting info
canarydrop.alerting(input_channel=input_channel,**kwargs)
for requested_output_channel in canarydrop.get_requested_output_channels():
try:
output_channel = self.output_channels[requested_output_channel]
output_channel.send_alert(canarydrop=canarydrop,
input_channel=self.input_channels[input_channel],
**kwargs)
except KeyError as e:
raise Exception('Error sending alert: {err}'.format(err=e.message))
except Exception as e:
log.error('Exception occurred in switchboard dispatch: {err}'.format(err=e))