-
Notifications
You must be signed in to change notification settings - Fork 0
/
otp.py
executable file
·211 lines (175 loc) · 7.62 KB
/
otp.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
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
#!/bin/env python3
import sys
import base64
import hmac
import time
import struct
import shutil
import subprocess
from gi.repository import Gio, GLib
# The hotp and totp functions are from https://github.com/susam/mintotp by Susam Pal, licensed under the MIT License.
# Modifications have been made to the original code.
# License text:
# The MIT License (MIT)
# =====================
#
# Copyright (c) 2019 Susam Pal
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
def hotp(key, counter, digits=6):
key = base64.b32decode(key.upper() + '=' * ((8 - len(key)) % 8))
counter = struct.pack('>Q', counter)
mac = hmac.new(key, counter, 'sha1').digest()
offset = mac[-1] & 0x0f
binary = struct.unpack('>L', mac[offset:offset + 4])[0] & 0x7fffffff
return str(binary)[-digits:].zfill(digits)
def totp(key):
return hotp(key, int(time.time() / 30))
def copy_text(text):
try:
proxy = Gio.DBusProxy.new_for_bus_sync(Gio.BusType.SESSION, Gio.DBusProxyFlags.DO_NOT_CONNECT_SIGNALS, None, 'org.kde.klipper', '/klipper', 'org.kde.klipper.klipper', None)
proxy.setClipboardContents('(s)', text)
except GLib.Error:
if shutil.which('wl-copy'):
subprocess.run(['wl-copy', text])
elif shutil.which('xclip'):
process = subprocess.Popen(['xclip', '-selection', 'clipboard'], stdin=subprocess.PIPE, text=True)
try:
process.communicate(input=text, timeout=10)
except subprocess.TimeoutExpired:
pass
process.terminate()
class KWallet:
def __init__(self, app_id):
self._proxy = Gio.DBusProxy.new_for_bus_sync(Gio.BusType.SESSION, Gio.DBusProxyFlags.DO_NOT_CONNECT_SIGNALS, None, 'org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet', None)
self._app_id = app_id
self._handle = 0
def open(self):
if self._handle <= 0:
self._handle = self._proxy.open('(sxs)', 'kdewallet', 0, self._app_id)
if self._handle <= 0:
raise RuntimeError('Open failed')
def read_password(self, folder, key):
return self._proxy.readPassword('(isss)', self._handle, folder, key, self._app_id)
def write_password(self, folder, key, value):
return self._proxy.writePassword('(issss)', self._handle, folder, key, value, self._app_id) == 0
def create_folder(self, folder):
return self._proxy.createFolder('(iss)', self._handle, folder, self._app_id)
def close(self):
if self._handle > 0:
self._proxy.close('(ibs)', self._handle, False, self._app_id)
self._handle = 0
class OTPApplication(Gio.Application):
def __init__(self, **kwargs):
super().__init__(**kwargs, flags=Gio.ApplicationFlags.ALLOW_REPLACEMENT | Gio.ApplicationFlags.REPLACE, inactivity_timeout=120 * 1000)
self._registration_id = None
self._wallet = KWallet(self.get_application_id())
self._wallet.open()
self._value = None
def _on_method_call(self, connection, sender, object_path, interface_name, method_name, parameters, invocation):
func = getattr(self, method_name)
args = parameters.unpack()
result = func(*args)
if result is None:
result = ()
else:
result = (result,)
outargs = ''.join(arg.signature for arg in invocation.get_method_info().out_args)
invocation.return_value(GLib.Variant(f'({outargs})', result))
def _read_otp_key(self, name):
return self._wallet.read_password('OTP Keys', name)
def _write_otp_key(self, name, key):
self._wallet.create_folder('OTP Keys')
self._wallet.write_password('OTP Keys', name, key)
def do_local_command_line(self, arguments):
if len(arguments) == 1:
return Gio.Application.do_local_command_line(self, arguments)
elif len(arguments) == 2:
key = self._read_otp_key(arguments[1])
if key:
print(totp(key))
return (True, [], 0)
else:
return (True, [], 1)
elif len(arguments) == 3:
self._write_otp_key(arguments[1], arguments[2])
return (True, [], 0)
else:
return (True, [], 1)
def do_dbus_register(self, connection, object_path):
introspection_xml = '''
<node>
<interface name="org.kde.krunner1">
<method name="Match">
<arg name="query" type="s" direction="in" />
<arg name="matches" type="a(sssida{sv})" direction="out" />
</method>
<method name="Actions">
<arg name="matches" type="a(sss)" direction="out" />
</method>
<method name="Run">
<arg name="matchId" type="s" direction="in" />
<arg name="actionId" type="s" direction="in" />
</method>
</interface>
</node>
'''
interface_info = Gio.DBusNodeInfo.new_for_xml(introspection_xml).interfaces[0]
self._registration_id = connection.register_object('/otp', interface_info, self._on_method_call)
return Gio.Application.do_dbus_register(self, connection, object_path)
def do_dbus_unregister(self, connection, object_path):
Gio.Application.do_dbus_unregister(self, connection, object_path)
if self._registration_id:
connection.unregister_object(self._registration_id)
def do_activate(self):
self.hold()
self.release()
def do_shutdown(self):
Gio.Application.do_shutdown(self)
self._wallet.close()
def Match(self, query):
self.do_activate()
args = query.split()
if args[0] != 'otp':
return []
unknown_result = [('', '- - - - - -', 'otp', 100, 1.0, {})]
if len(args) == 2:
key = self._read_otp_key(args[1])
if key:
self._value = totp(key)
return [('copy', self._value, 'otp', 100, 1.0, {})]
else:
return unknown_result
if len(args) == 3:
self._value = (args[1], args[2])
return [('write', 'Press enter to store the key', 'otp', 100, 1.0, {})]
else:
return unknown_result
def Actions(self):
return []
def Run(self, match_id, action_id):
if match_id == 'copy':
copy_text(self._value)
elif match_id == 'write':
self._write_otp_key(*self._value)
def main():
app = OTPApplication(application_id='com.github.otp')
sys.exit(app.run(sys.argv))
main()