This repository has been archived by the owner on Aug 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
qute_1pass.py
executable file
·381 lines (310 loc) · 11.6 KB
/
qute_1pass.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
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
#!/usr/bin/env python3
import os
import sys
import json
import logging
import argparse
import tempfile
import subprocess
from datetime import datetime, timedelta
from urllib.parse import urlsplit
logger = logging.getLogger("qute_1pass")
CACHE_DIR = os.path.join(tempfile.gettempdir(), "qute_1pass")
os.makedirs(CACHE_DIR, exist_ok=True)
os.chmod(CACHE_DIR, 0o750)
SESSION_PATH = os.path.join(CACHE_DIR, "session")
SESSION_DURATION = timedelta(minutes=30)
LAST_ITEM_PATH = os.path.join(CACHE_DIR, "last_item")
LAST_ITEM_DURATION = timedelta(seconds=10)
CMD_PASSWORD_PROMPT = [
"rofi", "-password", "-dmenu", "-p", "Vault Password", "-l", "0", "-sidebar", "-width", "20"
]
CMD_LIST_PROMPT = ["rofi", "-dmenu"]
CMD_ITEM_SELECT = CMD_LIST_PROMPT + ["-p", "Select login"]
CMD_OP_CHECK_LOGIN = ["op", "whoami"]
CMD_OP_LOGIN = ["op", "signin", "--raw"]
CMD_OP_LIST_ITEMS = "op item list --categories Login --session {session_id} --format=json"
CMD_OP_GET_ITEM = "op item get --session {session_id} {uuid} --format=json"
CMD_OP_GET_TOTP = "op item get --otp --session {session_id} {uuid}"
QUTE_FIFO = os.environ["QUTE_FIFO"]
parser = argparse.ArgumentParser()
parser.add_argument(
"command", help="fill_credentials, fill_totp, fill_username, fill_password"
)
parser.add_argument(
"--auto-submit", help="Auto submit after filling", action="store_true"
)
parser.add_argument(
"--cache-session",
help="Cache 1password session for 30 minutes",
action="store_true",
)
parser.add_argument(
"--allow-insecure-sites",
help="Allow filling credentials on insecure sites",
action="store_true",
)
parser.add_argument(
"--cache",
help="store and use cached information",
action="store_true",
)
parser.add_argument(
"--biometric",
help="Use biometric unlock - don't ask for password",
action="store_true",
)
class Qute:
"""Logic related to qutebrowser"""
@classmethod
def _command(cls, command, *args):
with open(QUTE_FIFO, "w") as fifo:
logger.info(f"{command} {' '.join(args)}")
fifo.write(f"{command} {' '.join(args)}\n")
fifo.flush()
@classmethod
def _message(cls, message, type="error"):
cls._command(f"message-{type}", f"'qute-1password: {message}'")
@classmethod
def message_error(cls, message):
cls._message(message)
@classmethod
def message_warning(cls, message):
cls._message(message, type="warning")
@classmethod
def fake_key(cls, key):
key = key.replace(" ", "<Space>")
cls._command("fake-key", key)
@classmethod
def fill_credentials_tabmode(cls, username, password, submit=False):
cls.fake_key(username)
cls.fake_key("<TAB>")
cls.fake_key(password)
if submit:
cls.fake_key("<Return>")
@classmethod
def fill_single_field_tabmode(cls, value, submit=False):
cls.fake_key(value)
if submit:
cls.fake_key("<Return>")
@classmethod
def fill_totp(cls, totp, submit=True):
cls.fake_key(totp)
if submit:
cls.fake_key("<Return>")
class ExecuteError(Exception):
"""Used when commands executed return code is not 0"""
pass
def execute_command(command):
"""Executes a command, mainly used to launch commands for user input and the op cli"""
result = subprocess.run(command, capture_output=True, encoding="utf-8")
if result.returncode != 0:
logger.error(result.stderr)
raise ExecuteError(result.stderr)
return result.stdout.strip()
def pipe_commands(cmd1, cmd2):
p1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE)
p2 = subprocess.Popen(cmd2, stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()
return p2.communicate()[0].decode("utf-8").strip()
def extract_host(url):
"""Extracts the host from a given URL"""
_, host, *_ = urlsplit(url)
return host
class OnePass:
"""Logic related to the op command and parsing results"""
@classmethod
def login(cls):
if arguments.biometric:
try:
execute_command(CMD_OP_CHECK_LOGIN)
except ExecuteError:
try:
execute_command(CMD_OP_LOGIN)
except ExecuteError:
Qute.message_error("Login error")
sys.exit(0)
return "0"
else:
try:
password = execute_command(CMD_PASSWORD_PROMPT)
except ExecuteError:
Qute.message_error("Error calling pinentry program")
sys.exit(0)
try:
session_id = pipe_commands(
["echo", "-n", password],
CMD_OP_LOGIN)
except ExecuteError:
Qute.message_error("Login error")
sys.exit(0)
if arguments.cache_session:
with open(SESSION_PATH, "w") as handler:
handler.write(session_id)
os.chmod(SESSION_PATH, 0o640)
return session_id
@classmethod
def get_session(cls):
"""
Returns a session for the op command to make calls with.
If a session is cached, we check if it's expired first to avoid any errors.
"""
if arguments.cache_session and os.path.isfile(SESSION_PATH):
# op sessions last 30 minutes, check if still valid
creation_time = datetime.fromtimestamp(os.stat(SESSION_PATH).st_ctime)
if (datetime.now() - creation_time) < SESSION_DURATION:
return open(SESSION_PATH, "r").read()
else:
# Session expired
os.unlink(SESSION_PATH)
return cls.login()
@classmethod
def list_items(cls):
session_id = cls.get_session()
result = execute_command(CMD_OP_LIST_ITEMS.format(session_id=session_id).split())
parsed = json.loads(result)
return parsed
@classmethod
def get_item(cls, uuid):
session_id = cls.get_session()
try:
result = execute_command(
CMD_OP_GET_ITEM.format(uuid=uuid, session_id=session_id).split()
)
except ExecuteError:
logger.error("Error retrieving credential", exc_info=True)
parsed = json.loads(result)
return parsed
@classmethod
def get_item_for_url(cls, url):
host = extract_host(url)
def filter_host(item):
"""Exclude items that does not match host on any configured URL"""
if "urls" in item:
return any(filter(lambda x: host in x["href"], item["urls"]))
return False
items = cls.list_items()
filtered = filter(filter_host, items)
mapping = {
f"{host}: {item['title']} ({item['id']})": item
for item in filtered
}
if not mapping:
raise cls.NoItemsFoundError(f"No items found for host {host}")
try:
credential = pipe_commands(
["echo", "\n".join(mapping.keys())], CMD_ITEM_SELECT
)
except ExecuteError:
pass
if not credential:
# Cancelled
return
return cls.get_item(mapping[credential]["id"])
@classmethod
def get_credentials(cls, item):
username = password = None
for field in item["fields"]:
if field.get("purpose") == "USERNAME":
username = field["value"]
if field.get("purpose") == "PASSWORD":
password = field["value"]
if username is None or password is None:
logger.warning(
"Present: username={username} password={password}".format(
username=username is not None, password=password is not None
)
)
Qute.message_warning("Filled incomplete credentials")
return {"username": username, "password": password}
@classmethod
def get_totp(cls, uuid):
session_id = cls.get_session()
try:
return execute_command(
CMD_OP_GET_TOTP.format(uuid=uuid, session_id=session_id).split()
)
except ExecuteError:
logger.error("Error retrieving TOTP", exc_info=True)
class NoItemsFoundError(Exception):
pass
class CLI:
def __init__(self, arguments):
self.arguments = arguments
def run(self):
command = self.arguments.command
if command != "run" and not command.startswith("_") and hasattr(self, command):
return getattr(self, command)()
def _get_item(self):
try:
item = OnePass.get_item_for_url(os.environ["QUTE_URL"])
except OnePass.NoItemsFoundError as error:
Qute.message_warning("No item found for this site")
logger.error(f"No item found for site: {os.environ['QUTE_URL']}")
logger.error(error)
sys.exit(0)
return item
def _store_last_item(self, item):
"""
Stores a reference to an item to easily get single information from it (password, TOTP)
right after filling the username or credentials.
"""
last_item = {"host": extract_host(os.environ["QUTE_URL"]), "id": item["id"]}
with open(LAST_ITEM_PATH, "w") as handler:
handler.write(json.dumps(last_item))
os.chmod(LAST_ITEM_PATH, 0o640)
def _fill_single_field(self, field):
item = self._get_item()
credentials = OnePass.get_credentials(item)
Qute.fill_single_field_tabmode(
credentials[field], submit=self.arguments.auto_submit
)
return item
def fill_username(self):
item = self._fill_single_field("username")
self._store_last_item(item)
def fill_password(self):
item = self._fill_single_field("password")
self._store_last_item(item)
def fill_credentials(self):
item = self._get_item()
credentials = OnePass.get_credentials(item)
Qute.fill_credentials_tabmode(
*credentials.values(), submit=self.arguments.auto_submit
)
self._store_last_item(item)
def fill_totp(self):
# Check last item first
# If theres a last_item file created in the last LAST_ITEM_DURATION seconds
# and the host matches the one the user is visiting, use that UUID to retrieve
# the totp
item = None
if os.path.isfile(LAST_ITEM_PATH):
creation_time = datetime.fromtimestamp(os.stat(LAST_ITEM_PATH).st_ctime)
if (datetime.now() - creation_time) < LAST_ITEM_DURATION:
last_item = json.loads(open(LAST_ITEM_PATH, "r").read())
if last_item["host"] == extract_host(os.environ["QUTE_URL"]):
item = last_item
if not item:
item = self._get_item()
totp = OnePass.get_totp(item["id"])
logger.error(totp)
Qute.fill_totp(totp)
if os.path.isfile(LAST_ITEM_PATH):
os.unlink(LAST_ITEM_PATH)
if __name__ == "__main__":
arguments = parser.parse_args()
if arguments.cache:
# add --cache to cacheable commands with
CMD_OP_LIST_ITEMS += " --cache"
CMD_OP_GET_ITEM += " --cache"
# Prevent filling credentials in non-secure sites if not explicitly allwoed
if not arguments.allow_insecure_sites:
if urlsplit(os.environ["QUTE_URL"])[0] != "https":
Qute.message_error(
"Trying to fill a non-secure site. If you want to allow it add the --allow-insecure-sites flag."
)
logger.error("Refusing to fill credentials on non-secure sites")
sys.exit(0)
cli = CLI(arguments)
sys.exit(cli.run())