baseui.py 16 KB

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