Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

default.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. # -*- test-case-name: twisted.conch.test.test_knownhosts,twisted.conch.test.test_default -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Various classes and functions for implementing user-interaction in the
  6. command-line conch client.
  7. You probably shouldn't use anything in this module directly, since it assumes
  8. you are sitting at an interactive terminal. For example, to programmatically
  9. interact with a known_hosts database, use L{twisted.conch.client.knownhosts}.
  10. """
  11. import contextlib
  12. import getpass
  13. import io
  14. import os
  15. import sys
  16. from base64 import decodebytes
  17. from twisted.conch.client import agent
  18. from twisted.conch.client.knownhosts import ConsoleUI, KnownHostsFile
  19. from twisted.conch.error import ConchError
  20. from twisted.conch.ssh import common, keys, userauth
  21. from twisted.internet import defer, protocol, reactor
  22. from twisted.python.compat import nativeString
  23. from twisted.python.filepath import FilePath
  24. # The default location of the known hosts file (probably should be parsed out
  25. # of an ssh config file someday).
  26. _KNOWN_HOSTS = "~/.ssh/known_hosts"
  27. # This name is bound so that the unit tests can use 'patch' to override it.
  28. _open = open
  29. _input = input
  30. def verifyHostKey(transport, host, pubKey, fingerprint):
  31. """
  32. Verify a host's key.
  33. This function is a gross vestige of some bad factoring in the client
  34. internals. The actual implementation, and a better signature of this logic
  35. is in L{KnownHostsFile.verifyHostKey}. This function is not deprecated yet
  36. because the callers have not yet been rehabilitated, but they should
  37. eventually be changed to call that method instead.
  38. However, this function does perform two functions not implemented by
  39. L{KnownHostsFile.verifyHostKey}. It determines the path to the user's
  40. known_hosts file based on the options (which should really be the options
  41. object's job), and it provides an opener to L{ConsoleUI} which opens
  42. '/dev/tty' so that the user will be prompted on the tty of the process even
  43. if the input and output of the process has been redirected. This latter
  44. part is, somewhat obviously, not portable, but I don't know of a portable
  45. equivalent that could be used.
  46. @param host: Due to a bug in L{SSHClientTransport.verifyHostKey}, this is
  47. always the dotted-quad IP address of the host being connected to.
  48. @type host: L{str}
  49. @param transport: the client transport which is attempting to connect to
  50. the given host.
  51. @type transport: L{SSHClientTransport}
  52. @param fingerprint: the fingerprint of the given public key, in
  53. xx:xx:xx:... format. This is ignored in favor of getting the fingerprint
  54. from the key itself.
  55. @type fingerprint: L{str}
  56. @param pubKey: The public key of the server being connected to.
  57. @type pubKey: L{str}
  58. @return: a L{Deferred} which fires with C{1} if the key was successfully
  59. verified, or fails if the key could not be successfully verified. Failure
  60. types may include L{HostKeyChanged}, L{UserRejectedKey}, L{IOError} or
  61. L{KeyboardInterrupt}.
  62. """
  63. actualHost = transport.factory.options["host"]
  64. actualKey = keys.Key.fromString(pubKey)
  65. kh = KnownHostsFile.fromPath(
  66. FilePath(
  67. transport.factory.options["known-hosts"] or os.path.expanduser(_KNOWN_HOSTS)
  68. )
  69. )
  70. ui = ConsoleUI(lambda: _open("/dev/tty", "r+b", buffering=0))
  71. return kh.verifyHostKey(ui, actualHost, host, actualKey)
  72. def isInKnownHosts(host, pubKey, options):
  73. """
  74. Checks to see if host is in the known_hosts file for the user.
  75. @return: 0 if it isn't, 1 if it is and is the same, 2 if it's changed.
  76. @rtype: L{int}
  77. """
  78. keyType = common.getNS(pubKey)[0]
  79. retVal = 0
  80. if not options["known-hosts"] and not os.path.exists(os.path.expanduser("~/.ssh/")):
  81. print("Creating ~/.ssh directory...")
  82. os.mkdir(os.path.expanduser("~/.ssh"))
  83. kh_file = options["known-hosts"] or _KNOWN_HOSTS
  84. try:
  85. known_hosts = open(os.path.expanduser(kh_file), "rb")
  86. except OSError:
  87. return 0
  88. with known_hosts:
  89. for line in known_hosts.readlines():
  90. split = line.split()
  91. if len(split) < 3:
  92. continue
  93. hosts, hostKeyType, encodedKey = split[:3]
  94. if host not in hosts.split(b","): # incorrect host
  95. continue
  96. if hostKeyType != keyType: # incorrect type of key
  97. continue
  98. try:
  99. decodedKey = decodebytes(encodedKey)
  100. except BaseException:
  101. continue
  102. if decodedKey == pubKey:
  103. return 1
  104. else:
  105. retVal = 2
  106. return retVal
  107. def getHostKeyAlgorithms(host, options):
  108. """
  109. Look in known_hosts for a key corresponding to C{host}.
  110. This can be used to change the order of supported key types
  111. in the KEXINIT packet.
  112. @type host: L{str}
  113. @param host: the host to check in known_hosts
  114. @type options: L{twisted.conch.client.options.ConchOptions}
  115. @param options: options passed to client
  116. @return: L{list} of L{str} representing key types or L{None}.
  117. """
  118. knownHosts = KnownHostsFile.fromPath(
  119. FilePath(options["known-hosts"] or os.path.expanduser(_KNOWN_HOSTS))
  120. )
  121. keyTypes = []
  122. for entry in knownHosts.iterentries():
  123. if entry.matchesHost(host):
  124. if entry.keyType not in keyTypes:
  125. keyTypes.append(entry.keyType)
  126. return keyTypes or None
  127. class SSHUserAuthClient(userauth.SSHUserAuthClient):
  128. def __init__(self, user, options, *args):
  129. userauth.SSHUserAuthClient.__init__(self, user, *args)
  130. self.keyAgent = None
  131. self.options = options
  132. self.usedFiles = []
  133. if not options.identitys:
  134. options.identitys = ["~/.ssh/id_rsa", "~/.ssh/id_dsa"]
  135. def serviceStarted(self):
  136. if "SSH_AUTH_SOCK" in os.environ and not self.options["noagent"]:
  137. self._log.debug(
  138. "using SSH agent {authSock!r}", authSock=os.environ["SSH_AUTH_SOCK"]
  139. )
  140. cc = protocol.ClientCreator(reactor, agent.SSHAgentClient)
  141. d = cc.connectUNIX(os.environ["SSH_AUTH_SOCK"])
  142. d.addCallback(self._setAgent)
  143. d.addErrback(self._ebSetAgent)
  144. else:
  145. userauth.SSHUserAuthClient.serviceStarted(self)
  146. def serviceStopped(self):
  147. if self.keyAgent:
  148. self.keyAgent.transport.loseConnection()
  149. self.keyAgent = None
  150. def _setAgent(self, a):
  151. self.keyAgent = a
  152. d = self.keyAgent.getPublicKeys()
  153. d.addBoth(self._ebSetAgent)
  154. return d
  155. def _ebSetAgent(self, f):
  156. userauth.SSHUserAuthClient.serviceStarted(self)
  157. def _getPassword(self, prompt):
  158. """
  159. Prompt for a password using L{getpass.getpass}.
  160. @param prompt: Written on tty to ask for the input.
  161. @type prompt: L{str}
  162. @return: The input.
  163. @rtype: L{str}
  164. """
  165. with self._replaceStdoutStdin():
  166. try:
  167. p = getpass.getpass(prompt)
  168. return p
  169. except (KeyboardInterrupt, OSError):
  170. print()
  171. raise ConchError("PEBKAC")
  172. def getPassword(self, prompt=None):
  173. if prompt:
  174. prompt = nativeString(prompt)
  175. else:
  176. prompt = "{}@{}'s password: ".format(
  177. nativeString(self.user),
  178. self.transport.transport.getPeer().host,
  179. )
  180. try:
  181. # We don't know the encoding the other side is using,
  182. # signaling that is not part of the SSH protocol. But
  183. # using our defaultencoding is better than just going for
  184. # ASCII.
  185. p = self._getPassword(prompt).encode(sys.getdefaultencoding())
  186. return defer.succeed(p)
  187. except ConchError:
  188. return defer.fail()
  189. def getPublicKey(self):
  190. """
  191. Get a public key from the key agent if possible, otherwise look in
  192. the next configured identity file for one.
  193. """
  194. if self.keyAgent:
  195. key = self.keyAgent.getPublicKey()
  196. if key is not None:
  197. return key
  198. files = [x for x in self.options.identitys if x not in self.usedFiles]
  199. self._log.debug(
  200. "public key identities: {identities}\n{files}",
  201. identities=self.options.identitys,
  202. files=files,
  203. )
  204. if not files:
  205. return None
  206. file = files[0]
  207. self.usedFiles.append(file)
  208. file = os.path.expanduser(file)
  209. file += ".pub"
  210. if not os.path.exists(file):
  211. return self.getPublicKey() # try again
  212. try:
  213. return keys.Key.fromFile(file)
  214. except keys.BadKeyError:
  215. return self.getPublicKey() # try again
  216. def signData(self, publicKey, signData):
  217. """
  218. Extend the base signing behavior by using an SSH agent to sign the
  219. data, if one is available.
  220. @type publicKey: L{Key}
  221. @type signData: L{bytes}
  222. """
  223. if not self.usedFiles: # agent key
  224. return self.keyAgent.signData(publicKey.blob(), signData)
  225. else:
  226. return userauth.SSHUserAuthClient.signData(self, publicKey, signData)
  227. def getPrivateKey(self):
  228. """
  229. Try to load the private key from the last used file identified by
  230. C{getPublicKey}, potentially asking for the passphrase if the key is
  231. encrypted.
  232. """
  233. file = os.path.expanduser(self.usedFiles[-1])
  234. if not os.path.exists(file):
  235. return None
  236. try:
  237. return defer.succeed(keys.Key.fromFile(file))
  238. except keys.EncryptedKeyError:
  239. for i in range(3):
  240. prompt = "Enter passphrase for key '%s': " % self.usedFiles[-1]
  241. try:
  242. p = self._getPassword(prompt).encode(sys.getfilesystemencoding())
  243. return defer.succeed(keys.Key.fromFile(file, passphrase=p))
  244. except (keys.BadKeyError, ConchError):
  245. pass
  246. return defer.fail(ConchError("bad password"))
  247. raise
  248. except KeyboardInterrupt:
  249. print()
  250. reactor.stop()
  251. def getGenericAnswers(self, name, instruction, prompts):
  252. responses = []
  253. with self._replaceStdoutStdin():
  254. if name:
  255. print(name.decode("utf-8"))
  256. if instruction:
  257. print(instruction.decode("utf-8"))
  258. for prompt, echo in prompts:
  259. prompt = prompt.decode("utf-8")
  260. if echo:
  261. responses.append(_input(prompt))
  262. else:
  263. responses.append(getpass.getpass(prompt))
  264. return defer.succeed(responses)
  265. @classmethod
  266. def _openTty(cls):
  267. """
  268. Open /dev/tty as two streams one in read, one in write mode,
  269. and return them.
  270. @return: File objects for reading and writing to /dev/tty,
  271. corresponding to standard input and standard output.
  272. @rtype: A L{tuple} of L{io.TextIOWrapper} on Python 3.
  273. """
  274. stdin = io.TextIOWrapper(open("/dev/tty", "rb"))
  275. stdout = io.TextIOWrapper(open("/dev/tty", "wb"))
  276. return stdin, stdout
  277. @classmethod
  278. @contextlib.contextmanager
  279. def _replaceStdoutStdin(cls):
  280. """
  281. Contextmanager that replaces stdout and stdin with /dev/tty
  282. and resets them when it is done.
  283. """
  284. oldout, oldin = sys.stdout, sys.stdin
  285. sys.stdin, sys.stdout = cls._openTty()
  286. try:
  287. yield
  288. finally:
  289. sys.stdout.close()
  290. sys.stdin.close()
  291. sys.stdout, sys.stdin = oldout, oldin