baseui.py 16 KB

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