base.py 20 KB

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