base.py 22 KB

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