baseui.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. ce = CryptoEngine.get()
  184. nodes = self._db.getnodes(ids)
  185. for node in nodes:
  186. password = ce.decrypt(node[2])
  187. tools.text_to_clipboards(password)
  188. flushtimeout = self.config.get_value('Global', 'cp_timeout')
  189. flushtimeout = flushtimeout or 10
  190. print("erasing in {} sec...".format(flushtimeout))
  191. time.sleep(int(flushtimeout))
  192. tools.text_to_clipboards("")
  193. def do_open(self, args): # pragma: no cover
  194. ids = self._get_ids(args)
  195. if not args:
  196. self.help_open()
  197. return
  198. nodes = self._db.getnodes(ids)
  199. ce = CryptoEngine.get()
  200. for node in nodes:
  201. url = ce.decrypt(node[3])
  202. if not url.startswith(("http://", "https://")):
  203. url = "https://" + url
  204. tools.open_url(url)
  205. def do_exit(self, args): # pragma: no cover
  206. """close the text console"""
  207. self._db.close()
  208. return True
  209. def do_cls(self, args): # pragma: no cover
  210. """clear the screen"""
  211. os.system("clear")
  212. def do_export(self, args):
  213. """export the database to a given format"""
  214. try:
  215. args = ast.literal_eval(args)
  216. except Exception:
  217. args = {}
  218. filename = args.get('filename', 'pwman-export.csv')
  219. delim = args.get('delimiter', ';')
  220. nodeids = self._db.listnodes()
  221. nodes = self._db.getnodes(nodeids)
  222. with open(filename, 'w') as csvfile:
  223. writer = csv.writer(csvfile, delimiter=delim)
  224. writer.writerow(['Username', 'URL', 'Password', 'Notes',
  225. 'Tags'])
  226. for node in nodes:
  227. n = Node.from_encrypted_entries(node[1], node[2], node[3],
  228. node[4],
  229. node[5:])
  230. tags = n.tags
  231. tags = ','.join(t.strip() for t in tags)
  232. r = list([n.username, n.url, n.password, n.notes])
  233. writer.writerow(r + [tags])
  234. print("Successfuly exported database to {}".format(
  235. os.path.join(os.getcwd(), filename)))
  236. def do_forget(self, args):
  237. """
  238. drop saved key forcing the user to re-enter the master
  239. password
  240. """
  241. enc = CryptoEngine.get()
  242. enc.forget()
  243. def do_passwd(self, args): # pragma: no cover
  244. """change the master password of the database"""
  245. pass
  246. def do_tags(self, args):
  247. """
  248. print all existing tags
  249. """
  250. ce = CryptoEngine.get()
  251. print("Tags:")
  252. tags = self._db.listtags()
  253. for t in tags:
  254. print(ce.decrypt(t).decode())
  255. def _get_tags(self, default=None, reader=raw_input):
  256. """
  257. Read tags from user input.
  258. Tags are simply returned as a list
  259. """
  260. # TODO: add method to read tags from db, so they
  261. # could be used for tab completer
  262. print("Tags: ", end="")
  263. sys.stdout.flush()
  264. taglist = sys.stdin.readline()
  265. tagstrings = taglist.split()
  266. tags = [tn for tn in tagstrings]
  267. return tags
  268. def _prep_term(self):
  269. self.do_cls('')
  270. if sys.platform != 'win32':
  271. rows, cols = tools.gettermsize()
  272. else: # pragma: no cover
  273. rows, cols = 18, 80 # fix this !
  274. return rows, cols
  275. def _format_line(self, tag_pad, nid="ID", user="USER", url="URL",
  276. tags="TAGS"):
  277. return ("{ID:<3} {USER:<{us}}{URL:<{ur}}{Tags:<{tg}}"
  278. "".format(ID=nid, USER=user,
  279. URL=url, Tags=tags, us=25,
  280. ur=25, tg=20))
  281. def _print_node_line(self, node, rows, cols):
  282. tagstring = ','.join([t for t in node.tags])
  283. fmt = self._format_line(cols, node._id, node.username,
  284. node.url[:20]+'...' if (len(node.url) > 22)
  285. else node.url,
  286. tagstring)
  287. formatted_entry = tools.typeset(fmt, Fore.YELLOW, False)
  288. print(formatted_entry)
  289. def _get_node_ids(self, args):
  290. filter = None
  291. if args:
  292. filter = args.split()[0]
  293. ce = CryptoEngine.get()
  294. filter = ce.encrypt(filter)
  295. nodeids = self._db.listnodes(filter=filter)
  296. return nodeids
  297. def _db_entries_to_nodes(self, raw_nodes):
  298. _nodes_inst = []
  299. # user, pass, url, notes
  300. for node in raw_nodes:
  301. _nodes_inst.append(Node.from_encrypted_entries(
  302. node[1],
  303. node[2],
  304. node[3],
  305. node[4],
  306. node[5:]))
  307. _nodes_inst[-1]._id = node[0]
  308. return _nodes_inst
  309. def do_edit(self, args, menu=None):
  310. ids = self._get_ids(args)
  311. for i in ids:
  312. i = int(i)
  313. node = self._db.getnodes([i])[0]
  314. node = node[1:5] + [node[5:]]
  315. node = Node.from_encrypted_entries(*node)
  316. if not menu:
  317. menu = CMDLoop(self.config)
  318. print ("Editing node %d." % (i))
  319. menu.add(CliMenuItem("Username",
  320. self._get_input,
  321. node.username,
  322. node.username))
  323. menu.add(CliMenuItem("Password", self._get_secret,
  324. node.password,
  325. node.password))
  326. menu.add(CliMenuItem("Url", self._get_input,
  327. node.url,
  328. node.url))
  329. menunotes = CliMenuItem("Notes", self._get_input,
  330. node.notes,
  331. node.notes)
  332. menu.add(menunotes)
  333. tgetter = lambda: ', '.join(t for t in node.tags)
  334. menu.add(CliMenuItem("Tags", self._get_input,
  335. tgetter(),
  336. node.tags))
  337. menu.run(node)
  338. self._db.editnode(i, **node.to_encdict())
  339. # when done with node erase it
  340. zerome(node._password)
  341. def do_list(self, args):
  342. """
  343. list all existing nodes in database
  344. """
  345. rows, cols = self._prep_term()
  346. nodeids = self._get_node_ids(args)
  347. raw_nodes = self._db.getnodes(nodeids)
  348. _nodes_inst = self._db_entries_to_nodes(raw_nodes)
  349. head = self._format_line(cols-32)
  350. print(tools.typeset(head, Fore.YELLOW, False))
  351. for idx, node in enumerate(_nodes_inst):
  352. self._print_node_line(node, rows, cols)
  353. def _get_input(self, prompt):
  354. print(prompt, end="")
  355. sys.stdout.flush()
  356. return sys.stdin.readline().strip()
  357. def _get_secret(self):
  358. # TODO: enable old functionallity, with password generator.
  359. if sys.stdin.isatty(): # pragma: no cover
  360. p = getpass.getpass()
  361. else:
  362. p = sys.stdin.readline().rstrip()
  363. return p
  364. def _do_new(self, args):
  365. node = {}
  366. node['username'] = self._get_input("Username: ")
  367. node['password'] = self._get_secret()
  368. node['url'] = self._get_input("Url: ")
  369. node['notes'] = self._get_input("Notes: ")
  370. node['tags'] = self._get_tags()
  371. node = Node(clear_text=True, **node)
  372. self._db.add_node(node)
  373. return node
  374. def do_new(self, args): # pragma: no cover
  375. # The cmd module stops if and of do_* return something
  376. # else than None ...
  377. # This is bad for testing, so everything that is do_*
  378. # should call _do_* method which is testable
  379. self._do_new(args)
  380. def do_print(self, args):
  381. if not args.isdigit():
  382. print("print accepts only a single ID ...")
  383. return
  384. nodes = self._db.getnodes([args])
  385. node = self._db_entries_to_nodes(nodes)[0]
  386. print(node)
  387. flushtimeout = self.config.get_value('Global', 'cls_timeout')
  388. flushtimeout = flushtimeout or 10
  389. print("Type Enter to flush screen or wait %s sec. " % flushtimeout)
  390. _wait_until_enter(_heard_enter, float(flushtimeout))
  391. self.do_cls('')
  392. def _do_rm(self, args):
  393. for i in args.split():
  394. if not i.isdigit():
  395. print("%s is not a node ID" % i)
  396. return None
  397. for i in args.split():
  398. ans = tools.getinput(("Are you sure you want to delete node {}"
  399. " [y/N]?".format(i)))
  400. if ans.lower() == 'y':
  401. self._db.removenodes([i])
  402. def do_delete(self, args): # pragma: no cover
  403. CryptoEngine.get()
  404. self._do_rm(args)