summaryrefslogtreecommitdiff
path: root/misc/userscripts/qute-bitwarden
blob: f6212d35af675cb00ee00e46751e1de29b13799a (plain)
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
#!/usr/bin/env python3

# Copyright 2017 Chris Braun (cryzed) <cryzed@googlemail.com>
# Adapted for Bitwarden by Jonathan Haylett (JonnyHaystack) <jonathan@haylett.dev>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published bjy
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser 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 qutebrowser.  If not, see <http://www.gnu.org/licenses/>.

"""
Insert login information using Bitwarden CLI and a dmenu-compatible application
(e.g. dmenu, rofi -dmenu, ...).
"""

USAGE = """The domain of the site has to be in the name of the Bitwarden entry, for example: "github.com/cryzed" or
"websites/github.com".  The login information is inserted by emulating key events using qutebrowser's fake-key command in this manner:
[USERNAME]<Tab>[PASSWORD], which is compatible with almost all login forms.

You must log into Bitwarden CLI using `bw login` prior to use of this script.
The session key will be stored using keyctl for the number of seconds passed to
the --auto-lock option.

To use in qutebrowser, run: `spawn --userscript qute-bitwarden`
"""

EPILOG = """Dependencies: tldextract (Python 3 module), Bitwarden CLI (1.7.4 is
known to work but older versions may well also work)

WARNING: The login details are viewable as plaintext in qutebrowser's debug log
(qute://log) and might be shared if you decide to submit a crash report!"""

import argparse
import enum
import fnmatch
import functools
import os
import re
import shlex
import subprocess
import sys
import json
import tldextract

argument_parser = argparse.ArgumentParser(
    description=__doc__,
    usage=USAGE,
    epilog=EPILOG,
)
argument_parser.add_argument('url', nargs='?', default=os.getenv('QUTE_URL'))
argument_parser.add_argument('--dmenu-invocation', '-d', default='rofi -dmenu -i -p Bitwarden',
                             help='Invocation used to execute a dmenu-provider')
argument_parser.add_argument('--no-insert-mode', '-n', dest='insert_mode', action='store_false',
                             help="Don't automatically enter insert mode")
argument_parser.add_argument('--io-encoding', '-i', default='UTF-8',
                             help='Encoding used to communicate with subprocesses')
argument_parser.add_argument('--merge-candidates', '-m', action='store_true',
                             help='Merge pass candidates for fully-qualified and registered domain name')
argument_parser.add_argument('--auto-lock', type=int, default=900,
                             help='Automatically lock the vault after this many seconds')
group = argument_parser.add_mutually_exclusive_group()
group.add_argument('--username-only', '-e',
                   action='store_true', help='Only insert username')
group.add_argument('--password-only', '-w',
                   action='store_true', help='Only insert password')

stderr = functools.partial(print, file=sys.stderr)


class ExitCodes(enum.IntEnum):
    SUCCESS = 0
    FAILURE = 1
    # 1 is automatically used if Python throws an exception
    NO_PASS_CANDIDATES = 2
    COULD_NOT_MATCH_USERNAME = 3
    COULD_NOT_MATCH_PASSWORD = 4


def qute_command(command):
    with open(os.environ['QUTE_FIFO'], 'w') as fifo:
        fifo.write(command + '\n')
        fifo.flush()


def ask_password():
    process = subprocess.run([
        'rofi',
        '-dmenu',
        '-p',
        'Master Password',
        '-password',
        '-lines',
        '0',
    ], universal_newlines=True, stdout=subprocess.PIPE)
    if process.returncode > 0:
        raise Exception('Could not unlock vault')
    master_pass = process.stdout.strip()
    return subprocess.check_output(
        ['bw', 'unlock', '--raw', master_pass],
        universal_newlines=True,
    ).strip()


def get_session_key(auto_lock):
    if auto_lock == 0:
        subprocess.call(['keyctl', 'purge', 'user', 'bw_session'])
        return ask_password()
    else:
        process = subprocess.run(
            ['keyctl', 'request', 'user', 'bw_session'],
            universal_newlines=True,
            stdout=subprocess.PIPE,
        )
        key_id = process.stdout.strip()
        if process.returncode > 0:
            session = ask_password()
            if not session:
                raise Exception('Could not unlock vault')
            key_id = subprocess.check_output(
                ['keyctl', 'add', 'user', 'bw_session', session, '@u'],
                universal_newlines=True,
            ).strip()

        if auto_lock > 0:
            subprocess.call(['keyctl', 'timeout', str(key_id), str(auto_lock)])
        return subprocess.check_output(
            ['keyctl', 'pipe', str(key_id)],
            universal_newlines=True,
        ).strip()


def pass_(domain, encoding, auto_lock):
    session_key = get_session_key(auto_lock)
    process = subprocess.run(
        ['bw', 'list', 'items', '--session', session_key, '--url', domain],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )

    err = process.stderr.decode(encoding).strip()
    if err:
        msg = 'Bitwarden CLI returned for {:s} - {:s}'.format(domain, err)
        stderr(msg)
        return '[]'

    out = process.stdout.decode(encoding).strip()

    return out


def dmenu(items, invocation, encoding):
    command = shlex.split(invocation)
    process = subprocess.run(command, input='\n'.join(
        items).encode(encoding), stdout=subprocess.PIPE)
    return process.stdout.decode(encoding).strip()


def fake_key_raw(text):
    for character in text:
        # Escape all characters by default, space requires special handling
        sequence = '" "' if character == ' ' else '\{}'.format(character)
        qute_command('fake-key {}'.format(sequence))


def main(arguments):
    if not arguments.url:
        argument_parser.print_help()
        return ExitCodes.FAILURE

    extract_result = tldextract.extract(arguments.url)

    # Try to find candidates using targets in the following order: fully-qualified domain name (includes subdomains),
    # the registered domain name and finally: the IPv4 address if that's what
    # the URL represents
    candidates = []
    for target in filter(None, [
                extract_result.fqdn,
                extract_result.registered_domain,
                extract_result.subdomain + extract_result.domain,
                extract_result.domain,
                extract_result.ipv4]):
        target_candidates = json.loads(
            pass_(
                target,
                arguments.io_encoding,
                arguments.auto_lock,
            )
        )
        if not target_candidates:
            continue

        candidates = candidates + target_candidates
        if not arguments.merge_candidates:
            break
    else:
        if not candidates:
            stderr('No pass candidates for URL {!r} found!'.format(
                arguments.url))
            return ExitCodes.NO_PASS_CANDIDATES

    if len(candidates) == 1:
        selection = candidates.pop()
    else:
        choices = ['{:s} | {:s}'.format(c['name'], c['login']['username']) for c in candidates]
        choice = dmenu(choices, arguments.dmenu_invocation, arguments.io_encoding)
        choice_tokens = choice.split('|')
        choice_name = choice_tokens[0].strip()
        choice_username = choice_tokens[1].strip()
        selection = next((c for (i, c) in enumerate(candidates)
                          if c['name'] == choice_name
                          and c['login']['username'] == choice_username),
                         None)

    # Nothing was selected, simply return
    if not selection:
        return ExitCodes.SUCCESS

    username = selection['login']['username']
    password = selection['login']['password']

    if arguments.username_only:
        fake_key_raw(username)
    elif arguments.password_only:
        fake_key_raw(password)
    else:
        # Enter username and password using fake-key and <Tab> (which seems to work almost universally), then switch
        # back into insert-mode, so the form can be directly submitted by
        # hitting enter afterwards
        fake_key_raw(username)
        qute_command('fake-key <Tab>')
        fake_key_raw(password)

    if arguments.insert_mode:
        qute_command('enter-mode insert')

    return ExitCodes.SUCCESS


if __name__ == '__main__':
    arguments = argument_parser.parse_args()
    sys.exit(main(arguments))