-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authy_helper.py
152 lines (140 loc) · 6.24 KB
/
authy_helper.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
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright © 2019 Zing Lau (zinglau2015@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see
# <http://www.gnu.org/licenses/>.
#
from threading import activeCount, current_thread, Thread
try:
from polling import poll, TimeoutException
except ImportError as e:
raise SystemExit('Please install python3-pip and run "pip3 install polling" first!')
from time import sleep
from settings import *
try:
from authy.api import AuthyApiClient
except ImportError as e:
raise SystemExit('Please install python3-pip and run "pip3 install authy" first!')
import logging
logger = logging.getLogger()
class AuthyHelper(object):
def __init__(self, bus, busname):
self.handledSignals = ['NeedApproval']
if MANAGE_ENABLE_DISABLE:
self.handledSignals.append('PropertyChanged')
self._authy_api = AuthyApiClient(TWILLO_AUTHY_API_KEY)
self._clients = {}
def _check_response(self, uuid, client):
logger.debug('Latest thread for client {} is {}'.format(client, self._clients[client]))
thread_id = current_thread().ident
if self._clients[client] != thread_id:
return 'outdated'
status_response = self._authy_api.one_touch.get_approval_status(uuid)
if status_response.ok():
# one of 'pending', 'approved', 'denied', or 'expired'
approval_status = status_response.content['approval_request']['status']
if approval_status != 'pending':
return approval_status
else:
logger.error(status_response.errors())
return 'continue'
def _run(self, signal, path, args, properties, proxy):
# UGLY HACK: wait so main thread has time to store our thread id
sleep(1)
thread_id = current_thread().ident
current_thread().name = current_thread().name + ' ' + str(thread_id)
logger.info("Authy helper child thread starts processing signal: {} on {}".format(signal, path))
for arg in args:
logger.debug(' ' + str(arg))
client = path[9:]
if signal == "PropertyChanged" and args[0] == "Enabled":
client_info = "{} ({}) on {}".format(str(properties['Name']), str(properties['Host']), MANDOS_SERVER_NAME)
enabled = args[1]
logger.debug("Status change of {} : {}".format(client_info, 'Enabled' if enabled else 'Disabled'))
request = self._authy_api.one_touch.send_request(
AUTHY_USER_ID,
"Client {} has just been {}".format(client_info, 'ENABLED!' if enabled else 'DISABLED!')
)
if request.ok():
uuid = request.get_uuid()
try:
status = poll(lambda: self._check_response(uuid, client),
check_success=lambda s: s != 'continue',
step=AUTHY_POLL_INTERVAL,
timeout=30
)
except TimeoutException:
logger.info("Timeout. Doing nothing")
return
logger.debug(status)
if self._clients[client] == thread_id:
logger.info('Authy helper child thread received request result: ' + status)
if status == 'denied':
proxy.Disable() if enabled else proxy.Enable()
else:
logger.error(request.errors())
return
client_address = None
if len(args) == 3:
milliseconds_to_expire, default, client_address = args
else:
milliseconds_to_expire, default = args
seconds_to_expire = int(milliseconds_to_expire / 1000)
details = {
'Client': str(properties['Name']),
'Host': str(properties['Host']),
'Connecting from': str(client_address),
'Default response': ('Approved' if default == 1 else 'Denied'),
'Timeout (seconds)': str(seconds_to_expire)
}
logger.debug(details)
request = self._authy_api.one_touch.send_request(
AUTHY_USER_ID,
"Boot request approval required on {}:".format(MANDOS_SERVER_NAME),
seconds_to_expire=seconds_to_expire,
details=details,
)
if request.ok():
uuid = request.get_uuid()
status = poll(
lambda: self._check_response(uuid, client),
check_success=lambda s: s != 'continue',
step=AUTHY_POLL_INTERVAL,
timeout=seconds_to_expire
)
logger.info(status)
if self._clients[client] == thread_id:
logger.info('Authy helper child thread received request result: ' + status)
if status == 'approved':
proxy.Approve(True)
elif status == 'denied':
proxy.Approve(False)
if DISABLE_IF_DENIED:
proxy.Disable()
else:
logger.error(request.errors())
def process(self, signal, path, args, properties, proxy):
logger.debug("Authy helper starts processing signal: {} on {}".format(signal, path))
for arg in args: logger.debug(' ' + str(arg))
client = path[9:]
if signal == "PropertyChanged" and args[0] != "Enabled":
logger.debug("Ignored")
return
t = Thread(name=client, target=self._run, args=(signal, path, args, properties, proxy))
t.setDaemon(True)
t.start()
self._clients[client] = t.ident
def stop(self):
pass