forked from firecat53/keepmenu
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeepmenu.py
More file actions
executable file
·1647 lines (1412 loc) · 52.3 KB
/
keepmenu.py
File metadata and controls
executable file
·1647 lines (1412 loc) · 52.3 KB
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# encoding:utf8
"""Read and copy Keepass database entries using dmenu or rofi
"""
import configparser
import argparse
import logging
from functools import partial
from contextlib import closing
from enum import Enum
import errno
import re
import itertools
import locale
from multiprocessing import Event, Process, Queue
from multiprocessing.managers import BaseManager
import os
from os.path import exists, expanduser
import random
import shlex
import socket
import string
import sys
from subprocess import call, Popen, PIPE
import tempfile
from threading import Timer
import time
import re
import webbrowser
import construct
from pynput import keyboard
from pykeepass import PyKeePass
from systemd import journal
LOG = logging.getLogger(__name__)
LOG.addHandler(journal.JournalHandler(SYSLOG_IDENTIFIER='keepmenu'))
logging.basicConfig(level=logging.INFO)
try:
# secrets only available python 3.6+
from secrets import choice
except ImportError:
def choice(seq):
"""Provide `choice` function call for pw generation
"""
return random.SystemRandom().choice(seq)
AUTH_FILE = expanduser("~/.cache/.keepmenu-auth")
CONF_FILE = expanduser("~/.config/keepmenu/config.ini")
class MenuOption(Enum):
ViewEntry = 0
Edit = 1
Add = 2
ManageGroups = 3
ReloadDB = 4
KillDaemon = 5
TypePassword = 6
TypeEntry = 7
TypeUsername = 8
TypePrevUsername = 9
TypePrevPassword = 10
ShowPrevEntry = 11
def description(self):
return {
self.TypePassword:'Type password',
self.ViewEntry:'View Individual entry',
self.Edit:'Edit entries',
self.Add:'Add entry',
self.ManageGroups:'Manage groups',
self.TypeUsername:'Type username',
self.ReloadDB:'Reload database',
self.KillDaemon:'Kill Keepmenu daemon',
self.TypeEntry:'Select entry to autotype',
}.get(self)
def find_free_port():
"""Find random free port to use for BaseManager server
Returns: int Port
"""
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
sock.bind(('127.0.0.1', 0)) # pylint:disable=no-member
return sock.getsockname()[1] # pylint:disable=no-member
def random_str():
"""Generate random auth string for BaseManager
Returns: string
"""
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(15))
def gen_passwd(chars, length=20):
"""Generate password (min = # of distinct character sets picked)
Args: chars - Dict {preset_name_1: {char_set_1: string, char_set_2: string},
preset_name_2: ....}
length - int (default 20)
Returns: password - string OR False
"""
sets = set()
if chars:
sets = set(j for i in chars.values() for j in i.values())
if length < len(sets) or not chars:
return False
alphabet = "".join(set("".join(j for j in i.values()) for i in chars.values()))
# Ensure minimum of one char from each character set
password = "".join(choice(k) for k in sets)
password += "".join(choice(alphabet) for i in range(length - len(sets)))
tpw = list(password)
random.shuffle(tpw)
return "".join(tpw)
def process_config():
"""Set global variables. Read the config file. Create default config file if
one doesn't exist.
"""
# pragma pylint: disable=global-variable-undefined
global CACHE_PERIOD_MIN, \
CACHE_PERIOD_DEFAULT_MIN, \
CONF, \
DMENU_LEN, \
ENV, \
ENC, \
SEQUENCE
# pragma pylint: enable=global-variable-undefined
ENV = os.environ.copy()
ENV['LC_ALL'] = 'C'
ENC = locale.getpreferredencoding()
CACHE_PERIOD_DEFAULT_MIN = 360
SEQUENCE = "{USERNAME}{TAB}{PASSWORD}{ENTER}"
CONF = configparser.ConfigParser()
if not exists(CONF_FILE):
try:
os.mkdir(os.path.dirname(CONF_FILE))
except OSError:
pass
with open(CONF_FILE, 'w') as conf_file:
CONF.add_section('dmenu')
CONF.set('dmenu', 'dmenu_command', 'dmenu')
CONF.add_section('dmenu_passphrase')
CONF.set('dmenu_passphrase', 'nf', '#222222')
CONF.set('dmenu_passphrase', 'nb', '#222222')
CONF.set('dmenu_passphrase', 'rofi_obscure', 'True')
CONF.add_section('database')
CONF.set('database', 'database_1', '')
CONF.set('database', 'keyfile_1', '')
CONF.set('database', 'pw_cache_period_min', str(CACHE_PERIOD_DEFAULT_MIN))
CONF.set('database', 'autotype_default', SEQUENCE)
CONF.write(conf_file)
try:
CONF.read(CONF_FILE)
except configparser.ParsingError as err:
dmenu_err("Config file error: {}".format(err))
sys.exit()
if CONF.has_option("database", "pw_cache_period_min"):
CACHE_PERIOD_MIN = int(CONF.get("database", "pw_cache_period_min"))
else:
CACHE_PERIOD_MIN = CACHE_PERIOD_DEFAULT_MIN
if CONF.has_option("dmenu", "l"):
DMENU_LEN = int(CONF.get("dmenu", "l"))
else:
DMENU_LEN = 24
if CONF.has_option('database', 'autotype_default'):
SEQUENCE = CONF.get("database", "autotype_default")
if CONF.has_option("database", "type_library"):
if CONF.get("database", "type_library") == "xdotool":
try:
call(['xdotool', 'version'])
except OSError:
dmenu_err("Xdotool not installed.\n"
"Please install or remove that option from config.ini")
sys.exit()
elif CONF.get("database", "type_library") == "ydotool":
try:
call(['ydotool'])
except OSError:
dmenu_err("Ydotool not installed.\n"
"Please install or remove that option from config.ini")
sys.exit()
def get_auth():
"""Generate and save port and authkey to ~/.cache/.keepmenu-auth
Returns: int port, bytestring authkey
"""
auth = configparser.ConfigParser()
if not exists(AUTH_FILE):
fd = os.open(AUTH_FILE, os.O_WRONLY | os.O_CREAT, 0o600)
with open(fd, 'w') as a_file:
auth.set('DEFAULT', 'port', str(find_free_port()))
auth.set('DEFAULT', 'authkey', random_str())
auth.write(a_file)
try:
auth.read(AUTH_FILE)
port = auth.get('DEFAULT', 'port')
authkey = auth.get('DEFAULT', 'authkey').encode()
except (configparser.NoOptionError, configparser.MissingSectionHeaderError):
os.remove(AUTH_FILE)
print("Cache file was corrupted. Stopping all instances. Please try again")
call(["pkill", "keepmenu"]) # Kill all prior instances as well
return None, None
return int(port), authkey
def dmenu_cmd(num_lines, prompt):
"""Parse config.ini for dmenu options
Args: args - num_lines: number of lines to display
prompt: prompt to show
Returns: command invocation (as a list of strings) for
dmenu -l <num_lines> -p <prompt> -i ...
"""
args_dict = {"dmenu_command": "dmenu"}
if CONF.has_section('dmenu'):
args = CONF.items('dmenu')
args_dict.update(dict(args))
command = shlex.split(args_dict["dmenu_command"])
dmenu_command = command[0]
dmenu_args = command[1:]
del args_dict["dmenu_command"]
lines = "-i -dmenu -multi-select -lines" if "rofi" in dmenu_command else "-i -l"
if "l" in args_dict:
lines = "{} {}".format(lines, min(num_lines, int(args_dict['l'])))
del args_dict['l']
else:
lines = "{} {}".format(lines, num_lines)
if "pinentry" in args_dict:
del args_dict["pinentry"]
if prompt == "Passphrase":
if CONF.has_section('dmenu_passphrase'):
args = CONF.items('dmenu_passphrase')
args_dict.update(args)
rofi_obscure = True
if CONF.has_option('dmenu_passphrase', 'rofi_obscure'):
rofi_obscure = CONF.getboolean('dmenu_passphrase', 'rofi_obscure')
del args_dict["rofi_obscure"]
if rofi_obscure is True and "rofi" in dmenu_command:
dmenu_args.extend(["-password"])
extras = (["-" + str(k), str(v)] for (k, v) in args_dict.items())
dmenu = [dmenu_command, "-p", str(prompt)]
dmenu.extend(dmenu_args)
dmenu += list(itertools.chain.from_iterable(extras))
dmenu[1:1] = lines.split()
dmenu = list(filter(None, dmenu)) # Remove empty list elements
return dmenu
def dmenu_select(num_lines, prompt="Entries", inp=""):
"""Call dmenu and return the selected entry
Args: num_lines - number of lines to display
prompt - prompt to show
inp - bytes string to pass to dmenu via STDIN
Returns: sel - string
"""
cmd = dmenu_cmd(num_lines, prompt)
sel, err = Popen(cmd,
stdin=PIPE,
stdout=PIPE,
stderr=PIPE,
env=ENV).communicate(input=inp)
if err:
cmd = [cmd[0]] + ["-dmenu"] if "rofi" in cmd[0] else [""]
Popen(cmd[0], stdin=PIPE, stdout=PIPE, env=ENV).communicate(input=err)
sys.exit()
if sel is not None:
sel = sel.decode(ENC).rstrip('\n')
return sel
def dmenu_err(prompt):
"""Pops up a dmenu prompt with an error message
"""
return dmenu_select(1, prompt)
def get_password_chars():
"""Get characters to use for password generation from defaults, config file
and user input.
Returns: Dict {preset_name_1: {char_set_1: string, char_set_2: string},
preset_name_2: ....}
"""
chars = {"upper": string.ascii_uppercase,
"lower": string.ascii_lowercase,
"digits": string.digits,
"punctuation": string.punctuation}
presets = {}
presets["Letters+Digits+Punctuation"] = chars
presets["Letters+Digits"] = {k: chars[k] for k in ("upper", "lower", "digits")}
presets["Letters"] = {k: chars[k] for k in ("upper", "lower")}
presets["Digits"] = {k: chars[k] for k in ("digits",)}
if CONF.has_section('password_chars'):
pw_chars = dict(CONF.items('password_chars'))
chars.update(pw_chars)
for key, val in pw_chars.items():
presets[key.title()] = {k: chars[k] for k in (key,)}
if CONF.has_section('password_char_presets'):
if CONF.options('password_char_presets'):
presets = {}
for name, val in CONF.items('password_char_presets'):
try:
presets[name.title()] = {k: chars[k] for k in shlex.split(val)}
except KeyError:
print("Error: Unknown value in preset {}. Ignoring.".format(name))
continue
input_b = "\n".join(presets).encode(ENC)
char_sel = dmenu_select(len(presets),
"Pick character set(s) to use", inp=input_b)
# This dictionary return also handles Rofi multiple select
return {k: presets[k] for k in char_sel.split('\n')} if char_sel else False
def get_database():
"""Read databases from config or ask for user input.
Returns: (database name, keyfile, passphrase)
Returns (None, None, None) on error selecting database
"""
args = CONF.items('database')
args_dict = dict(args)
dbases = [i for i in args_dict if i.startswith('database')]
dbs = []
for dbase in dbases:
dbn = expanduser(args_dict[dbase])
idx = dbase.rsplit('_', 1)[-1]
try:
keyfile = expanduser(args_dict['keyfile_{}'.format(idx)])
except KeyError:
keyfile = ''
try:
passw = args_dict['password_{}'.format(idx)]
except KeyError:
passw = ''
try:
cmd = args_dict['password_cmd_{}'.format(idx)]
res = Popen(shlex.split(cmd), stdout=PIPE, stderr=PIPE).communicate()
if res[1]:
dmenu_err("Password command error: {}".format(res[1]))
sys.exit()
else:
passw = res[0].decode().rstrip('\n') if res[0] else passw
except KeyError:
pass
if dbn:
dbs.append((dbn, keyfile, passw))
if not dbs:
res = get_initial_db()
if res is True:
dbs = [get_database()]
else:
return (None, None, None)
if len(dbs) > 1:
inp_bytes = "\n".join(i[0] for i in dbs).encode(ENC)
sel = dmenu_select(len(dbs), "Select Database", inp=inp_bytes)
dbs = [i for i in dbs if i[0] == sel]
if not sel or not dbs:
return (None, None, None)
if not dbs[0][-1]:
db_l = list(dbs[0])
db_l[-1] = get_passphrase()
dbs[0] = db_l
return dbs[0]
def get_initial_db():
"""Ask for initial database name and keyfile if not entered in config file
"""
db_name = dmenu_select(0, "Enter path to existing "
"Keepass database. ~/ for $HOME is ok")
if not db_name:
dmenu_err("No database entered. Try again.")
return False
keyfile_name = dmenu_select(0, "Enter path to keyfile. ~/ for $HOME is ok")
with open(CONF_FILE, 'w') as conf_file:
CONF.set('database', 'database_1', db_name)
if keyfile_name:
CONF.set('database', 'keyfile_1', keyfile_name)
CONF.write(conf_file)
return True
def get_entries(dbo):
"""Open keepass database and return the PyKeePass object
Args: dbo: tuple (db path, keyfile path, password)
Returns: PyKeePass object
"""
dbf, keyfile, password = dbo
if dbf is None:
return None
try:
kpo = PyKeePass(dbf, password, keyfile=keyfile)
except (FileNotFoundError, construct.core.ChecksumError) as err:
if str(err.args[0]).startswith("wrong checksum"):
dmenu_err("Invalid Password or keyfile")
return None
try:
if err.errno == errno.ENOENT:
if not os.path.isfile(dbf):
dmenu_err("Database does not exist. Edit ~/.config/keepmenu/config.ini")
elif not os.path.isfile(keyfile):
dmenu_err("Keyfile does not exist. Edit ~/.config/keepmenu/config.ini")
except AttributeError:
pass
return None
except Exception as err:
dmenu_err("Error: {}".format(err))
return None
return kpo
def get_passphrase():
"""Get a database password from dmenu or pinentry
Returns: string
"""
pinentry = None
if CONF.has_option("dmenu", "pinentry"):
pinentry = CONF.get("dmenu", "pinentry")
if pinentry:
password = ""
out = Popen(pinentry,
stdout=PIPE,
stdin=PIPE).communicate(
input=b'setdesc Enter database password\ngetpin\n')[0]
if out:
res = out.decode(ENC).split("\n")[2]
if res.startswith("D "):
password = res.split("D ")[1]
else:
password = dmenu_select(0, "Passphrase")
if not password:
sys.exit()
return password
def tokenize_autotype(autotype):
"""Process the autotype sequence
Args: autotype - string
Returns: tokens - generator ((token, if_special_char T/F), ...)
"""
while autotype:
opening_idx = -1
for char in "{+^%~@":
idx = autotype.find(char)
if idx != -1 and (opening_idx == -1 or idx < opening_idx):
opening_idx = idx
if opening_idx == -1:
# found the end of the string without further opening braces or
# other characters
yield autotype, False
return
if opening_idx > 0:
yield autotype[:opening_idx], False
if autotype[opening_idx] in "+^%~@":
yield autotype[opening_idx], True
autotype = autotype[opening_idx + 1:]
continue
closing_idx = autotype.find('}')
if closing_idx == -1:
dmenu_err("Unable to find matching right brace (}) while" +
"tokenizing auto-type string: %s\n" % (autotype))
return
if closing_idx == opening_idx + 1 and closing_idx + 1 < len(autotype) \
and autotype[closing_idx + 1] == '}':
yield "{}}", True
autotype = autotype[closing_idx + 2:]
continue
yield autotype[opening_idx:closing_idx + 1], True
autotype = autotype[closing_idx + 1:]
def token_command(token):
"""When token denotes a special command, this function provides a callable
implementing its behaviour.
"""
cmd = None
def _check_delay():
match = re.match(r'{DELAY (\d+)}', token)
if match:
delay = match.group(1)
nonlocal cmd
cmd = lambda t=delay: time.sleep(int(t) / 1000)
return True
return False
if _check_delay(): # {DELAY x}
return cmd
return None
def type_entry(entry):
"""Pick which library to use to type strings
Defaults to pynput
"""
sequence = SEQUENCE
if hasattr(entry, 'autotype_enabled') and entry.autotype_enabled is False:
dmenu_err("Autotype disabled for this entry")
return
if hasattr(entry, 'autotype_sequence') and \
entry.autotype_sequence is not None and \
entry.autotype_sequence != 'None':
sequence = entry.autotype_sequence
tokens = tokenize_autotype(sequence)
library = 'pynput'
if CONF.has_option('database', 'type_library'):
library = CONF.get('database', 'type_library')
if library == 'xdotool':
type_entry_xdotool(entry, tokens)
elif library == 'ydotool':
type_entry_ydotool(entry, tokens)
else:
type_entry_pynput(entry, tokens)
PLACEHOLDER_AUTOTYPE_TOKENS = {
"{TITLE}" : lambda e: e.title,
"{USERNAME}": lambda e: e.username,
"{URL}" : lambda e: e.url,
"{PASSWORD}": lambda e: e.password,
"{NOTES}" : lambda e: e.notes,
}
STRING_AUTOTYPE_TOKENS = {
"{PLUS}" : '+',
"{PERCENT}" : '%',
"{CARET}" : '^',
"{TILDE}" : '~',
"{LEFTPAREN}" : '(',
"{RIGHTPAREN}": ')',
"{LEFTBRACE}" : '{',
"{RIGHTBRACE}": '}',
"{AT}" : '@',
"{+}" : '+',
"{%}" : '%',
"{^}" : '^',
"{~}" : '~',
"{(}" : '(',
"{)}" : ')',
"{[}" : '[',
"{]}" : ']',
"{{}" : '{',
"{}}" : '}',
}
PYNPUT_AUTOTYPE_TOKENS = {
"{TAB}" : keyboard.Key.tab,
"{ENTER}" : keyboard.Key.enter,
"~" : keyboard.Key.enter,
"{UP}" : keyboard.Key.up,
"{DOWN}" : keyboard.Key.down,
"{LEFT}" : keyboard.Key.left,
"{RIGHT}" : keyboard.Key.right,
"{INSERT}" : keyboard.Key.insert,
"{INS}" : keyboard.Key.insert,
"{DELETE}" : keyboard.Key.delete,
"{DEL}" : keyboard.Key.delete,
"{HOME}" : keyboard.Key.home,
"{END}" : keyboard.Key.end,
"{PGUP}" : keyboard.Key.page_up,
"{PGDN}" : keyboard.Key.page_down,
"{SPACE}" : keyboard.Key.space,
"{BACKSPACE}" : keyboard.Key.backspace,
"{BS}" : keyboard.Key.backspace,
"{BKSP}" : keyboard.Key.backspace,
"{BREAK}" : keyboard.Key.pause,
"{CAPSLOCK}" : keyboard.Key.caps_lock,
"{ESC}" : keyboard.Key.esc,
"{WIN}" : keyboard.Key.cmd,
"{LWIN}" : keyboard.Key.cmd_l,
"{RWIN}" : keyboard.Key.cmd_r,
# "{APPS}" : keyboard.Key.
# "{HELP}" : keyboard.Key.
"{NUMLOCK}" : keyboard.Key.num_lock,
"{PRTSC}" : keyboard.Key.print_screen,
"{SCROLLLOCK}": keyboard.Key.scroll_lock,
"{F1}" : keyboard.Key.f1,
"{F2}" : keyboard.Key.f2,
"{F3}" : keyboard.Key.f3,
"{F4}" : keyboard.Key.f4,
"{F5}" : keyboard.Key.f5,
"{F6}" : keyboard.Key.f6,
"{F7}" : keyboard.Key.f7,
"{F8}" : keyboard.Key.f8,
"{F9}" : keyboard.Key.f9,
"{F10}" : keyboard.Key.f10,
"{F11}" : keyboard.Key.f11,
"{F12}" : keyboard.Key.f12,
"{F13}" : keyboard.Key.f13,
"{F14}" : keyboard.Key.f14,
"{F15}" : keyboard.Key.f15,
"{F16}" : keyboard.Key.f16,
# "{ADD}" : keyboard.Key.
# "{SUBTRACT}" : keyboard.Key.
# "{MULTIPLY}" : keyboard.Key.
# "{DIVIDE}" : keyboard.Key.
# "{NUMPAD0}" : keyboard.Key.
# "{NUMPAD1}" : keyboard.Key.
# "{NUMPAD2}" : keyboard.Key.
# "{NUMPAD3}" : keyboard.Key.
# "{NUMPAD4}" : keyboard.Key.
# "{NUMPAD5}" : keyboard.Key.
# "{NUMPAD6}" : keyboard.Key.
# "{NUMPAD7}" : keyboard.Key.
# "{NUMPAD8}" : keyboard.Key.
# "{NUMPAD9}" : keyboard.Key.
"+" : keyboard.Key.shift,
"^" : keyboard.Key.ctrl,
"%" : keyboard.Key.alt,
"@" : keyboard.Key.cmd,
}
def type_entry_pynput(entry, tokens):
"""Use pynput to auto-type the selected entry
"""
kbd = keyboard.Controller()
enter_idx = True
for token, special in tokens:
if special:
cmd = token_command(token)
if callable(cmd):
cmd()
elif token in PLACEHOLDER_AUTOTYPE_TOKENS:
to_type = PLACEHOLDER_AUTOTYPE_TOKENS[token](entry)
if to_type:
try:
kbd.type(to_type)
except kbd.InvalidCharacterException:
dmenu_err("Unable to type string...bad character.\n"
"Try setting `type_library = xdotool` in config.ini")
return
elif token in STRING_AUTOTYPE_TOKENS:
to_type = STRING_AUTOTYPE_TOKENS[token]
try:
kbd.type(to_type)
except kbd.InvalidCharacterException:
dmenu_err("Unable to type string...bad character.\n"
"Try setting `type_library = xdotool` in config.ini")
return
elif token in PYNPUT_AUTOTYPE_TOKENS:
to_tap = PYNPUT_AUTOTYPE_TOKENS[token]
kbd.tap(to_tap)
# Add extra {ENTER} key tap for first instance of {ENTER}. It
# doesn't get recognized for some reason.
if enter_idx is True and token in ("{ENTER}", "~"):
kbd.tap(to_tap)
enter_idx = False
else:
dmenu_err("Unsupported auto-type token (pynput): \"%s\"" % (token))
return
else:
try:
kbd.type(token)
except kbd.InvalidCharacterException:
dmenu_err("Unable to type string...bad character.\n"
"Try setting `type_library = xdotool` in config.ini")
return
XDOTOOL_AUTOTYPE_TOKENS = {
"{TAB}" : ['key', 'Tab'],
"{ENTER}" : ['key', 'Return'],
"~" : ['key', 'Return'],
"{UP}" : ['key', 'Up'],
"{DOWN}" : ['key', 'Down'],
"{LEFT}" : ['key', 'Left'],
"{RIGHT}" : ['key', 'Right'],
"{INSERT}" : ['key', 'Insert'],
"{INS}" : ['key', 'Insert'],
"{DELETE}" : ['key', 'Delete'],
"{DEL}" : ['key', 'Delete'],
"{HOME}" : ['key', 'Home'],
"{END}" : ['key', 'End'],
"{PGUP}" : ['key', 'Page_Up'],
"{PGDN}" : ['key', 'Page_Down'],
"{SPACE}" : ['type', ' '],
"{BACKSPACE}" : ['key', 'BackSpace'],
"{BS}" : ['key', 'BackSpace'],
"{BKSP}" : ['key', 'BackSpace'],
"{BREAK}" : ['key', 'Break'],
"{CAPSLOCK}" : ['key', 'Caps_Lock'],
"{ESC}" : ['key', 'Escape'],
"{WIN}" : ['key', 'Super'],
"{LWIN}" : ['key', 'Super_L'],
"{RWIN}" : ['key', 'Super_R'],
# "{APPS}" : ['key', ''],
# "{HELP}" : ['key', ''],
"{NUMLOCK}" : ['key', 'Num_Lock'],
# "{PRTSC}" : ['key', ''],
"{SCROLLLOCK}": ['key', 'Scroll_Lock'],
"{F1}" : ['key', 'F1'],
"{F2}" : ['key', 'F2'],
"{F3}" : ['key', 'F3'],
"{F4}" : ['key', 'F4'],
"{F5}" : ['key', 'F5'],
"{F6}" : ['key', 'F6'],
"{F7}" : ['key', 'F7'],
"{F8}" : ['key', 'F8'],
"{F9}" : ['key', 'F9'],
"{F10}" : ['key', 'F10'],
"{F11}" : ['key', 'F11'],
"{F12}" : ['key', 'F12'],
"{F13}" : ['key', 'F13'],
"{F14}" : ['key', 'F14'],
"{F15}" : ['key', 'F15'],
"{F16}" : ['key', 'F16'],
"{ADD}" : ['key', 'KP_Add'],
"{SUBTRACT}" : ['key', 'KP_Subtract'],
"{MULTIPLY}" : ['key', 'KP_Multiply'],
"{DIVIDE}" : ['key', 'KP_Divide'],
"{NUMPAD0}" : ['key', 'KP_0'],
"{NUMPAD1}" : ['key', 'KP_1'],
"{NUMPAD2}" : ['key', 'KP_2'],
"{NUMPAD3}" : ['key', 'KP_3'],
"{NUMPAD4}" : ['key', 'KP_4'],
"{NUMPAD5}" : ['key', 'KP_5'],
"{NUMPAD6}" : ['key', 'KP_6'],
"{NUMPAD7}" : ['key', 'KP_7'],
"{NUMPAD8}" : ['key', 'KP_8'],
"{NUMPAD9}" : ['key', 'KP_9'],
"+" : ['key', 'Shift'],
"^" : ['Key', 'Ctrl'],
"%" : ['key', 'Alt'],
"@" : ['key', 'Super'],
}
def type_entry_xdotool(entry, tokens):
"""Auto-type entry entry using xdotool
"""
enter_idx = True
for token, special in tokens:
if special:
cmd = token_command(token)
if callable(cmd):
cmd()
elif token in PLACEHOLDER_AUTOTYPE_TOKENS:
to_type = PLACEHOLDER_AUTOTYPE_TOKENS[token](entry)
if to_type:
call(['xdotool', 'type', to_type])
elif token in STRING_AUTOTYPE_TOKENS:
to_type = STRING_AUTOTYPE_TOKENS[token]
call(['xdotool', 'type', to_type])
elif token in XDOTOOL_AUTOTYPE_TOKENS:
cmd = ['xdotool'] + XDOTOOL_AUTOTYPE_TOKENS[token]
call(cmd)
# Add extra {ENTER} key tap for first instance of {ENTER}. It
# doesn't get recognized for some reason.
if enter_idx is True and token in ("{ENTER}", "~"):
cmd = ['xdotool'] + XDOTOOL_AUTOTYPE_TOKENS[token]
call(cmd)
enter_idx = False
else:
dmenu_err("Unsupported auto-type token (xdotool): \"%s\"" % (token))
return
else:
call(['xdotool', 'type', token])
YDOTOOL_AUTOTYPE_TOKENS = {
"{TAB}" : ['key', 'TAB'],
"{ENTER}" : ['key', 'ENTER'],
"~" : ['key', 'Return'],
"{UP}" : ['key', 'UP'],
"{DOWN}" : ['key', 'DOWN'],
"{LEFT}" : ['key', 'LEFT'],
"{RIGHT}" : ['key', 'RIGHT'],
"{INSERT}" : ['key', 'INSERT'],
"{INS}" : ['key', 'INSERT'],
"{DELETE}" : ['key', 'DELETE'],
"{DEL}" : ['key', 'DELETE'],
"{HOME}" : ['key', 'HOME'],
"{END}" : ['key', 'END'],
"{PGUP}" : ['key', 'PAGEUP'],
"{PGDN}" : ['key', 'PAGEDOWN'],
"{SPACE}" : ['type', ' '],
"{BACKSPACE}" : ['key', 'BACKSPACE'],
"{BS}" : ['key', 'BACKSPACE'],
"{BKSP}" : ['key', 'BACKSPACE'],
"{BREAK}" : ['key', 'BREAK'],
"{CAPSLOCK}" : ['key', 'CAPSLOCK'],
"{ESC}" : ['key', 'ESC'],
# "{WIN}" : ['key', 'Super'],
# "{LWIN}" : ['key', 'Super_L'],
# "{RWIN}" : ['key', 'Super_R'],
# "{APPS}" : ['key', ''],
# "{HELP}" : ['key', ''],
"{NUMLOCK}" : ['key', 'NUMLOCK'],
# "{PRTSC}" : ['key', ''],
"{SCROLLLOCK}": ['key', 'SCROLLLOCK'],
"{F1}" : ['key', 'F1'],
"{F2}" : ['key', 'F2'],
"{F3}" : ['key', 'F3'],
"{F4}" : ['key', 'F4'],
"{F5}" : ['key', 'F5'],
"{F6}" : ['key', 'F6'],
"{F7}" : ['key', 'F7'],
"{F8}" : ['key', 'F8'],
"{F9}" : ['key', 'F9'],
"{F10}" : ['key', 'F10'],
"{F11}" : ['key', 'F11'],
"{F12}" : ['key', 'F12'],
"{F13}" : ['key', 'F13'],
"{F14}" : ['key', 'F14'],
"{F15}" : ['key', 'F15'],
"{F16}" : ['key', 'F16'],
"{ADD}" : ['key', 'KPPLUS'],
"{SUBTRACT}" : ['key', 'KPMINUS'],
"{MULTIPLY}" : ['key', 'KPASTERISK'],
"{DIVIDE}" : ['key', 'KPSLASH'],
"{NUMPAD0}" : ['key', 'KP0'],
"{NUMPAD1}" : ['key', 'KP1'],
"{NUMPAD2}" : ['key', 'KP2'],
"{NUMPAD3}" : ['key', 'KP3'],
"{NUMPAD4}" : ['key', 'KP4'],
"{NUMPAD5}" : ['key', 'KP5'],
"{NUMPAD6}" : ['key', 'KP6'],
"{NUMPAD7}" : ['key', 'KP7'],
"{NUMPAD8}" : ['key', 'KP8'],
"{NUMPAD9}" : ['key', 'KP9'],
"+" : ['key', 'LEFTSHIFT'],
"^" : ['Key', 'LEFTCTRL'],
"%" : ['key', 'LEFTALT'],
# "@" : ['key', 'Super']
}
def type_entry_ydotool(entry, tokens):
"""Auto-type entry entry using ydotool
"""
enter_idx = True
for token, special in tokens:
if special:
cmd = token_command(token)
if callable(cmd):
cmd()
elif token in PLACEHOLDER_AUTOTYPE_TOKENS:
to_type = PLACEHOLDER_AUTOTYPE_TOKENS[token](entry)
if to_type:
call(['ydotool', 'type', to_type])
elif token in STRING_AUTOTYPE_TOKENS:
to_type = STRING_AUTOTYPE_TOKENS[token]
call(['ydotool', 'type', to_type])
elif token in YDOTOOL_AUTOTYPE_TOKENS:
cmd = ['ydotool'] + YDOTOOL_AUTOTYPE_TOKENS[token]
call(cmd)
# Add extra {ENTER} key tap for first instance of {ENTER}. It
# doesn't get recognized for some reason.
if enter_idx is True and token in ("{ENTER}", "~"):
cmd = ['ydotool'] + YDOTOOL_AUTOTYPE_TOKENS[token]
call(cmd)
enter_idx = False
else:
dmenu_err("Unsupported auto-type token (ydotool): \"%s\"" % (token))
return
else:
call(['ydotool', 'type', token])
def type_text(data):
"""Type the given text data
"""
library = 'pynput'
if CONF.has_option('database', 'type_library'):
library = CONF.get('database', 'type_library')
if library == 'xdotool':
call(['xdotool', 'type', data])
elif library == 'ydotool':
call(['ydotool', 'type', data])
else:
kbd = keyboard.Controller()
try:
kbd.type(data)
except kbd.InvalidCharacterException:
dmenu_err("Unable to type string...bad character.\n"
"Try setting `type_library = xdotool` in config.ini")
def view_all_entries(options, entries_descriptions, prompt='Entries'):
"""Generate numbered list of all Keepass entries and open with dmenu.
Returns: dmenu selection
"""
kp_entries_b = str("\n").join(entries_descriptions).encode(ENC)
if options:
options_b = ("\n".join(map(str, options)) + "\n").encode(ENC)
entries_b = options_b + kp_entries_b
else:
entries_b = kp_entries_b
return dmenu_select(min(DMENU_LEN, len(options) + len(entries_descriptions)), prompt, inp=entries_b)
def select_group(kpo, prompt="Groups"):
"""Select which group for an entry
Args: kpo - Keepass object
options - list of menu options for groups
Returns: False for no entry
group - string
"""
groups = kpo.groups
num_align = len(str(len(groups)))
pattern = str("{:>{na}} - {}")
input_b = str("\n").join([pattern.format(j, i.path, na=num_align)
for j, i in enumerate(groups)]).encode(ENC)
sel = dmenu_select(min(DMENU_LEN, len(groups)), prompt, inp=input_b)
if not sel:
return False
try:
return groups[int(sel.split('-', 1)[0])]
except (ValueError, TypeError):
return False
def manage_groups(kpo):
"""Rename, create, move or delete groups
Args: kpo - Keepass object
Returns: Group object or False
"""
edit = True
options = ['Create',
'Move',
'Rename',
'Delete']
group = False
while edit is True:
input_b = b"\n".join(i.encode(ENC) for i in options) + b"\n\n" + \
b"\n".join(i.path.encode(ENC) for i in kpo.groups)
sel = dmenu_select(len(options) + len(kpo.groups) + 1, "Groups", inp=input_b)
if not sel:
edit = False
elif sel == 'Create':
group = create_group(kpo)
elif sel == 'Move':
group = move_group(kpo)
elif sel == 'Rename':
group = rename_group(kpo)
elif sel == 'Delete':
group = delete_group(kpo)
else:
edit = False
return group
def create_group(kpo):
"""Create new group
Args: kpo - Keepass object
Returns: Group object or False
"""