-
Notifications
You must be signed in to change notification settings - Fork 10
/
bitwarden.py
315 lines (265 loc) · 9.05 KB
/
bitwarden.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
import subprocess
import os
from datetime import datetime, timedelta
import json
from json import JSONDecodeError
class BitwardenCliNotFoundError(Exception):
pass
class BitwardenCliError(Exception):
""" Contains error message returned by bitwarden-cli """
def __init__(self, message):
self.message = message
class BitwardenVaultLockedError(BitwardenCliError):
def __init__(self, message):
self.message = message
class BitwardenClient:
""" Wrapper around bitwarden-cli """
def __init__(self):
self.cli = "bw"
self.init_done = False
self.path = None
self.path_checked = False
self.server = None
self.email = None
self.session = None
self.folders = None
self.mfa_enabled = None
self.passphrase_expires_at = None
self.inactivity_lock_timeout = 0
self.session_store_cmd = ""
def initialize(self, server, email, mfa_enabled, inactivity_lock_timeout, session_store_cmd):
"""
Check that
- we can call the CLI
Don't call more than once.
"""
self.server = server
self.email = email
self.mfa_enabled = mfa_enabled
self.inactivity_lock_timeout = inactivity_lock_timeout
self.session_store_cmd = session_store_cmd
if not self.init_done:
self.configure_server()
if self.can_execute_cli():
self.init_done = True
else:
raise BitwardenCliNotFoundError()
if self.inactivity_lock_timeout and self.passphrase_expires_at is not None:
if datetime.now() > self.passphrase_expires_at:
self.lock()
def change_server_url(self, new_server_url):
"""
Change the path to the database file and lock the database.
"""
self.logout()
self.server = new_server_url
self.passphrase_expires_at = None
self.configure_server()
def change_email(self, new_email):
"""
Change the path to the database file and lock the database.
"""
self.logout()
self.email = new_email
self.passphrase_expires_at = None
def change_inactivity_lock_timeout(self, secs):
"""
Change the inactivity lock timeout and immediately lock the database.
"""
self.inactivity_lock_timeout = secs
self.passphrase_expires_at = None
def change_session_store_cmd(self, cmd):
"""
Change the inactivity lock timeout and immediately lock the database.
"""
self.session_store_cmd = cmd
def configure_server(self):
self.run_cli_session("config", "server", self.server)
def need_login(self):
try:
(err, out) = self.run_cli_session("login", "--check")
return self.handle_unlock_result(err, out)
except BitwardenVaultLockedError:
return True
def need_mfa(self):
return self.mfa_enabled
def need_unlock(self):
if not self.has_session():
return True
(err, out) = self.run_cli_session("unlock", "--check")
return self.handle_unlock_result(err, out)
def has_session(self):
return self.session is not None
@staticmethod
def handle_unlock_result(err, out):
if out:
try:
result = out["success"] is False
return result
except JSONDecodeError:
raise BitwardenCliError(err)
else:
return False
def verify_and_set_passphrase(self, pp, mfa):
success = False
if self.need_login():
success = self.login(pp, mfa)
elif self.need_unlock():
success = self.unlock(pp)
if success:
self.run_cli_store_session()
self.list_folders()
return success
def login(self, pp, mfa):
args = ["login", self.email, "--raw"]
if self.mfa_enabled and mfa:
args.append("--code")
args.append(mfa)
(err, out) = self.run_cli_pp(pp, *args)
if out:
self.session = out
return True
else:
self.session = None
return False
def logout(self):
self.session = None
(err, out) = self.run_cli_session("logout")
if err:
raise BitwardenCliError(err)
def unlock(self, pp):
(err, out) = self.run_cli_pp(pp, "unlock", "--raw")
if out:
self.session = out
return True
else:
self.session = None
return False
def lock(self):
self.session = None
(err, out) = self.run_cli_session("lock")
if err:
raise BitwardenCliError(err)
else:
return True
def sync(self):
(err, out) = self.run_cli_session("sync")
if err:
raise BitwardenCliError(err)
else:
self.list_folders()
return True
def list_folders(self):
(err, out) = self.run_cli_session("list", "folders")
if err:
self.folders = None
return False
else:
self.folders = dict()
for item in out["data"]["data"]:
self.folders[item["id"]] = item["name"]
return True
def get_folder(self, folder_id):
if folder_id in self.folders:
return self.folders[folder_id]
else:
return ""
def search(self, query):
if len(query) < 2:
return []
(err, out) = self.run_cli_session("list", "items", "--search", query)
if err:
raise BitwardenCliError(err)
else:
return out["data"]["data"]
def get_entry_details(self, entry):
attrs = dict()
(err, out) = self.run_cli_session("get", "item", entry)
if err:
raise BitwardenCliError(err)
else:
data = out["data"]
login = data["login"]
if "fields" in data:
attrs["fields"] = data["fields"]
attrs["username"] = login["username"]
attrs["password"] = login["password"]
if "uris" in login:
uris = login["uris"]
attrs["uri"] = uris[0]["uri"] if uris else ""
if "totp" in login and login["totp"]:
(err, out) = self.run_cli_session("get", "totp", entry)
attrs["totp"] = out["data"]["data"]
return attrs
def can_execute_cli(self):
try:
subprocess.run([self.cli], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return True
except FileNotFoundError:
return False
def get_bw_version(self):
try:
cp = subprocess.run(
[self.cli, "--version"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
except FileNotFoundError:
raise BitwardenCliNotFoundError()
out = cp.stdout.decode("utf-8")
return str(out).strip()
def run_cli_session(self, *args):
env_vars = os.environ.copy()
if self.session:
env_vars["BW_SESSION"] = self.session
try:
cp = subprocess.run(
[self.cli, *args, "--response"],
env=env_vars,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
except FileNotFoundError:
raise BitwardenCliNotFoundError()
if self.inactivity_lock_timeout:
self.passphrase_expires_at = datetime.now() + timedelta(
seconds=self.inactivity_lock_timeout
)
err = cp.stderr.decode("utf-8")
out = cp.stdout.decode("utf-8")
err_json = None
out_json = None
if out:
out_json = json.loads(out)
if not out_json["success"] and out_json["message"] == "You are not logged in.":
raise BitwardenVaultLockedError(out_json["message"])
return err_json, out_json
def run_cli_pp(self, passphrase, *args):
try:
cp = subprocess.run(
[self.cli, *args],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
input=bytes(passphrase, "utf-8"),
)
except FileNotFoundError:
raise BitwardenCliNotFoundError()
if self.inactivity_lock_timeout:
self.passphrase_expires_at = datetime.now() + timedelta(
seconds=self.inactivity_lock_timeout
)
return cp.stderr.decode("utf-8"), cp.stdout.decode("utf-8")
def run_cli_store_session(self):
if self.session_store_cmd == '':
return
try:
cp = subprocess.run(
[self.session_store_cmd],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
input=bytes(self.session, "utf-8"),
)
except FileNotFoundError:
raise BitwardenCliNotFoundError()
except Exception as e:
raise BitwardenCliError(e)