base.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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_save(self):
  119. self.usage("save [filename]")
  120. print("Saves the current configuration to [filename]. If no filename ",
  121. "is given, the configuration is saved to the file from which ",
  122. "the initial configuration was loaded.")
  123. def help_set(self):
  124. self.usage("set [configoption] [value]")
  125. print("Sets a configuration option. If no value is specified, the ",
  126. "current value for [configoption] is output. If neither ",
  127. "[configoption] nor [value] are specified, the whole current ",
  128. "configuration is output. [configoption] must be of the ",
  129. "format <section>.<option>")
  130. def help_passwd(self):
  131. self.usage("passwd")
  132. print("Changes the password on the database. ")
  133. def help_forget(self):
  134. self.usage("forget")
  135. print("Forgets the database password. Your password will need to ",
  136. "be reentered before accessing the database again.")
  137. def help_clear(self):
  138. self.usage("clear")
  139. print("Clears the filter criteria. ")
  140. def help_filter(self):
  141. self.usage("filter <tag> ...")
  142. print("Filters nodes on tag. Arguments can be zero or more tags. ",
  143. "Displays current tags if called without arguments.")
  144. def help_tags(self):
  145. self.usage("tags")
  146. print("Displays all tags in used in the database.")
  147. class BaseUI(object):
  148. """
  149. this class holds all the UI functionality
  150. in PwmanCliNew. The later inherits from this class
  151. and allows it to print messages to the console.
  152. """
  153. def _do_filter(self, args):
  154. pass
  155. def _tags(self, enc):
  156. """
  157. read tags from TAGS table in DB,
  158. """
  159. tags = self._db.listtags()
  160. if tags:
  161. _tags = [''] * len(tags)
  162. for t in tags:
  163. try:
  164. _tags.append(enc.decrypt(t))
  165. except (ValueError, Exception) as e:
  166. _tags.append(t)
  167. del(e)
  168. _tags = filter(None, _tags)
  169. _tags = list(_tags)
  170. return _tags
  171. # pylint: disable=R0904
  172. class BaseCommands(BaseUI, HelpUI):
  173. """
  174. Inherit from the old class, override
  175. all the methods related to tags, and
  176. newer Node format, so backward compatability is kept...
  177. Commands defined here, can have aliases definded in Aliases.
  178. You can define the aliases here too, but it makes
  179. the class code really long and unclear.
  180. """
  181. def error(self, exception):
  182. if (isinstance(exception, KeyboardInterrupt)):
  183. print('')
  184. else:
  185. print("Error: {0} ".format(exception))
  186. def do_copy(self, args):
  187. if self.hasxsel:
  188. ids = self.get_ids(args)
  189. if len(ids) > 1:
  190. print ("Can copy only 1 password at a time...")
  191. return None
  192. try:
  193. node = self._db.getnodes(ids)
  194. tools.text_to_clipboards(node[0].password)
  195. print("copied password for {}@{} clipboard".format(
  196. node[0].username, node[0].url))
  197. print("erasing in 10 sec...")
  198. time.sleep(10)
  199. tools.text_to_clipboards("")
  200. except Exception as e:
  201. self.error(e)
  202. else:
  203. print ("Can't copy to clipboard, no xsel found in the system!")
  204. def do_exit(self, args):
  205. """exit the ui"""
  206. self._db.close()
  207. return True
  208. def do_export(self, args):
  209. try:
  210. args = ast.literal_eval(args)
  211. except Exception:
  212. args = {}
  213. filename = args.get('filename', 'pwman-export.csv')
  214. delim = args.get('delimiter', ';')
  215. nodeids = self._db.listnodes()
  216. nodes = self._db.getnodes(nodeids)
  217. with open(filename, 'w') as csvfile:
  218. writer = csv.writer(csvfile, delimiter=delim)
  219. writer.writerow(['Username', 'URL', 'Password', 'Notes',
  220. 'Tags'])
  221. for n in nodes:
  222. tags = n.tags
  223. tags = filter(None, tags)
  224. tags = ','.join(t.strip() for t in tags)
  225. writer.writerow([n.username, n.url, n.password, n.notes,
  226. tags])
  227. print("Successfuly exported database to {}".format(
  228. os.path.join(os.getcwd(), filename)))
  229. def do_forget(self, args):
  230. try:
  231. enc = CryptoEngine.get()
  232. enc.forget()
  233. except Exception as e:
  234. self.error(e)
  235. def do_set(self, args):
  236. argstrs = args.split()
  237. try:
  238. if len(argstrs) == 0:
  239. conf = config.get_conf()
  240. for s in conf.keys():
  241. for n in conf[s].keys():
  242. print ("%s.%s = %s" % (s, n, conf[s][n]))
  243. elif len(argstrs) == 1:
  244. r = re.compile("(.+)\.(.+)")
  245. m = r.match(argstrs[0])
  246. if m is None or len(m.groups()) != 2:
  247. print ("Invalid option format")
  248. self.help_set()
  249. return
  250. print ("%s.%s = %s" % (m.group(1), m.group(2),
  251. config.get_value(m.group(1),
  252. m.group(2))))
  253. elif len(argstrs) == 2:
  254. r = re.compile("(.+)\.(.+)")
  255. m = r.match(argstrs[0])
  256. if m is None or len(m.groups()) != 2:
  257. print ("Invalid option format")
  258. self.help_set()
  259. return
  260. config.set_value(m.group(1), m.group(2), argstrs[1])
  261. else:
  262. self.help_set()
  263. except Exception as e:
  264. self.error(e)
  265. def get_username(self, default="", reader=raw_input):
  266. return tools.getinput("Username: ", default, reader)
  267. def get_url(self, default="", reader=raw_input):
  268. return tools.getinput("Url: ", default, reader)
  269. def get_notes(self, default="", reader=raw_input):
  270. return tools.getinput("Notes: ", default, reader)
  271. def do_open(self, args):
  272. ids = self.get_ids(args)
  273. if not args:
  274. self.help_open()
  275. return
  276. if len(ids) > 1:
  277. print ("Can open only 1 link at a time ...")
  278. return None
  279. try:
  280. node = self._db.getnodes(ids)
  281. url = node[0].url
  282. tools.open_url(url)
  283. except Exception as e:
  284. self.error(e)
  285. def do_clear(self, args):
  286. try:
  287. self._db.clearfilter()
  288. except Exception as e:
  289. self.error(e)
  290. def do_cls(self, args):
  291. os.system('clear')
  292. def do_edit(self, arg, menu=None):
  293. ids = self.get_ids(arg)
  294. for i in ids:
  295. try:
  296. i = int(i)
  297. node = self._db.getnodes([i])[0]
  298. if not menu:
  299. menu = CMDLoop()
  300. print ("Editing node %d." % (i))
  301. menu.add(CliMenuItem("Username", self.get_username,
  302. node.username,
  303. node.username))
  304. menu.add(CliMenuItem("Password", self.get_password,
  305. node.password,
  306. node.password))
  307. menu.add(CliMenuItem("Url", self.get_url,
  308. node.url,
  309. node.url))
  310. menunotes = CliMenuItem("Notes", self.get_notes,
  311. node.notes,
  312. node.notes)
  313. menu.add(menunotes)
  314. menu.add(CliMenuItem("Tags", self.get_tags,
  315. node.tags,
  316. node.tags))
  317. menu.run(node)
  318. self._db.editnode(i, node)
  319. # when done with node erase it
  320. zerome(node._password)
  321. except Exception as e:
  322. self.error(e)
  323. def print_node(self, node):
  324. width = str(tools._defaultwidth)
  325. print ("Node %d." % (node._id))
  326. print (("%" + width + "s %s") % (tools.typeset("Username:", Fore.RED),
  327. node.username))
  328. print (("%" + width + "s %s") % (tools.typeset("Password:", Fore.RED),
  329. node.password))
  330. print (("%" + width + "s %s") % (tools.typeset("Url:", Fore.RED),
  331. node.url))
  332. print (("%" + width + "s %s") % (tools.typeset("Notes:", Fore.RED),
  333. node.notes))
  334. print (tools.typeset("Tags: ", Fore.RED)),
  335. for t in node.tags:
  336. print (" %s " % t)
  337. print()
  338. def heardEnter():
  339. i, o, e = uselect.select([sys.stdin], [], [], 0.0001)
  340. for s in i:
  341. if s == sys.stdin:
  342. sys.stdin.readline()
  343. return True
  344. return False
  345. def waituntil_enter(somepredicate, timeout, period=0.25):
  346. mustend = time.time() + timeout
  347. while time.time() < mustend:
  348. cond = somepredicate()
  349. if cond:
  350. break
  351. time.sleep(period)
  352. self.do_cls('')
  353. try:
  354. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  355. except ValueError:
  356. flushtimeout = 10
  357. if flushtimeout > 0:
  358. print ("Type Enter to flush screen (autoflash in "
  359. "%d sec.)" % flushtimeout)
  360. waituntil_enter(heardEnter, flushtimeout)
  361. def do_passwd(self, args):
  362. raise Exception("Not Implemented ...")
  363. #try:
  364. # key = self._db.changepassword()
  365. # self._db.savekey(key)
  366. #except Exception as e:
  367. # self.error(e)
  368. def do_save(self, args):
  369. argstrs = args.split()
  370. try:
  371. if len(argstrs) > 0:
  372. config.save(argstrs[0])
  373. else:
  374. config.save()
  375. print ("Config saved.")
  376. except Exception as e:
  377. self.error(e)
  378. def do_tags(self, arg):
  379. enc = CryptoEngine.get()
  380. if not enc.alive():
  381. enc._getcipher()
  382. print ("Tags: \n",)
  383. t = self._tags(enc)
  384. print ('\n'.join(t))
  385. def get_tags(self, default=None, reader=raw_input):
  386. """read tags from user"""
  387. defaultstr = ''
  388. if default:
  389. for t in default:
  390. defaultstr += "%s " % (t)
  391. else:
  392. # tags = self._db.currenttags()
  393. tags = self._db._filtertags
  394. for t in tags:
  395. defaultstr += "%s " % (t)
  396. # strings = []
  397. tags = self._db.listtags(True)
  398. # for t in tags:
  399. # strings.append(t.get_name())
  400. # strings.append(t)
  401. strings = [t for t in tags]
  402. def complete(text, state):
  403. count = 0
  404. for s in strings:
  405. if s.startswith(text):
  406. if count == state:
  407. return s
  408. else:
  409. count += 1
  410. taglist = tools.getinput("Tags: ", defaultstr, completer=complete,
  411. reader=reader)
  412. tagstrings = taglist.split()
  413. tags = [TagNew(tn) for tn in tagstrings]
  414. return tags
  415. def do_list(self, args):
  416. if len(args.split()) > 0:
  417. self.do_clear('')
  418. self.do_filter(args)
  419. try:
  420. if sys.platform != 'win32':
  421. rows, cols = tools.gettermsize()
  422. else:
  423. rows, cols = 18, 80 # fix this !
  424. nodeids = self._db.listnodes()
  425. nodes = self._db.getnodes(nodeids)
  426. cols -= 8
  427. i = 0
  428. for n in nodes:
  429. tags = n.tags
  430. tags = filter(None, tags)
  431. tagstring = ''
  432. first = True
  433. for t in tags:
  434. if not first:
  435. tagstring += ", "
  436. else:
  437. first = False
  438. tagstring += t
  439. name = "%s@%s" % (n.username, n.url)
  440. name_len = cols * 2 / 3
  441. tagstring_len = cols / 3
  442. if len(name) > name_len:
  443. name = name[:name_len - 3] + "..."
  444. if len(tagstring) > tagstring_len:
  445. tagstring = tagstring[:tagstring_len - 3] + "..."
  446. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  447. formatted_entry = tools.typeset(fmt % (n._id,
  448. name, tagstring),
  449. Fore.YELLOW, False)
  450. print (formatted_entry)
  451. i += 1
  452. if i > rows - 2:
  453. i = 0
  454. c = tools.getonechar("Press <Space> for more,"
  455. " or 'Q' to cancel")
  456. if c.lower() == 'q':
  457. break
  458. except Exception as e:
  459. self.error(e)
  460. def do_filter(self, args):
  461. tagstrings = args.split()
  462. try:
  463. tags = [TagNew(ts) for ts in tagstrings]
  464. self._db.filter(tags)
  465. tags = self._db.currenttags()
  466. print ("Current tags: ",)
  467. if len(tags) == 0:
  468. print ("None",)
  469. for t in tags:
  470. print ("%s " % t.name.decode())
  471. print
  472. except Exception as e:
  473. self.error(e)
  474. def do_new(self, args):
  475. """
  476. can override default config settings the following way:
  477. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  478. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  479. Password (Blank to generate):
  480. """
  481. errmsg = ("could not parse config override, please input some"
  482. " kind of dictionary, e.g.: n {'leetify':False, "
  483. " numerics':True, 'special_chars':True}")
  484. try:
  485. username = self.get_username()
  486. if args:
  487. try:
  488. args = ast.literal_eval(args)
  489. except Exception:
  490. raise Exception(errmsg)
  491. if not isinstance(args, dict):
  492. raise Exception(errmsg)
  493. password = self.get_password(argsgiven=1, **args)
  494. else:
  495. numerics, leet, s_chars = get_pass_conf()
  496. password = self.get_password(argsgiven=0,
  497. numerics=numerics,
  498. leetify=leet,
  499. special_signs=s_chars)
  500. url = self.get_url()
  501. notes = self.get_notes()
  502. node = NewNode()
  503. node.username = username
  504. node.password = password
  505. node.url = url
  506. node.notes = notes
  507. # node = NewNode(username, password, url, notes)
  508. node.tags = self.get_tags()
  509. self._db.addnodes([node])
  510. print ("Password ID: %d" % (node._id))
  511. # when done with node erase it
  512. zerome(password)
  513. except Exception as e:
  514. self.error(e)
  515. def do_print(self, arg):
  516. for i in self.get_ids(arg):
  517. try:
  518. node = self._db.getnodes([i])
  519. self.print_node(node[0])
  520. # when done with node erase it
  521. zerome(node[0]._password)
  522. except Exception as e:
  523. self.error(e)
  524. def do_delete(self, arg):
  525. ids = self.get_ids(arg)
  526. try:
  527. nodes = self._db.getnodes(ids)
  528. for n in nodes:
  529. ans = ''
  530. while True:
  531. ans = tools.getinput(("Are you sure you want to"
  532. " delete '%s@%s' ([y/N])?"
  533. ) % (n.username, n.url)
  534. ).lower().strip('\n')
  535. if ans == '' or ans == 'y' or ans == 'n':
  536. break
  537. if ans == 'y':
  538. self._db.removenodes([n])
  539. print ("%s@%s deleted" % (n.username, n.url))
  540. except Exception as e:
  541. self.error(e)
  542. def get_ids(self, args):
  543. """
  544. Command can get a single ID or
  545. a range of IDs, with begin-end.
  546. e.g. 1-3 , will get 1 to 3.
  547. """
  548. ids = []
  549. rex = re.compile("^(?P<begin>\d+)(?:-(?P<end>\d+))?$")
  550. rex = rex.match(args)
  551. if hasattr(rex, 'groupdict'):
  552. try:
  553. begin = int(rex.groupdict()['begin'])
  554. end = int(rex.groupdict()['end'])
  555. if not end > begin:
  556. print("Start node should be smaller than end node")
  557. return ids
  558. ids += range(begin, end+1)
  559. return ids
  560. except TypeError:
  561. ids.append(int(begin))
  562. else:
  563. print("Could not understand your input...")
  564. return ids
  565. def get_password(self, argsgiven, numerics=False, leetify=False,
  566. symbols=False, special_signs=False,
  567. reader=getpass.getpass, length=None):
  568. return tools.getpassword("Password (Blank to generate): ",
  569. reader=reader, length=length, leetify=leetify,
  570. special_signs=special_signs, symbols=symbols,
  571. numerics=numerics)
  572. class Aliases(BaseCommands): # pragma: no cover
  573. """
  574. Define all the alias you want here...
  575. """
  576. def do_cp(self, args):
  577. self.do_copy(args)
  578. def do_e(self, arg):
  579. self.do_edit(arg)
  580. def do_EOF(self, args):
  581. return self.do_exit(args)
  582. def do_l(self, args):
  583. self.do_list(args)
  584. def do_ls(self, args):
  585. self.do_list(args)
  586. def do_p(self, arg):
  587. self.do_print(arg)
  588. def do_rm(self, arg):
  589. self.do_delete(arg)
  590. def do_o(self, args):
  591. self.do_open(args)
  592. def do_h(self, arg):
  593. self.do_help(arg)
  594. def do_n(self, arg):
  595. self.do_new(arg)