win.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. """
  2. # ============================================================================
  3. # This file is part of Pwman3.
  4. #
  5. # Pwman3 is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License, version 2
  7. # as published by the Free Software Foundation;
  8. #
  9. # Pwman3 is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with Pwman3; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  17. # ============================================================================
  18. # Copyright (C) 2012 Oz Nahum <nahumoz@gmail.com>
  19. # ============================================================================
  20. # Copyright (C) 2006 Ivan Kelly <ivan@ivankelly.net>
  21. # ============================================================================
  22. """
  23. from __future__ import print_function
  24. import time
  25. import ctypes
  26. import ast
  27. import os
  28. try:
  29. import msvcrt
  30. except ImportError:
  31. pass
  32. from colorama import Fore
  33. import pwman.util.config as config
  34. from pwman.ui.cli import PwmanCli
  35. from pwman.data.nodes import Node
  36. from pwman.ui import tools
  37. from pwman.util.crypto_engine import zerome
  38. from pwman.util.crypto_engine import CryptoEngine
  39. def winGetClipboard():
  40. ctypes.windll.user32.OpenClipboard(0)
  41. pcontents = ctypes.windll.user32.GetClipboardData(1) # 1 is CF_TEXT
  42. data = ctypes.c_char_p(pcontents).value
  43. #ctypes.windll.kernel32.GlobalUnlock(pcontents)
  44. ctypes.windll.user32.CloseClipboard()
  45. return data
  46. def winSetClipboard(text):
  47. text = str(text)
  48. GMEM_DDESHARE = 0x2000
  49. ctypes.windll.user32.OpenClipboard(0)
  50. ctypes.windll.user32.EmptyClipboard()
  51. try:
  52. # works on Python 2 (bytes() only takes one argument)
  53. hCd = ctypes.windll.kernel32.GlobalAlloc(GMEM_DDESHARE,
  54. len(bytes(text))+1)
  55. except TypeError:
  56. # works on Python 3 (bytes() requires an encoding)
  57. hCd = ctypes.windll.kernel32.GlobalAlloc(GMEM_DDESHARE,
  58. len(bytes(text, 'ascii'))+1)
  59. pchData = ctypes.windll.kernel32.GlobalLock(hCd)
  60. try:
  61. # works on Python 2 (bytes() only takes one argument)
  62. ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text))
  63. except TypeError:
  64. # works on Python 3 (bytes() requires an encoding)
  65. ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData),
  66. bytes(text, 'ascii'))
  67. ctypes.windll.kernel32.GlobalUnlock(hCd)
  68. ctypes.windll.user32.SetClipboardData(1, hCd)
  69. ctypes.windll.user32.CloseClipboard()
  70. class PwmanCliWin(PwmanCli):
  71. """
  72. windows ui class
  73. """
  74. def do_new(self, args):
  75. """
  76. can override default config settings the following way:
  77. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  78. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  79. Password (Blank to generate):
  80. """
  81. errmsg = """could not parse config override, please input some"""\
  82. + """ kind of dictionary, e.g.: n {'leetify':False, """\
  83. + """'numerics':True, 'special_chars':True}"""
  84. try:
  85. username = self.get_username()
  86. if args:
  87. try:
  88. args = ast.literal_eval(args)
  89. except Exception:
  90. raise Exception(errmsg)
  91. if not isinstance(args, dict):
  92. raise Exception(errmsg)
  93. password = self.get_password(1, **args)
  94. else:
  95. numerics = config.get_value(
  96. "Generator", "numerics").lower() == 'true'
  97. # TODO: allow custom leetifying through the config
  98. leetify = config.get_value(
  99. "Generator", "leetify").lower() == 'true'
  100. special_chars = config.get_value(
  101. "Generator", "special_chars").lower() == 'true'
  102. password = self.get_password(0,
  103. numerics=numerics,
  104. symbols=leetify,
  105. special_signs=special_chars)
  106. url = self.get_url()
  107. notes = self.get_notes()
  108. node = Node()
  109. node.username = username
  110. node.password = password
  111. node.url = url
  112. node.notes = notes
  113. tags = self.get_tags()
  114. node.tags = tags
  115. self._db.addnodes([node])
  116. print("Password ID: %d" % (node._id))
  117. # when done with node erase it
  118. zerome(password)
  119. except Exception as e:
  120. self.error(e)
  121. def print_node(self, node):
  122. width = tools._defaultwidth
  123. print("Node {}.".format(node._id))
  124. print("{} {}".format(tools.typeset("Username:", Fore.RED).ljust(width),
  125. node.username))
  126. print ("{} {}".format(tools.typeset("Password:",
  127. Fore.RED).ljust(width),
  128. node.password))
  129. print("{} {}".format(tools.typeset("Url:", Fore.RED).ljust(width),
  130. node.url))
  131. print("{} {}".format(tools.typeset("Notes:", Fore.RED).ljust(width),
  132. node.notes))
  133. print("{}".format(tools.typeset("Tags: ", Fore.RED)), end=" ")
  134. for t in node.tags:
  135. print(t)
  136. def heardEnterWin():
  137. c = msvcrt.kbhit()
  138. if c == 1:
  139. ret = msvcrt.getch()
  140. if ret is not None:
  141. return True
  142. return False
  143. def waituntil_enter(somepredicate, timeout, period=0.25):
  144. mustend = time.time() + timeout
  145. while time.time() < mustend:
  146. cond = somepredicate()
  147. if cond:
  148. break
  149. time.sleep(period)
  150. self.do_cls('')
  151. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  152. if flushtimeout > 0:
  153. print("Press any key to flush screen (autoflash "
  154. "in %d sec.)" % flushtimeout)
  155. waituntil_enter(heardEnterWin, flushtimeout)
  156. def do_copy(self, args):
  157. ids = self._get_ids(args)
  158. if len(ids) > 1:
  159. print ("Can copy only 1 password at a time...")
  160. return None
  161. ce = CryptoEngine.get()
  162. nodes = self._db.getnodes(ids)
  163. for node in nodes:
  164. password = ce.decrypt(node[2])
  165. winSetClipboard(password)
  166. print("erasing in 10 sec...")
  167. time.sleep(10)
  168. winSetClipboard("")
  169. def do_open(self, args):
  170. ids = self._get_ids(args)
  171. if not args:
  172. self.help_open()
  173. return
  174. if len(ids) > 1:
  175. print ("Can open only 1 link at a time ...")
  176. return None
  177. try:
  178. node = self._db.getnodes(ids)
  179. url = node[0].url
  180. if not url.startswith(("http://", "https://")):
  181. url = "https://" + url
  182. os.system("start "+url)
  183. except Exception as e:
  184. self.error(e)
  185. def do_cls(self, args):
  186. os.system('cls')