base.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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 Oz Nahum <nahumoz@gmail.com>
  18. # ============================================================================
  19. # pylint: disable=I0011
  20. """
  21. Define the base CLI interface for pwman3
  22. """
  23. from __future__ import print_function
  24. from pwman.util.crypto_engine import CryptoEngine, zerome
  25. import re
  26. import sys
  27. import os
  28. import time
  29. import select as uselect
  30. import ast
  31. from pwman.util.config import get_pass_conf
  32. from pwman.ui import tools
  33. from pwman.ui.tools import CliMenuItem
  34. from colorama import Fore
  35. from pwman.data.nodes import NewNode
  36. from pwman.ui.tools import CMDLoop
  37. import getpass
  38. from pwman.data.tags import TagNew
  39. import csv
  40. if sys.version_info.major > 2:
  41. raw_input = input
  42. class HelpUI(object): # pragma: no cover
  43. """
  44. this class holds all the UI help functionality.
  45. in PwmanCliNew. The later inherits from this class
  46. and allows it to print help messages to the console.
  47. """
  48. def usage(self, string):
  49. print ("Usage: %s" % (string))
  50. def help_open(self):
  51. self.usage("open <ID>")
  52. print ("Launch default browser with 'xdg-open url',\n",
  53. "the url must contain http:// or https://.")
  54. def help_o(self):
  55. self.help_open()
  56. def help_copy(self):
  57. self.usage("copy <ID>")
  58. print ("Copy password to X clipboard (xsel required)")
  59. def help_cp(self):
  60. self.help_copy()
  61. def help_cls(self):
  62. self.usage("cls")
  63. print ("Clear the Screen from information.")
  64. def help_list(self):
  65. self.usage("list <tag> ...")
  66. print ("List nodes that match current or specified filter.",
  67. " l is an alias.")
  68. def help_EOF(self):
  69. self.help_exit()
  70. def help_delete(self):
  71. self.usage("delete <ID|tag> ...")
  72. print ("Deletes nodes. rm is an alias.")
  73. self._mult_id_help()
  74. def help_h(self):
  75. self.help_help()
  76. def help_help(self):
  77. self.usage("help [topic]")
  78. print ("Prints a help message for a command.")
  79. def help_e(self):
  80. self.help_edit()
  81. def help_n(self):
  82. self.help_new()
  83. def help_p(self):
  84. self.help_print()
  85. def help_l(self):
  86. self.help_list()
  87. def help_edit(self):
  88. self.usage("edit <ID|tag> ... ")
  89. print ("Edits a nodes.")
  90. def help_import(self):
  91. self.usage("import [filename] ...")
  92. print ("Not implemented...")
  93. def help_export(self):
  94. self.usage("export [{'filename': 'foo.csv', 'delimiter':'|'}] ")
  95. print("All nodes under the current filter are exported.")
  96. def help_new(self):
  97. self.usage("new")
  98. print ("Creates a new node.,",
  99. "You can override default config settings the following way:\n",
  100. "pwman> n {'leetify':False, 'numerics':True}")
  101. def help_rm(self):
  102. self.help_delete()
  103. def help_print(self):
  104. self.usage("print <ID|tag> ...")
  105. print ("Displays a node. ")
  106. self._mult_id_help()
  107. def _mult_id_help(self):
  108. print("Multiple ids and nodes can be specified, separated by a space.",
  109. " A range of ids can be specified in the format n-N. e.g. ",
  110. " '10-20' would specify all nodes having ids from 10 to 20 ",
  111. " inclusive. Tags are considered one-by-one. e.g. 'foo 2 bar'",
  112. " would yield to all nodes with tag 'foo', node 2 and all ",
  113. " nodes with tag 'bar'.")
  114. def help_exit(self):
  115. self.usage("exit")
  116. print("Exits the application.")
  117. def help_passwd(self):
  118. self.usage("passwd")
  119. print("Changes the password on the database. ")
  120. def help_forget(self):
  121. self.usage("forget")
  122. print("Forgets the database password. Your password will need to ",
  123. "be reentered before accessing the database again.")
  124. def help_clear(self):
  125. self.usage("clear")
  126. print("Clears the filter criteria. ")
  127. def help_filter(self):
  128. self.usage("filter <tag> ...")
  129. print("Filters nodes on tag. Arguments can be zero or more tags. ",
  130. "Displays current tags if called without arguments.")
  131. def help_tags(self):
  132. self.usage("tags")
  133. print("Displays all tags in used in the database.")
  134. class BaseUI(object):
  135. """
  136. this class holds all the UI functionality
  137. in PwmanCliNew. The later inherits from this class
  138. and allows it to print messages to the console.
  139. """
  140. def _do_filter(self, args):
  141. pass
  142. def _tags(self, enc):
  143. """
  144. read tags from TAGS table in DB,
  145. """
  146. tags = self._db.listtags()
  147. if tags:
  148. _tags = [''] * len(tags)
  149. for t in tags:
  150. try:
  151. _tags.append(enc.decrypt(t))
  152. except (ValueError, Exception) as e:
  153. _tags.append(t)
  154. del(e)
  155. _tags = filter(None, _tags)
  156. _tags = list(_tags)
  157. return _tags
  158. # pylint: disable=R0904
  159. class BaseCommands(BaseUI, HelpUI):
  160. """
  161. Inherit from the old class, override
  162. all the methods related to tags, and
  163. newer Node format, so backward compatability is kept...
  164. Commands defined here, can have aliases definded in Aliases.
  165. You can define the aliases here too, but it makes
  166. the class code really long and unclear.
  167. """
  168. def error(self, exception):
  169. if (isinstance(exception, KeyboardInterrupt)):
  170. print('')
  171. else:
  172. print("Error: {0} ".format(exception))
  173. def do_copy(self, args):
  174. if self.hasxsel:
  175. ids = self.get_ids(args)
  176. if len(ids) > 1:
  177. print ("Can copy only 1 password at a time...")
  178. return None
  179. try:
  180. node = self._db.getnodes(ids)
  181. tools.text_to_clipboards(node[0].password)
  182. print("copied password for {}@{} clipboard".format(
  183. node[0].username, node[0].url))
  184. print("erasing in 10 sec...")
  185. time.sleep(10)
  186. tools.text_to_clipboards("")
  187. except Exception as e:
  188. self.error(e)
  189. else:
  190. print ("Can't copy to clipboard, no xsel found in the system!")
  191. def do_exit(self, args):
  192. """exit the ui"""
  193. self._db.close()
  194. return True
  195. def do_export(self, args):
  196. try:
  197. args = ast.literal_eval(args)
  198. except Exception:
  199. args = {}
  200. filename = args.get('filename', 'pwman-export.csv')
  201. delim = args.get('delimiter', ';')
  202. nodeids = self._db.listnodes()
  203. nodes = self._db.getnodes(nodeids)
  204. with open(filename, 'w') as csvfile:
  205. writer = csv.writer(csvfile, delimiter=delim)
  206. writer.writerow(['Username', 'URL', 'Password', 'Notes',
  207. 'Tags'])
  208. for n in nodes:
  209. tags = n.tags
  210. tags = filter(None, tags)
  211. tags = ','.join(t.strip() for t in tags)
  212. writer.writerow([n.username, n.url, n.password, n.notes,
  213. tags])
  214. print("Successfuly exported database to {}".format(
  215. os.path.join(os.getcwd(), filename)))
  216. def do_forget(self, args):
  217. try:
  218. enc = CryptoEngine.get()
  219. enc.forget()
  220. except Exception as e:
  221. self.error(e)
  222. def get_username(self, default="", reader=raw_input):
  223. return tools.getinput("Username: ", default, reader)
  224. def get_url(self, default="", reader=raw_input):
  225. return tools.getinput("Url: ", default, reader)
  226. def get_notes(self, default="", reader=raw_input):
  227. return tools.getinput("Notes: ", default, reader)
  228. def do_open(self, args):
  229. ids = self.get_ids(args)
  230. if not args:
  231. self.help_open()
  232. return
  233. if len(ids) > 1:
  234. print ("Can open only 1 link at a time ...")
  235. return None
  236. try:
  237. node = self._db.getnodes(ids)
  238. url = node[0].url
  239. tools.open_url(url)
  240. except Exception as e:
  241. self.error(e)
  242. def do_clear(self, args):
  243. try:
  244. self._db.clearfilter()
  245. except Exception as e:
  246. self.error(e)
  247. def do_cls(self, args):
  248. os.system('clear')
  249. def do_edit(self, arg, menu=None):
  250. ids = self.get_ids(arg)
  251. for i in ids:
  252. try:
  253. i = int(i)
  254. node = self._db.getnodes([i])[0]
  255. if not menu:
  256. menu = CMDLoop()
  257. print ("Editing node %d." % (i))
  258. menu.add(CliMenuItem("Username", self.get_username,
  259. node.username,
  260. node.username))
  261. menu.add(CliMenuItem("Password", self.get_password,
  262. node.password,
  263. node.password))
  264. menu.add(CliMenuItem("Url", self.get_url,
  265. node.url,
  266. node.url))
  267. menunotes = CliMenuItem("Notes", self.get_notes,
  268. node.notes,
  269. node.notes)
  270. menu.add(menunotes)
  271. menu.add(CliMenuItem("Tags", self.get_tags,
  272. node.tags,
  273. node.tags))
  274. menu.run(node)
  275. self._db.editnode(i, node)
  276. # when done with node erase it
  277. zerome(node._password)
  278. except Exception as e:
  279. self.error(e)
  280. def print_node(self, node):
  281. width = str(tools._defaultwidth)
  282. print ("Node %d." % (node._id))
  283. print (("%" + width + "s %s") % (tools.typeset("Username:", Fore.RED),
  284. node.username))
  285. print (("%" + width + "s %s") % (tools.typeset("Password:", Fore.RED),
  286. node.password))
  287. print (("%" + width + "s %s") % (tools.typeset("Url:", Fore.RED),
  288. node.url))
  289. print (("%" + width + "s %s") % (tools.typeset("Notes:", Fore.RED),
  290. node.notes))
  291. print (tools.typeset("Tags: ", Fore.RED)),
  292. for t in node.tags:
  293. print (" %s " % t)
  294. print()
  295. def heardEnter():
  296. i, o, e = uselect.select([sys.stdin], [], [], 0.0001)
  297. for s in i:
  298. if s == sys.stdin:
  299. sys.stdin.readline()
  300. return True
  301. return False
  302. def waituntil_enter(somepredicate, timeout, period=0.25):
  303. mustend = time.time() + timeout
  304. while time.time() < mustend:
  305. cond = somepredicate()
  306. if cond:
  307. break
  308. time.sleep(period)
  309. self.do_cls('')
  310. try:
  311. flushtimeout = int(self.config.get_value("Global", "cls_timeout"))
  312. except ValueError:
  313. flushtimeout = 10
  314. if flushtimeout > 0:
  315. print ("Type Enter to flush screen (autoflash in "
  316. "%d sec.)" % flushtimeout)
  317. waituntil_enter(heardEnter, flushtimeout)
  318. def do_passwd(self, args):
  319. raise Exception("Not Implemented ...")
  320. #try:
  321. # key = self._db.changepassword()
  322. # self._db.savekey(key)
  323. #except Exception as e:
  324. # self.error(e)
  325. def do_tags(self, arg):
  326. enc = CryptoEngine.get()
  327. if not enc.alive():
  328. enc._getcipher()
  329. print ("Tags: \n",)
  330. t = self._tags(enc)
  331. print ('\n'.join(t))
  332. def get_tags(self, default=None, reader=raw_input):
  333. """read tags from user"""
  334. defaultstr = ''
  335. if default:
  336. for t in default:
  337. defaultstr += "%s " % (t)
  338. else:
  339. # tags = self._db.currenttags()
  340. tags = self._db._filtertags
  341. for t in tags:
  342. defaultstr += "%s " % (t)
  343. # strings = []
  344. tags = self._db.listtags(True)
  345. # for t in tags:
  346. # strings.append(t.get_name())
  347. # strings.append(t)
  348. strings = [t for t in tags]
  349. def complete(text, state):
  350. count = 0
  351. for s in strings:
  352. if s.startswith(text):
  353. if count == state:
  354. return s
  355. else:
  356. count += 1
  357. taglist = tools.getinput("Tags: ", defaultstr, completer=complete,
  358. reader=reader)
  359. tagstrings = taglist.split()
  360. tags = [TagNew(tn) for tn in tagstrings]
  361. return tags
  362. def do_list(self, args):
  363. if len(args.split()) > 0:
  364. self.do_clear('')
  365. self.do_filter(args)
  366. try:
  367. if sys.platform != 'win32':
  368. rows, cols = tools.gettermsize()
  369. else:
  370. rows, cols = 18, 80 # fix this !
  371. nodeids = self._db.listnodes()
  372. nodes = self._db.getnodes(nodeids)
  373. cols -= 8
  374. i = 0
  375. for n in nodes:
  376. tags = n.tags
  377. tags = filter(None, tags)
  378. tagstring = ''
  379. first = True
  380. for t in tags:
  381. if not first:
  382. tagstring += ", "
  383. else:
  384. first = False
  385. tagstring += t
  386. name = "%s@%s" % (n.username, n.url)
  387. name_len = cols * 2 / 3
  388. tagstring_len = cols / 3
  389. if len(name) > name_len:
  390. name = name[:name_len - 3] + "..."
  391. if len(tagstring) > tagstring_len:
  392. tagstring = tagstring[:tagstring_len - 3] + "..."
  393. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  394. formatted_entry = tools.typeset(fmt % (n._id,
  395. name, tagstring),
  396. Fore.YELLOW, False)
  397. print (formatted_entry)
  398. i += 1
  399. if i > rows - 2:
  400. i = 0
  401. c = tools.getonechar("Press <Space> for more,"
  402. " or 'Q' to cancel")
  403. if c.lower() == 'q':
  404. break
  405. except Exception as e:
  406. self.error(e)
  407. def do_filter(self, args):
  408. tagstrings = args.split()
  409. try:
  410. tags = [TagNew(ts) for ts in tagstrings]
  411. self._db.filter(tags)
  412. tags = self._db.currenttags()
  413. print ("Current tags: ",)
  414. if len(tags) == 0:
  415. print ("None",)
  416. for t in tags:
  417. print ("%s " % t.name.decode())
  418. print
  419. except Exception as e:
  420. self.error(e)
  421. def do_print(self, arg):
  422. for i in self.get_ids(arg):
  423. try:
  424. node = self._db.getnodes([i])
  425. self.print_node(node[0])
  426. # when done with node erase it
  427. zerome(node[0]._password)
  428. except Exception as e:
  429. self.error(e)
  430. def do_delete(self, arg):
  431. ids = self.get_ids(arg)
  432. try:
  433. nodes = self._db.getnodes(ids)
  434. for n in nodes:
  435. ans = ''
  436. while True:
  437. ans = tools.getinput(("Are you sure you want to"
  438. " delete '%s@%s' ([y/N])?"
  439. ) % (n.username, n.url)
  440. ).lower().strip('\n')
  441. if ans == '' or ans == 'y' or ans == 'n':
  442. break
  443. if ans == 'y':
  444. self._db.removenodes([n])
  445. print ("%s@%s deleted" % (n.username, n.url))
  446. except Exception as e:
  447. self.error(e)
  448. def get_ids(self, args):
  449. """
  450. Command can get a single ID or
  451. a range of IDs, with begin-end.
  452. e.g. 1-3 , will get 1 to 3.
  453. """
  454. ids = []
  455. rex = re.compile("^(?P<begin>\d+)(?:-(?P<end>\d+))?$")
  456. rex = rex.match(args)
  457. if hasattr(rex, 'groupdict'):
  458. try:
  459. begin = int(rex.groupdict()['begin'])
  460. end = int(rex.groupdict()['end'])
  461. if not end > begin:
  462. print("Start node should be smaller than end node")
  463. return ids
  464. ids += range(begin, end+1)
  465. return ids
  466. except TypeError:
  467. ids.append(int(begin))
  468. else:
  469. print("Could not understand your input...")
  470. return ids
  471. def get_password(self, argsgiven, numerics=False, leetify=False,
  472. symbols=False, special_signs=False,
  473. reader=getpass.getpass, length=None):
  474. return tools.getpassword("Password (Blank to generate): ",
  475. reader=reader, length=length, leetify=leetify,
  476. special_signs=special_signs, symbols=symbols,
  477. numerics=numerics, config=self.config)
  478. class Aliases(BaseCommands): # pragma: no cover
  479. """
  480. Define all the alias you want here...
  481. """
  482. def do_cp(self, args):
  483. self.do_copy(args)
  484. def do_e(self, arg):
  485. self.do_edit(arg)
  486. def do_EOF(self, args):
  487. return self.do_exit(args)
  488. def do_l(self, args):
  489. self.do_list(args)
  490. def do_ls(self, args):
  491. self.do_list(args)
  492. def do_p(self, arg):
  493. self.do_print(arg)
  494. def do_rm(self, arg):
  495. self.do_delete(arg)
  496. def do_o(self, args):
  497. self.do_open(args)
  498. def do_h(self, arg):
  499. self.do_help(arg)
  500. def do_n(self, arg):
  501. self.do_new(arg)