baseui.py 15 KB

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