base.py 22 KB

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