baseui.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. # ===========================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. # ============================================================================
  17. # Copyright (C) 2013-2017 Oz Nahum Tiram <oz.tiram@gmail.com>
  18. # ============================================================================
  19. import ast
  20. import csv
  21. import os
  22. import re
  23. import select as uselect
  24. import shutil
  25. import sys
  26. import time
  27. from colorama import Fore
  28. from pwman.data.nodes import Node
  29. from pwman.ui import tools
  30. from pwman.util.crypto_engine import CryptoEngine
  31. from pwman.util.crypto_engine import zerome
  32. from pwman.ui.tools import CliMenuItem
  33. from pwman.ui.tools import CMDLoop, get_or_create_pass
  34. def _heard_enter(): # pragma: no cover
  35. i, o, e = uselect.select([sys.stdin], [], [], 0.0001)
  36. for s in i:
  37. if s == sys.stdin:
  38. sys.stdin.readline()
  39. return True
  40. return False
  41. def _wait_until_enter(predicate, timeout, period=0.25): # pragma: no cover
  42. mustend = time.time() + timeout
  43. while time.time() < mustend:
  44. cond = predicate()
  45. if cond:
  46. break
  47. time.sleep(period)
  48. class HelpUIMixin(object): # pragma: no cover
  49. """
  50. this class holds all the UI help functionality.
  51. in PwmanCliNew. The later inherits from this class
  52. and allows it to print help messages to the console.
  53. """
  54. def _usage(self, string):
  55. print("Usage: %s" % (string))
  56. def help_open(self):
  57. self._usage("open|o <ID>")
  58. print("Launch default browser with 'xdg-open url',\n",
  59. "the url must contain http:// or https://.")
  60. def help_copy(self):
  61. self._usage("copy|cp <ID>")
  62. print("Copy password to X clipboard (xsel required)")
  63. def help_cls(self):
  64. self._usage("cls")
  65. print("Clear the Screen from information.")
  66. def help_list(self):
  67. self._usage("list|ls <tag> ...")
  68. print("List nodes that match current or specified filter.",
  69. " ls is an alias.")
  70. def help_delete(self):
  71. self._usage("delete|rm <ID|tag> ...")
  72. print("Deletes nodes.")
  73. self._mult_id_help()
  74. def help_help(self):
  75. self._usage("help|h [topic]")
  76. print("Prints a help message for a command.")
  77. def help_edit(self):
  78. self._usage("edit <ID|tag> ... ")
  79. print("Edits a nodes.")
  80. def help_export(self):
  81. self._usage("export [{'filename': 'foo.csv', 'delimiter':'|'}] ")
  82. print("All nodes under the current filter are exported.")
  83. def help_new(self):
  84. self._usage("new")
  85. print("Creates a new node.,",
  86. "You can override default config settings the following way:\n",
  87. "pwman> n {'leetify':False, 'numerics':True}")
  88. def help_print(self):
  89. self._usage("print <ID|tag> ...")
  90. print("Displays a node. ")
  91. self._mult_id_help()
  92. def _mult_id_help(self):
  93. print("Multiple ids and nodes can be specified, separated by a space.",
  94. " A range of ids can be specified in the format n-N. e.g. ",
  95. " '10-20' would specify all nodes having ids from 10 to 20 ",
  96. " inclusive. Tags are considered one-by-one. e.g. 'foo 2 bar'",
  97. " would yield to all nodes with tag 'foo', node 2 and all ",
  98. " nodes with tag 'bar'.")
  99. def help_exit(self):
  100. self._usage("exit|EOF")
  101. print("Exits the application.")
  102. def help_passwd(self):
  103. self._usage("passwd")
  104. print("Changes the password on the database. ")
  105. def help_forget(self):
  106. self._usage("forget")
  107. print("Forgets the database password. Your password will need to ",
  108. "be reentered before accessing the database again.")
  109. def help_tags(self):
  110. self._usage("tags")
  111. print("Displays all tags in used in the database.")
  112. def help_info(self):
  113. print("Show information about the current database.")
  114. class AliasesMixin(object): # pragma: no cover
  115. """
  116. Define all the alias you want here...
  117. """
  118. def do_cp(self, args):
  119. self.do_copy(args)
  120. def do_EOF(self, args): # pragma: no cover
  121. self.do_exit(args)
  122. def do_ls(self, args):
  123. self.do_list(args)
  124. def do_p(self, arg):
  125. self.do_print(arg)
  126. def do_rm(self, arg):
  127. self.do_delete(arg)
  128. def do_o(self, args):
  129. self.do_open(args)
  130. def do_e(self, args):
  131. self.do_edit(args)
  132. def do_h(self, arg):
  133. self.do_help(arg)
  134. def do_n(self, arg):
  135. self.do_new(arg)
  136. class BaseUtilsMixin:
  137. """Helper class for storing all privates, useful for testing these methods
  138. directly
  139. """
  140. def _get_ids(self, args):
  141. """
  142. Each command can get a single ID or
  143. a range of IDs, with begin-end.
  144. e.g. 1-3 , will get 1 to 3.
  145. """
  146. ids = []
  147. rex = re.compile("^(?P<begin>\d+)(?:-(?P<end>\d+))?$")
  148. rex = rex.match(args)
  149. if hasattr(rex, 'groupdict'):
  150. try:
  151. begin = int(rex.groupdict()['begin'])
  152. end = int(rex.groupdict()['end'])
  153. if not end > begin:
  154. print("Start node should be smaller than end node")
  155. return ids
  156. ids += range(begin, end + 1)
  157. return ids
  158. except TypeError:
  159. ids.append(int(begin))
  160. else:
  161. print("Could not understand your input...")
  162. return ids
  163. return ids
  164. def _get_tags(self, default=None, reader=input):
  165. """
  166. Read tags from user input.
  167. Tags are simply returned as a list
  168. """
  169. # TODO: add method to read tags from db, so they
  170. # could be used for tab completer
  171. print("Tags: ", end="")
  172. sys.stdout.flush()
  173. taglist = sys.stdin.readline()
  174. tagstrings = taglist.split()
  175. tags = [tn for tn in tagstrings]
  176. return tags
  177. def _prep_term(self):
  178. self.do_cls('')
  179. rows, cols = shutil.get_terminal_size()
  180. return rows, cols
  181. def _format_line(self, tag_pad, nid="ID", user="USER", url="URL",
  182. tags="TAGS"):
  183. return ("{ID:<3} {USER:<{us}}{URL:<{ur}}{Tags:<{tg}}"
  184. "".format(ID=nid, USER=user,
  185. URL=url, Tags=tags, us=25,
  186. ur=25, tg=20))
  187. def _print_node_line(self, node, rows, cols):
  188. tagstring = ','.join([t.decode() for t in node.tags])
  189. fmt = self._format_line(cols, node._id, node.username,
  190. node.url[:20] + '...' if (len(node.url) > 22)
  191. else node.url,
  192. tagstring)
  193. formatted_entry = tools.typeset(fmt, Fore.YELLOW, False)
  194. print(formatted_entry)
  195. def _get_node_ids(self, args):
  196. filter = None
  197. if args:
  198. filter = args.split()[0]
  199. ce = CryptoEngine.get()
  200. filter = ce.encrypt(filter)
  201. nodeids = self._db.listnodes(filter=filter)
  202. return nodeids
  203. def _db_entries_to_nodes(self, raw_nodes):
  204. _nodes_inst = []
  205. # user, pass, url, notes
  206. for node in raw_nodes:
  207. _nodes_inst.append(Node.from_encrypted_entries(
  208. node[1],
  209. node[2],
  210. node[3],
  211. node[4],
  212. node[5:]))
  213. _nodes_inst[-1]._id = node[0]
  214. return _nodes_inst
  215. def _get_input(self, prompt):
  216. print(prompt, end="")
  217. sys.stdout.flush()
  218. return sys.stdin.readline().strip()
  219. def _get_secret(self):
  220. if sys.stdin.isatty(): # pragma: no cover
  221. p = get_or_create_pass()
  222. else:
  223. p = sys.stdin.readline().rstrip()
  224. return p
  225. def _do_new(self, args):
  226. node = {}
  227. node['username'] = self._get_input("Username: ")
  228. node['password'] = self._get_secret()
  229. node['url'] = self._get_input("Url: ")
  230. node['notes'] = self._get_input("Notes: ")
  231. node['tags'] = self._get_tags()
  232. node = Node(clear_text=True, **node)
  233. self._db.add_node(node)
  234. return node
  235. def _do_rm(self, nodes):
  236. for i in nodes:
  237. self._db.removenodes([i])
  238. def _get_node(self, nodeid):
  239. if not nodeid.isdigit():
  240. print("print accepts only a single ID ...")
  241. return
  242. nodes = self._db.getnodes([nodeid])
  243. if not nodes: # pragma: no cover
  244. print("Node not found ...")
  245. return
  246. node = self._db_entries_to_nodes(nodes)[0]
  247. return node
  248. class BaseCommands(HelpUIMixin, AliasesMixin, BaseUtilsMixin):
  249. @property
  250. def _xsel(self): # pragma: no cover
  251. if self.hasxsel:
  252. return True
  253. def do_EOF(self, args):
  254. return self.do_exit(args)
  255. def error(self, exception): # pragma: no cover
  256. if (isinstance(exception, KeyboardInterrupt)):
  257. print('')
  258. else:
  259. print("Error: {0} ".format(exception))
  260. def do_copy(self, args): # pragma: no cover
  261. """copy item to clipboard"""
  262. if not self.hasxsel:
  263. return
  264. if not args.isdigit():
  265. print("Copy accepts only IDs ...")
  266. return
  267. ids = args.split()
  268. if len(ids) > 1:
  269. print("Can copy only 1 password at a time...")
  270. return
  271. ce = CryptoEngine.get()
  272. nodes = self._db.getnodes(ids)
  273. for node in nodes:
  274. password = ce.decrypt(node[2])
  275. tools.text_to_clipboards(password)
  276. flushtimeout = self.config.get_value('Global', 'cp_timeout')
  277. flushtimeout = flushtimeout or 10
  278. print("erasing in {} sec...".format(flushtimeout))
  279. time.sleep(int(flushtimeout))
  280. tools.text_to_clipboards("")
  281. def do_open(self, args): # pragma: no cover
  282. ids = self._get_ids(args)
  283. if not args:
  284. self.help_open()
  285. return
  286. nodes = self._db.getnodes(ids)
  287. ce = CryptoEngine.get()
  288. for node in nodes:
  289. url = ce.decrypt(node[3]).decode()
  290. if not url.startswith(("http://", "https://")):
  291. url = "https://" + url
  292. if url:
  293. mask = os.umask(22)
  294. tools.open_url(url)
  295. os.umask(mask)
  296. def do_cls(self, args): # pragma: no cover
  297. """clear the screen"""
  298. os.system("clear")
  299. def do_exit(self, args): # pragma: no cover
  300. """close the text console"""
  301. self._db.close()
  302. return True
  303. def do_export(self, args):
  304. """export the database to a given format"""
  305. try:
  306. args = ast.literal_eval(args)
  307. except Exception:
  308. args = {}
  309. filename = args.get('filename', 'pwman-export.csv')
  310. delim = args.get('delimiter', ';')
  311. nodeids = self._db.listnodes()
  312. nodes = self._db.getnodes(nodeids)
  313. with open(filename, 'w') as csvfile:
  314. writer = csv.writer(csvfile, delimiter=delim)
  315. writer.writerow(['Username', 'URL', 'Password', 'Notes',
  316. 'Tags'])
  317. for node in nodes:
  318. n = Node.from_encrypted_entries(node[1], node[2], node[3],
  319. node[4],
  320. node[5:])
  321. tags = n.tags
  322. tags = ','.join(t.strip().decode() for t in tags)
  323. r = list([n.username, n.url, n.password, n.notes])
  324. writer.writerow(r + [tags])
  325. with open(filename) as f:
  326. for line in f.readlines():
  327. print(line)
  328. print("Successfuly exported database to {}".format(
  329. os.path.join(os.getcwd(), filename)))
  330. def do_forget(self, args):
  331. """
  332. drop saved key forcing the user to re-enter the master
  333. password
  334. """
  335. enc = CryptoEngine.get()
  336. enc.forget()
  337. def do_passwd(self, args): # pragma: no cover
  338. """change the master password of the database"""
  339. """old_enc = CryptoEngine.get()
  340. CryptoEngine._instance = None
  341. new_enc = CryptoEngine.get()
  342. TODO: backup tables: NODE, TAG, CRYPTO, LOOKUP
  343. TODO: create new tables
  344. TODO: Iterate on old entries, create new entries with new crypto
  345. TODO: If no errors encountered remove backup tables.
  346. TODO: expand list nodes to accept table name
  347. """
  348. def do_tags(self, args):
  349. """
  350. print all existing tags
  351. """
  352. ce = CryptoEngine.get()
  353. print("Tags:")
  354. tags = self._db.listtags()
  355. for t in tags:
  356. print(ce.decrypt(t).decode())
  357. def do_edit(self, args, menu=None):
  358. ids = self._get_ids(args)
  359. for i in ids:
  360. i = int(i)
  361. node = self._db.getnodes([i])
  362. if not node:
  363. print("Node not found ...")
  364. return
  365. node = node[0]
  366. node = node[1:5] + [node[5:]]
  367. node = Node.from_encrypted_entries(*node)
  368. if not menu:
  369. menu = CMDLoop(self.config)
  370. print("Editing node %d." % (i))
  371. menu.add(CliMenuItem("Username", node.username))
  372. menu.add(CliMenuItem("Password", node.password))
  373. menu.add(CliMenuItem("Url", node.url))
  374. menunotes = CliMenuItem("Notes", node.notes)
  375. menu.add(menunotes)
  376. menu.add(CliMenuItem("Tags", ','.join(map(lambda x: x.decode(), node.tags)))) # noqa
  377. menu.run(node)
  378. self._db.editnode(i, **node.to_encdict())
  379. # when done with node erase it
  380. zerome(node._password)
  381. def do_list(self, args):
  382. """
  383. list all existing nodes in database
  384. """
  385. rows, cols = self._prep_term()
  386. nodeids = self._get_node_ids(args)
  387. raw_nodes = self._db.getnodes(nodeids)
  388. _nodes_inst = self._db_entries_to_nodes(raw_nodes)
  389. head = self._format_line(cols - 32)
  390. print(tools.typeset(head, Fore.YELLOW, False))
  391. for idx, node in enumerate(_nodes_inst):
  392. self._print_node_line(node, rows, cols)
  393. def do_new(self, args): # pragma: no cover
  394. # The cmd module stops if any of do_* return something
  395. # else than None ...
  396. # This is bad for testing, so everything that is do_*
  397. # should call _do_* method which is testable
  398. self._do_new(args)
  399. def do_pp(self, args):
  400. node = self._get_node(args)
  401. print(node.password)
  402. def do_print(self, args):
  403. node = self._get_node(args)
  404. print(node)
  405. flushtimeout = self.config.get_value('Global', 'cls_timeout')
  406. flushtimeout = int(flushtimeout) if flushtimeout else 10
  407. if flushtimeout > 0:
  408. flushtimeout = flushtimeout or 10
  409. print("Type Enter to flush screen or wait %d sec. " % flushtimeout)
  410. _wait_until_enter(_heard_enter, flushtimeout)
  411. self.do_cls('')
  412. def do_delete(self, args):
  413. ce = CryptoEngine.get()
  414. ce.encrypt("")
  415. ids = self._get_ids(args)
  416. if not ids:
  417. return
  418. ans = tools.getinput("Are you sure you want to delete node{} {}"
  419. " [y/N]?".format("s" if len(ids) > 1 else "",
  420. ",".join(ids) if len(ids) > 1 else ids[0])) # noqa
  421. if ans.lower() == 'y':
  422. self._do_rm(ids)
  423. def do_info(self, args):
  424. print("Currently connected to: {}".format(
  425. self.config.get_value("Database", "dburi")))