test_endpoints.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for L{twisted.conch.endpoints}.
  5. """
  6. import os.path
  7. from struct import pack
  8. from errno import ENOSYS
  9. from zope.interface.verify import verifyObject, verifyClass
  10. from zope.interface import implementer
  11. from twisted.python.compat import networkString, iteritems
  12. from twisted.python.failure import Failure
  13. from twisted.python.filepath import FilePath
  14. from twisted.python.log import msg
  15. from twisted.python.reflect import requireModule
  16. from twisted.internet.interfaces import IAddress, IStreamClientEndpoint
  17. from twisted.internet.protocol import Factory, Protocol
  18. from twisted.internet.defer import CancelledError, Deferred, succeed, fail
  19. from twisted.internet.error import ConnectionDone, ConnectionRefusedError
  20. from twisted.internet.address import IPv4Address
  21. from twisted.trial.unittest import TestCase
  22. from twisted.test.proto_helpers import MemoryReactorClock
  23. from twisted.internet.error import ProcessTerminated, ConnectingCancelledError
  24. from twisted.cred.portal import Portal
  25. from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
  26. from twisted.conch.interfaces import IConchUser
  27. from twisted.conch.error import ConchError, UserRejectedKey, HostKeyChanged
  28. if requireModule('cryptography') and requireModule('pyasn1.type'):
  29. from twisted.conch.ssh.factory import SSHFactory
  30. from twisted.conch.ssh.userauth import SSHUserAuthServer
  31. from twisted.conch.ssh.connection import SSHConnection
  32. from twisted.conch.ssh.keys import Key
  33. from twisted.conch.ssh.channel import SSHChannel
  34. from twisted.conch.ssh.agent import SSHAgentServer
  35. from twisted.conch.client.knownhosts import KnownHostsFile, ConsoleUI
  36. from twisted.conch.checkers import SSHPublicKeyChecker, InMemorySSHKeyDB
  37. from twisted.conch.avatar import ConchUser
  38. from twisted.conch.test.keydata import (
  39. publicRSA_openssh, privateRSA_openssh,
  40. privateRSA_openssh_encrypted_aes,
  41. privateDSA_openssh)
  42. from twisted.conch.endpoints import (
  43. _ISSHConnectionCreator, AuthenticationFailed, SSHCommandAddress,
  44. SSHCommandClientEndpoint, _ReadFile, _NewConnectionHelper,
  45. _ExistingConnectionHelper)
  46. from twisted.conch.ssh.transport import SSHClientTransport
  47. else:
  48. skip = "can't run w/o cryptography and pyasn1"
  49. SSHFactory = SSHUserAuthServer = SSHConnection = Key = SSHChannel = \
  50. SSHAgentServer = KnownHostsFile = SSHPublicKeyChecker = ConchUser = \
  51. object
  52. from twisted.test.proto_helpers import StringTransport
  53. from twisted.test.iosim import FakeTransport, connect
  54. class AbortableFakeTransport(FakeTransport):
  55. """
  56. A L{FakeTransport} with added C{abortConnection} support.
  57. """
  58. aborted = False
  59. def abortConnection(self):
  60. """
  61. Abort the connection in a fake manner.
  62. This should really be implemented in the underlying module.
  63. """
  64. self.aborted = True
  65. class BrokenExecSession(SSHChannel):
  66. """
  67. L{BrokenExecSession} is a session on which exec requests always fail.
  68. """
  69. def request_exec(self, data):
  70. """
  71. Fail all exec requests.
  72. @param data: Information about what is being executed.
  73. @type data: L{bytes}
  74. @return: C{0} to indicate failure
  75. @rtype: L{int}
  76. """
  77. return 0
  78. class WorkingExecSession(SSHChannel):
  79. """
  80. L{WorkingExecSession} is a session on which exec requests always succeed.
  81. """
  82. def request_exec(self, data):
  83. """
  84. Succeed all exec requests.
  85. @param data: Information about what is being executed.
  86. @type data: L{bytes}
  87. @return: C{1} to indicate success
  88. @rtype: L{int}
  89. """
  90. return 1
  91. class UnsatisfiedExecSession(SSHChannel):
  92. """
  93. L{UnsatisfiedExecSession} is a session on which exec requests are always
  94. delayed indefinitely, never succeeding or failing.
  95. """
  96. def request_exec(self, data):
  97. """
  98. Delay all exec requests indefinitely.
  99. @param data: Information about what is being executed.
  100. @type data: L{bytes}
  101. @return: A L{Deferred} which will never fire.
  102. @rtype: L{Deferred}
  103. """
  104. return Deferred()
  105. class TrivialRealm(object):
  106. def __init__(self):
  107. self.channelLookup = {}
  108. def requestAvatar(self, avatarId, mind, *interfaces):
  109. avatar = ConchUser()
  110. avatar.channelLookup = self.channelLookup
  111. return (IConchUser, avatar, lambda: None)
  112. class AddressSpyFactory(Factory):
  113. address = None
  114. def buildProtocol(self, address):
  115. self.address = address
  116. return Factory.buildProtocol(self, address)
  117. class FixedResponseUI(object):
  118. def __init__(self, result):
  119. self.result = result
  120. def prompt(self, text):
  121. return succeed(self.result)
  122. def warn(self, text):
  123. pass
  124. class FakeClockSSHUserAuthServer(SSHUserAuthServer):
  125. # Delegate this setting to the factory to simplify tweaking it
  126. @property
  127. def attemptsBeforeDisconnect(self):
  128. """
  129. Use the C{attemptsBeforeDisconnect} value defined by the factory to make
  130. it easier to override.
  131. """
  132. return self.transport.factory.attemptsBeforeDisconnect
  133. @property
  134. def clock(self):
  135. """
  136. Use the reactor defined by the factory, rather than the default global
  137. reactor, to simplify testing (by allowing an alternate implementation
  138. to be supplied by tests).
  139. """
  140. return self.transport.factory.reactor
  141. class CommandFactory(SSHFactory):
  142. @property
  143. def publicKeys(self):
  144. return {
  145. b'ssh-rsa': Key.fromString(data=publicRSA_openssh)
  146. }
  147. @property
  148. def privateKeys(self):
  149. return {
  150. b'ssh-rsa': Key.fromString(data=privateRSA_openssh)
  151. }
  152. services = {
  153. b'ssh-userauth': FakeClockSSHUserAuthServer,
  154. b'ssh-connection': SSHConnection
  155. }
  156. # Simplify the tests by disconnecting after the first authentication
  157. # failure. One attempt should be sufficient to test authentication success
  158. # and failure. There is an off-by-one in the implementation of this
  159. # feature in Conch, so set it to 0 in order to allow 1 attempt.
  160. attemptsBeforeDisconnect = 0
  161. @implementer(IAddress)
  162. class MemoryAddress(object):
  163. pass
  164. @implementer(IStreamClientEndpoint)
  165. class SingleUseMemoryEndpoint(object):
  166. """
  167. L{SingleUseMemoryEndpoint} is a client endpoint which allows one connection
  168. to be set up and then exposes an API for moving around bytes related to
  169. that connection.
  170. @ivar pump: L{None} until a connection is attempted, then a L{IOPump}
  171. instance associated with the protocol which is connected.
  172. @type pump: L{IOPump}
  173. """
  174. def __init__(self, server):
  175. """
  176. @param server: An L{IProtocol} provider to which the client will be
  177. connected.
  178. @type server: L{IProtocol} provider
  179. """
  180. self.pump = None
  181. self._server = server
  182. def connect(self, factory):
  183. if self.pump is not None:
  184. raise Exception("SingleUseMemoryEndpoint was already used")
  185. try:
  186. protocol = factory.buildProtocol(MemoryAddress())
  187. except:
  188. return fail()
  189. else:
  190. self.pump = connect(
  191. self._server, AbortableFakeTransport(
  192. self._server, isServer=True),
  193. protocol, AbortableFakeTransport(protocol, isServer=False))
  194. return succeed(protocol)
  195. class SSHCommandClientEndpointTestsMixin(object):
  196. """
  197. Tests for L{SSHCommandClientEndpoint}, an L{IStreamClientEndpoint}
  198. implementations which connects a protocol with the stdin and stdout of a
  199. command running in an SSH session.
  200. These tests apply to L{SSHCommandClientEndpoint} whether it is constructed
  201. using L{SSHCommandClientEndpoint.existingConnection} or
  202. L{SSHCommandClientEndpoint.newConnection}.
  203. Subclasses must override L{create}, L{assertClientTransportState}, and
  204. L{finishConnection}.
  205. """
  206. def setUp(self):
  207. self.hostname = b"ssh.example.com"
  208. self.port = 42022
  209. self.user = b"user"
  210. self.password = b"password"
  211. self.reactor = MemoryReactorClock()
  212. self.realm = TrivialRealm()
  213. self.portal = Portal(self.realm)
  214. self.passwdDB = InMemoryUsernamePasswordDatabaseDontUse()
  215. self.passwdDB.addUser(self.user, self.password)
  216. self.portal.registerChecker(self.passwdDB)
  217. self.factory = CommandFactory()
  218. self.factory.reactor = self.reactor
  219. self.factory.portal = self.portal
  220. self.factory.doStart()
  221. self.addCleanup(self.factory.doStop)
  222. self.clientAddress = IPv4Address("TCP", "10.0.0.1", 12345)
  223. self.serverAddress = IPv4Address("TCP", "192.168.100.200", 54321)
  224. def create(self):
  225. """
  226. Create and return a new L{SSHCommandClientEndpoint} to be tested.
  227. Override this to implement creation in an interesting way the endpoint.
  228. """
  229. raise NotImplementedError(
  230. "%r did not implement create" % (self.__class__.__name__,))
  231. def assertClientTransportState(self, client, immediateClose):
  232. """
  233. Make an assertion about the connectedness of the given protocol's
  234. transport. Override this to implement either a check for the
  235. connection still being open or having been closed as appropriate.
  236. @param client: The client whose state is being checked.
  237. @param immediateClose: Boolean indicating whether the connection was
  238. closed immediately or not.
  239. """
  240. raise NotImplementedError(
  241. "%r did not implement assertClientTransportState" % (
  242. self.__class__.__name__,))
  243. def finishConnection(self):
  244. """
  245. Do any remaining work necessary to complete an in-memory connection
  246. attempted initiated using C{self.reactor}.
  247. """
  248. raise NotImplementedError(
  249. "%r did not implement finishConnection" % (
  250. self.__class__.__name__,))
  251. def connectedServerAndClient(self, serverFactory, clientFactory):
  252. """
  253. Set up an in-memory connection between protocols created by
  254. C{serverFactory} and C{clientFactory}.
  255. @return: A three-tuple. The first element is the protocol created by
  256. C{serverFactory}. The second element is the protocol created by
  257. C{clientFactory}. The third element is the L{IOPump} connecting
  258. them.
  259. """
  260. clientProtocol = clientFactory.buildProtocol(None)
  261. serverProtocol = serverFactory.buildProtocol(None)
  262. clientTransport = AbortableFakeTransport(
  263. clientProtocol, isServer=False, hostAddress=self.clientAddress,
  264. peerAddress=self.serverAddress)
  265. serverTransport = AbortableFakeTransport(
  266. serverProtocol, isServer=True, hostAddress=self.serverAddress,
  267. peerAddress=self.clientAddress)
  268. pump = connect(
  269. serverProtocol, serverTransport, clientProtocol, clientTransport)
  270. return serverProtocol, clientProtocol, pump
  271. def test_channelOpenFailure(self):
  272. """
  273. If a channel cannot be opened on the authenticated SSH connection, the
  274. L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with
  275. a L{Failure} wrapping the reason given by the server.
  276. """
  277. endpoint = self.create()
  278. factory = Factory()
  279. factory.protocol = Protocol
  280. connected = endpoint.connect(factory)
  281. server, client, pump = self.finishConnection()
  282. # The server logs the channel open failure - this is expected.
  283. errors = self.flushLoggedErrors(ConchError)
  284. self.assertIn(
  285. 'unknown channel', (errors[0].value.data, errors[0].value.value))
  286. self.assertEqual(1, len(errors))
  287. # Now deal with the results on the endpoint side.
  288. f = self.failureResultOf(connected)
  289. f.trap(ConchError)
  290. self.assertEqual(b'unknown channel', f.value.value)
  291. self.assertClientTransportState(client, False)
  292. def test_execFailure(self):
  293. """
  294. If execution of the command fails, the L{Deferred} returned by
  295. L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping
  296. the reason given by the server.
  297. """
  298. self.realm.channelLookup[b'session'] = BrokenExecSession
  299. endpoint = self.create()
  300. factory = Factory()
  301. factory.protocol = Protocol
  302. connected = endpoint.connect(factory)
  303. server, client, pump = self.finishConnection()
  304. f = self.failureResultOf(connected)
  305. f.trap(ConchError)
  306. self.assertEqual('channel request failed', f.value.value)
  307. self.assertClientTransportState(client, False)
  308. def test_execCancelled(self):
  309. """
  310. If execution of the command is cancelled via the L{Deferred} returned
  311. by L{SSHCommandClientEndpoint.connect}, the connection is closed
  312. immediately.
  313. """
  314. self.realm.channelLookup[b'session'] = UnsatisfiedExecSession
  315. endpoint = self.create()
  316. factory = Factory()
  317. factory.protocol = Protocol
  318. connected = endpoint.connect(factory)
  319. server, client, pump = self.finishConnection()
  320. connected.cancel()
  321. f = self.failureResultOf(connected)
  322. f.trap(CancelledError)
  323. self.assertClientTransportState(client, True)
  324. def test_buildProtocol(self):
  325. """
  326. Once the necessary SSH actions have completed successfully,
  327. L{SSHCommandClientEndpoint.connect} uses the factory passed to it to
  328. construct a protocol instance by calling its C{buildProtocol} method
  329. with an address object representing the SSH connection and command
  330. executed.
  331. """
  332. self.realm.channelLookup[b'session'] = WorkingExecSession
  333. endpoint = self.create()
  334. factory = AddressSpyFactory()
  335. factory.protocol = Protocol
  336. endpoint.connect(factory)
  337. server, client, pump = self.finishConnection()
  338. self.assertIsInstance(factory.address, SSHCommandAddress)
  339. self.assertEqual(server.transport.getHost(), factory.address.server)
  340. self.assertEqual(self.user, factory.address.username)
  341. self.assertEqual(b"/bin/ls -l", factory.address.command)
  342. def test_makeConnection(self):
  343. """
  344. L{SSHCommandClientEndpoint} establishes an SSH connection, creates a
  345. channel in it, runs a command in that channel, and uses the protocol's
  346. C{makeConnection} to associate it with a protocol representing that
  347. command's stdin and stdout.
  348. """
  349. self.realm.channelLookup[b'session'] = WorkingExecSession
  350. endpoint = self.create()
  351. factory = Factory()
  352. factory.protocol = Protocol
  353. connected = endpoint.connect(factory)
  354. server, client, pump = self.finishConnection()
  355. protocol = self.successResultOf(connected)
  356. self.assertIsNotNone(protocol.transport)
  357. def test_dataReceived(self):
  358. """
  359. After establishing the connection, when the command on the SSH server
  360. produces output, it is delivered to the protocol's C{dataReceived}
  361. method.
  362. """
  363. self.realm.channelLookup[b'session'] = WorkingExecSession
  364. endpoint = self.create()
  365. factory = Factory()
  366. factory.protocol = Protocol
  367. connected = endpoint.connect(factory)
  368. server, client, pump = self.finishConnection()
  369. protocol = self.successResultOf(connected)
  370. dataReceived = []
  371. protocol.dataReceived = dataReceived.append
  372. # Figure out which channel on the connection this protocol is
  373. # associated with so the test can do a write on it.
  374. channelId = protocol.transport.id
  375. server.service.channels[channelId].write(b"hello, world")
  376. pump.pump()
  377. self.assertEqual(b"hello, world", b"".join(dataReceived))
  378. def test_connectionLost(self):
  379. """
  380. When the command closes the channel, the protocol's C{connectionLost}
  381. method is called.
  382. """
  383. self.realm.channelLookup[b'session'] = WorkingExecSession
  384. endpoint = self.create()
  385. factory = Factory()
  386. factory.protocol = Protocol
  387. connected = endpoint.connect(factory)
  388. server, client, pump = self.finishConnection()
  389. protocol = self.successResultOf(connected)
  390. connectionLost = []
  391. protocol.connectionLost = connectionLost.append
  392. # Figure out which channel on the connection this protocol is
  393. # associated with so the test can do a write on it.
  394. channelId = protocol.transport.id
  395. server.service.channels[channelId].loseConnection()
  396. pump.pump()
  397. connectionLost[0].trap(ConnectionDone)
  398. self.assertClientTransportState(client, False)
  399. def _exitStatusTest(self, request, requestArg):
  400. """
  401. Test handling of non-zero exit statuses or exit signals.
  402. """
  403. self.realm.channelLookup[b'session'] = WorkingExecSession
  404. endpoint = self.create()
  405. factory = Factory()
  406. factory.protocol = Protocol
  407. connected = endpoint.connect(factory)
  408. server, client, pump = self.finishConnection()
  409. protocol = self.successResultOf(connected)
  410. connectionLost = []
  411. protocol.connectionLost = connectionLost.append
  412. # Figure out which channel on the connection this protocol is
  413. # associated with so the test can simulate command exit and
  414. # channel close.
  415. channelId = protocol.transport.id
  416. channel = server.service.channels[channelId]
  417. server.service.sendRequest(channel, request, requestArg)
  418. channel.loseConnection()
  419. pump.pump()
  420. self.assertClientTransportState(client, False)
  421. return connectionLost[0]
  422. def test_zeroExitCode(self):
  423. """
  424. When the command exits with a non-zero status, the protocol's
  425. C{connectionLost} method is called with a L{Failure} wrapping an
  426. exception which encapsulates that status.
  427. """
  428. exitCode = 0
  429. exc = self._exitStatusTest(b'exit-status', pack('>L', exitCode))
  430. exc.trap(ConnectionDone)
  431. def test_nonZeroExitStatus(self):
  432. """
  433. When the command exits with a non-zero status, the protocol's
  434. C{connectionLost} method is called with a L{Failure} wrapping an
  435. exception which encapsulates that status.
  436. """
  437. exitCode = 123
  438. signal = None
  439. exc = self._exitStatusTest(b'exit-status', pack('>L', exitCode))
  440. exc.trap(ProcessTerminated)
  441. self.assertEqual(exitCode, exc.value.exitCode)
  442. self.assertEqual(signal, exc.value.signal)
  443. def test_nonZeroExitSignal(self):
  444. """
  445. When the command exits with a non-zero signal, the protocol's
  446. C{connectionLost} method is called with a L{Failure} wrapping an
  447. exception which encapsulates that status.
  448. """
  449. exitCode = None
  450. signal = 123
  451. exc = self._exitStatusTest(b'exit-signal', pack('>L', signal))
  452. exc.trap(ProcessTerminated)
  453. self.assertEqual(exitCode, exc.value.exitCode)
  454. self.assertEqual(signal, exc.value.signal)
  455. def record(self, server, protocol, event, noArgs=False):
  456. """
  457. Hook into and record events which happen to C{protocol}.
  458. @param server: The SSH server protocol over which C{protocol} is
  459. running.
  460. @type server: L{IProtocol} provider
  461. @param protocol:
  462. @param event:
  463. @param noArgs:
  464. """
  465. # Figure out which channel the test is going to send data over
  466. # so we can look for it to arrive at the right place on the server.
  467. channelId = protocol.transport.id
  468. recorder = []
  469. if noArgs:
  470. f = lambda: recorder.append(None)
  471. else:
  472. f = recorder.append
  473. setattr(server.service.channels[channelId], event, f)
  474. return recorder
  475. def test_write(self):
  476. """
  477. The transport connected to the protocol has a C{write} method which
  478. sends bytes to the input of the command executing on the SSH server.
  479. """
  480. self.realm.channelLookup[b'session'] = WorkingExecSession
  481. endpoint = self.create()
  482. factory = Factory()
  483. factory.protocol = Protocol
  484. connected = endpoint.connect(factory)
  485. server, client, pump = self.finishConnection()
  486. protocol = self.successResultOf(connected)
  487. dataReceived = self.record(server, protocol, 'dataReceived')
  488. protocol.transport.write(b"hello, world")
  489. pump.pump()
  490. self.assertEqual(b"hello, world", b"".join(dataReceived))
  491. def test_writeSequence(self):
  492. """
  493. The transport connected to the protocol has a C{writeSequence} method which
  494. sends bytes to the input of the command executing on the SSH server.
  495. """
  496. self.realm.channelLookup[b'session'] = WorkingExecSession
  497. endpoint = self.create()
  498. factory = Factory()
  499. factory.protocol = Protocol
  500. connected = endpoint.connect(factory)
  501. server, client, pump = self.finishConnection()
  502. protocol = self.successResultOf(connected)
  503. dataReceived = self.record(server, protocol, 'dataReceived')
  504. protocol.transport.writeSequence([b"hello, world"])
  505. pump.pump()
  506. self.assertEqual(b"hello, world", b"".join(dataReceived))
  507. class NewConnectionTests(TestCase, SSHCommandClientEndpointTestsMixin):
  508. """
  509. Tests for L{SSHCommandClientEndpoint} when using the C{newConnection}
  510. constructor.
  511. """
  512. def setUp(self):
  513. """
  514. Configure an SSH server with password authentication enabled for a
  515. well-known (to the tests) account.
  516. """
  517. SSHCommandClientEndpointTestsMixin.setUp(self)
  518. # Make the server's host key available to be verified by the client.
  519. self.hostKeyPath = FilePath(self.mktemp())
  520. self.knownHosts = KnownHostsFile(self.hostKeyPath)
  521. self.knownHosts.addHostKey(
  522. self.hostname, self.factory.publicKeys[b'ssh-rsa'])
  523. self.knownHosts.addHostKey(
  524. networkString(self.serverAddress.host),
  525. self.factory.publicKeys[b'ssh-rsa'])
  526. self.knownHosts.save()
  527. def create(self):
  528. """
  529. Create and return a new L{SSHCommandClientEndpoint} using the
  530. C{newConnection} constructor.
  531. """
  532. return SSHCommandClientEndpoint.newConnection(
  533. self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
  534. password=self.password, knownHosts=self.knownHosts,
  535. ui=FixedResponseUI(False))
  536. def finishConnection(self):
  537. """
  538. Establish the first attempted TCP connection using the SSH server which
  539. C{self.factory} can create.
  540. """
  541. return self.connectedServerAndClient(
  542. self.factory, self.reactor.tcpClients[0][2])
  543. def loseConnectionToServer(self, server, client, protocol, pump):
  544. """
  545. Lose the connection to a server and pump the L{IOPump} sufficiently for
  546. the client to handle the lost connection. Asserts that the client
  547. disconnects its transport.
  548. @param server: The SSH server protocol over which C{protocol} is
  549. running.
  550. @type server: L{IProtocol} provider
  551. @param client: The SSH client protocol over which C{protocol} is
  552. running.
  553. @type client: L{IProtocol} provider
  554. @param protocol: The protocol created by calling connect on the ssh
  555. endpoint under test.
  556. @type protocol: L{IProtocol} provider
  557. @param pump: The L{IOPump} connecting client to server.
  558. @type pump: L{IOPump}
  559. """
  560. closed = self.record(server, protocol, 'closed', noArgs=True)
  561. protocol.transport.loseConnection()
  562. pump.pump()
  563. self.assertEqual([None], closed)
  564. # Let the last bit of network traffic flow. This lets the server's
  565. # close acknowledgement through, at which point the client can close
  566. # the overall SSH connection.
  567. pump.pump()
  568. # Given that the client transport is disconnecting, report the
  569. # disconnect from up to the ssh protocol.
  570. client.transport.reportDisconnect()
  571. def assertClientTransportState(self, client, immediateClose):
  572. """
  573. Assert that the transport for the given protocol has been disconnected.
  574. L{SSHCommandClientEndpoint.newConnection} creates a new dedicated SSH
  575. connection and cleans it up after the command exits.
  576. """
  577. # Nothing useful can be done with the connection at this point, so the
  578. # endpoint should close it.
  579. if immediateClose:
  580. self.assertTrue(client.transport.aborted)
  581. else:
  582. self.assertTrue(client.transport.disconnecting)
  583. def test_interface(self):
  584. """
  585. L{SSHCommandClientEndpoint} instances provide L{IStreamClientEndpoint}.
  586. """
  587. endpoint = SSHCommandClientEndpoint.newConnection(
  588. self.reactor, b"dummy command", b"dummy user",
  589. self.hostname, self.port)
  590. self.assertTrue(verifyObject(IStreamClientEndpoint, endpoint))
  591. def test_defaultPort(self):
  592. """
  593. L{SSHCommandClientEndpoint} uses the default port number for SSH when
  594. the C{port} argument is not specified.
  595. """
  596. endpoint = SSHCommandClientEndpoint.newConnection(
  597. self.reactor, b"dummy command", b"dummy user", self.hostname)
  598. self.assertEqual(22, endpoint._creator.port)
  599. def test_specifiedPort(self):
  600. """
  601. L{SSHCommandClientEndpoint} uses the C{port} argument if specified.
  602. """
  603. endpoint = SSHCommandClientEndpoint.newConnection(
  604. self.reactor, b"dummy command", b"dummy user",
  605. self.hostname, port=2222)
  606. self.assertEqual(2222, endpoint._creator.port)
  607. def test_destination(self):
  608. """
  609. L{SSHCommandClientEndpoint} uses the L{IReactorTCP} passed to it to
  610. attempt a connection to the host/port address also passed to it.
  611. """
  612. endpoint = SSHCommandClientEndpoint.newConnection(
  613. self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
  614. password=self.password, knownHosts=self.knownHosts,
  615. ui=FixedResponseUI(False))
  616. factory = Factory()
  617. factory.protocol = Protocol
  618. endpoint.connect(factory)
  619. host, port, factory, timeout, bindAddress = self.reactor.tcpClients[0]
  620. self.assertEqual(self.hostname, networkString(host))
  621. self.assertEqual(self.port, port)
  622. self.assertEqual(1, len(self.reactor.tcpClients))
  623. def test_connectionFailed(self):
  624. """
  625. If a connection cannot be established, the L{Deferred} returned by
  626. L{SSHCommandClientEndpoint.connect} fires with a L{Failure}
  627. representing the reason for the connection setup failure.
  628. """
  629. endpoint = SSHCommandClientEndpoint.newConnection(
  630. self.reactor, b"/bin/ls -l", b"dummy user",
  631. self.hostname, self.port, knownHosts=self.knownHosts,
  632. ui=FixedResponseUI(False))
  633. factory = Factory()
  634. factory.protocol = Protocol
  635. d = endpoint.connect(factory)
  636. factory = self.reactor.tcpClients[0][2]
  637. factory.clientConnectionFailed(None, Failure(ConnectionRefusedError()))
  638. self.failureResultOf(d).trap(ConnectionRefusedError)
  639. def test_userRejectedHostKey(self):
  640. """
  641. If the L{KnownHostsFile} instance used to construct
  642. L{SSHCommandClientEndpoint} rejects the SSH public key presented by the
  643. server, the L{Deferred} returned by L{SSHCommandClientEndpoint.connect}
  644. fires with a L{Failure} wrapping L{UserRejectedKey}.
  645. """
  646. endpoint = SSHCommandClientEndpoint.newConnection(
  647. self.reactor, b"/bin/ls -l", b"dummy user",
  648. self.hostname, self.port, knownHosts=KnownHostsFile(self.mktemp()),
  649. ui=FixedResponseUI(False))
  650. factory = Factory()
  651. factory.protocol = Protocol
  652. connected = endpoint.connect(factory)
  653. server, client, pump = self.connectedServerAndClient(
  654. self.factory, self.reactor.tcpClients[0][2])
  655. f = self.failureResultOf(connected)
  656. f.trap(UserRejectedKey)
  657. def test_mismatchedHostKey(self):
  658. """
  659. If the SSH public key presented by the SSH server does not match the
  660. previously remembered key, as reported by the L{KnownHostsFile}
  661. instance use to construct the endpoint, for that server, the
  662. L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with
  663. a L{Failure} wrapping L{HostKeyChanged}.
  664. """
  665. firstKey = Key.fromString(privateRSA_openssh).public()
  666. knownHosts = KnownHostsFile(FilePath(self.mktemp()))
  667. knownHosts.addHostKey(
  668. networkString(self.serverAddress.host), firstKey)
  669. # Add a different RSA key with the same hostname
  670. differentKey = Key.fromString(privateRSA_openssh_encrypted_aes,
  671. passphrase=b'testxp').public()
  672. knownHosts.addHostKey(self.hostname, differentKey)
  673. # The UI may answer true to any questions asked of it; they should
  674. # make no difference, since a *mismatched* key is not even optionally
  675. # allowed to complete a connection.
  676. ui = FixedResponseUI(True)
  677. endpoint = SSHCommandClientEndpoint.newConnection(
  678. self.reactor, b"/bin/ls -l", b"dummy user",
  679. self.hostname, self.port, password=b"dummy password",
  680. knownHosts=knownHosts, ui=ui)
  681. factory = Factory()
  682. factory.protocol = Protocol
  683. connected = endpoint.connect(factory)
  684. server, client, pump = self.connectedServerAndClient(
  685. self.factory, self.reactor.tcpClients[0][2])
  686. f = self.failureResultOf(connected)
  687. f.trap(HostKeyChanged)
  688. def test_connectionClosedBeforeSecure(self):
  689. """
  690. If the connection closes at any point before the SSH transport layer
  691. has finished key exchange (ie, gotten to the point where we may attempt
  692. to authenticate), the L{Deferred} returned by
  693. L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping
  694. the reason for the lost connection.
  695. """
  696. endpoint = SSHCommandClientEndpoint.newConnection(
  697. self.reactor, b"/bin/ls -l", b"dummy user",
  698. self.hostname, self.port, knownHosts=self.knownHosts,
  699. ui=FixedResponseUI(False))
  700. factory = Factory()
  701. factory.protocol = Protocol
  702. d = endpoint.connect(factory)
  703. transport = StringTransport()
  704. factory = self.reactor.tcpClients[0][2]
  705. client = factory.buildProtocol(None)
  706. client.makeConnection(transport)
  707. client.connectionLost(Failure(ConnectionDone()))
  708. self.failureResultOf(d).trap(ConnectionDone)
  709. def test_connectionCancelledBeforeSecure(self):
  710. """
  711. If the connection is cancelled before the SSH transport layer has
  712. finished key exchange (ie, gotten to the point where we may attempt to
  713. authenticate), the L{Deferred} returned by
  714. L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping
  715. L{CancelledError} and the connection is aborted.
  716. """
  717. endpoint = SSHCommandClientEndpoint.newConnection(
  718. self.reactor, b"/bin/ls -l", b"dummy user",
  719. self.hostname, self.port, knownHosts=self.knownHosts,
  720. ui=FixedResponseUI(False))
  721. factory = Factory()
  722. factory.protocol = Protocol
  723. d = endpoint.connect(factory)
  724. transport = AbortableFakeTransport(None, isServer=False)
  725. factory = self.reactor.tcpClients[0][2]
  726. client = factory.buildProtocol(None)
  727. client.makeConnection(transport)
  728. d.cancel()
  729. self.failureResultOf(d).trap(CancelledError)
  730. self.assertTrue(transport.aborted)
  731. # Make sure the connection closing doesn't result in unexpected
  732. # behavior when due to cancellation:
  733. client.connectionLost(Failure(ConnectionDone()))
  734. def test_connectionCancelledBeforeConnected(self):
  735. """
  736. If the connection is cancelled before it finishes connecting, the
  737. connection attempt is stopped.
  738. """
  739. endpoint = SSHCommandClientEndpoint.newConnection(
  740. self.reactor, b"/bin/ls -l", b"dummy user",
  741. self.hostname, self.port, knownHosts=self.knownHosts,
  742. ui=FixedResponseUI(False))
  743. factory = Factory()
  744. factory.protocol = Protocol
  745. d = endpoint.connect(factory)
  746. d.cancel()
  747. self.failureResultOf(d).trap(ConnectingCancelledError)
  748. self.assertTrue(self.reactor.connectors[0].stoppedConnecting)
  749. def test_passwordAuthenticationFailure(self):
  750. """
  751. If the SSH server rejects the password presented during authentication,
  752. the L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires
  753. with a L{Failure} wrapping L{AuthenticationFailed}.
  754. """
  755. endpoint = SSHCommandClientEndpoint.newConnection(
  756. self.reactor, b"/bin/ls -l", b"dummy user",
  757. self.hostname, self.port, password=b"dummy password",
  758. knownHosts=self.knownHosts, ui=FixedResponseUI(False))
  759. factory = Factory()
  760. factory.protocol = Protocol
  761. connected = endpoint.connect(factory)
  762. server, client, pump = self.connectedServerAndClient(
  763. self.factory, self.reactor.tcpClients[0][2])
  764. # For security, the server delays password authentication failure
  765. # response. Advance the simulation clock so the client sees the
  766. # failure.
  767. self.reactor.advance(server.service.passwordDelay)
  768. # Let the failure response traverse the "network"
  769. pump.flush()
  770. f = self.failureResultOf(connected)
  771. f.trap(AuthenticationFailed)
  772. # XXX Should assert something specific about the arguments of the
  773. # exception
  774. self.assertClientTransportState(client, False)
  775. def setupKeyChecker(self, portal, users):
  776. """
  777. Create an L{ISSHPrivateKey} checker which recognizes C{users} and add it
  778. to C{portal}.
  779. @param portal: A L{Portal} to which to add the checker.
  780. @type portal: L{Portal}
  781. @param users: The users and their keys the checker will recognize. Keys
  782. are byte strings giving user names. Values are byte strings giving
  783. OpenSSH-formatted private keys.
  784. @type users: L{dict}
  785. """
  786. mapping = dict([(k,[Key.fromString(v).public()])
  787. for k, v in iteritems(users)])
  788. checker = SSHPublicKeyChecker(InMemorySSHKeyDB(mapping))
  789. portal.registerChecker(checker)
  790. def test_publicKeyAuthenticationFailure(self):
  791. """
  792. If the SSH server rejects the key pair presented during authentication,
  793. the L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires
  794. with a L{Failure} wrapping L{AuthenticationFailed}.
  795. """
  796. badKey = Key.fromString(privateRSA_openssh)
  797. self.setupKeyChecker(self.portal, {self.user: privateDSA_openssh})
  798. endpoint = SSHCommandClientEndpoint.newConnection(
  799. self.reactor, b"/bin/ls -l", self.user,
  800. self.hostname, self.port, keys=[badKey],
  801. knownHosts=self.knownHosts, ui=FixedResponseUI(False))
  802. factory = Factory()
  803. factory.protocol = Protocol
  804. connected = endpoint.connect(factory)
  805. server, client, pump = self.connectedServerAndClient(
  806. self.factory, self.reactor.tcpClients[0][2])
  807. f = self.failureResultOf(connected)
  808. f.trap(AuthenticationFailed)
  809. # XXX Should assert something specific about the arguments of the
  810. # exception
  811. # Nothing useful can be done with the connection at this point, so the
  812. # endpoint should close it.
  813. self.assertTrue(client.transport.disconnecting)
  814. def test_authenticationFallback(self):
  815. """
  816. If the SSH server does not accept any of the specified SSH keys, the
  817. specified password is tried.
  818. """
  819. badKey = Key.fromString(privateRSA_openssh)
  820. self.setupKeyChecker(self.portal, {self.user: privateDSA_openssh})
  821. endpoint = SSHCommandClientEndpoint.newConnection(
  822. self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
  823. keys=[badKey], password=self.password, knownHosts=self.knownHosts,
  824. ui=FixedResponseUI(False))
  825. factory = Factory()
  826. factory.protocol = Protocol
  827. connected = endpoint.connect(factory)
  828. # Exercising fallback requires a failed authentication attempt. Allow
  829. # one.
  830. self.factory.attemptsBeforeDisconnect += 1
  831. server, client, pump = self.connectedServerAndClient(
  832. self.factory, self.reactor.tcpClients[0][2])
  833. pump.pump()
  834. # The server logs the channel open failure - this is expected.
  835. errors = self.flushLoggedErrors(ConchError)
  836. self.assertIn(
  837. 'unknown channel', (errors[0].value.data, errors[0].value.value))
  838. self.assertEqual(1, len(errors))
  839. # Now deal with the results on the endpoint side.
  840. f = self.failureResultOf(connected)
  841. f.trap(ConchError)
  842. self.assertEqual(b'unknown channel', f.value.value)
  843. # Nothing useful can be done with the connection at this point, so the
  844. # endpoint should close it.
  845. self.assertTrue(client.transport.disconnecting)
  846. def test_publicKeyAuthentication(self):
  847. """
  848. If L{SSHCommandClientEndpoint} is initialized with any private keys, it
  849. will try to use them to authenticate with the SSH server.
  850. """
  851. key = Key.fromString(privateDSA_openssh)
  852. self.setupKeyChecker(self.portal, {self.user: privateDSA_openssh})
  853. self.realm.channelLookup[b'session'] = WorkingExecSession
  854. endpoint = SSHCommandClientEndpoint.newConnection(
  855. self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
  856. keys=[key], knownHosts=self.knownHosts, ui=FixedResponseUI(False))
  857. factory = Factory()
  858. factory.protocol = Protocol
  859. connected = endpoint.connect(factory)
  860. server, client, pump = self.connectedServerAndClient(
  861. self.factory, self.reactor.tcpClients[0][2])
  862. protocol = self.successResultOf(connected)
  863. self.assertIsNotNone(protocol.transport)
  864. def test_skipPasswordAuthentication(self):
  865. """
  866. If the password is not specified, L{SSHCommandClientEndpoint} doesn't
  867. try it as an authentication mechanism.
  868. """
  869. endpoint = SSHCommandClientEndpoint.newConnection(
  870. self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
  871. knownHosts=self.knownHosts, ui=FixedResponseUI(False))
  872. factory = Factory()
  873. factory.protocol = Protocol
  874. connected = endpoint.connect(factory)
  875. server, client, pump = self.connectedServerAndClient(
  876. self.factory, self.reactor.tcpClients[0][2])
  877. pump.pump()
  878. # Now deal with the results on the endpoint side.
  879. f = self.failureResultOf(connected)
  880. f.trap(AuthenticationFailed)
  881. # Nothing useful can be done with the connection at this point, so the
  882. # endpoint should close it.
  883. self.assertTrue(client.transport.disconnecting)
  884. def test_agentAuthentication(self):
  885. """
  886. If L{SSHCommandClientEndpoint} is initialized with an
  887. L{SSHAgentClient}, the agent is used to authenticate with the SSH
  888. server. Once the connection with the SSH server has concluded, the
  889. connection to the agent is disconnected.
  890. """
  891. key = Key.fromString(privateRSA_openssh)
  892. agentServer = SSHAgentServer()
  893. agentServer.factory = Factory()
  894. agentServer.factory.keys = {key.blob(): (key, b"")}
  895. self.setupKeyChecker(self.portal, {self.user: privateRSA_openssh})
  896. agentEndpoint = SingleUseMemoryEndpoint(agentServer)
  897. endpoint = SSHCommandClientEndpoint.newConnection(
  898. self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
  899. knownHosts=self.knownHosts, ui=FixedResponseUI(False),
  900. agentEndpoint=agentEndpoint)
  901. self.realm.channelLookup[b'session'] = WorkingExecSession
  902. factory = Factory()
  903. factory.protocol = Protocol
  904. connected = endpoint.connect(factory)
  905. server, client, pump = self.connectedServerAndClient(
  906. self.factory, self.reactor.tcpClients[0][2])
  907. # Let the agent client talk with the agent server and the ssh client
  908. # talk with the ssh server.
  909. for i in range(14):
  910. agentEndpoint.pump.pump()
  911. pump.pump()
  912. protocol = self.successResultOf(connected)
  913. self.assertIsNotNone(protocol.transport)
  914. # Ensure the connection with the agent is cleaned up after the
  915. # connection with the server is lost.
  916. self.loseConnectionToServer(server, client, protocol, pump)
  917. self.assertTrue(client.transport.disconnecting)
  918. self.assertTrue(agentEndpoint.pump.clientIO.disconnecting)
  919. def test_loseConnection(self):
  920. """
  921. The transport connected to the protocol has a C{loseConnection} method
  922. which causes the channel in which the command is running to close and
  923. the overall connection to be closed.
  924. """
  925. self.realm.channelLookup[b'session'] = WorkingExecSession
  926. endpoint = self.create()
  927. factory = Factory()
  928. factory.protocol = Protocol
  929. connected = endpoint.connect(factory)
  930. server, client, pump = self.finishConnection()
  931. protocol = self.successResultOf(connected)
  932. self.loseConnectionToServer(server, client, protocol, pump)
  933. # Nothing useful can be done with the connection at this point, so the
  934. # endpoint should close it.
  935. self.assertTrue(client.transport.disconnecting)
  936. class ExistingConnectionTests(TestCase, SSHCommandClientEndpointTestsMixin):
  937. """
  938. Tests for L{SSHCommandClientEndpoint} when using the C{existingConnection}
  939. constructor.
  940. """
  941. def setUp(self):
  942. """
  943. Configure an SSH server with password authentication enabled for a
  944. well-known (to the tests) account.
  945. """
  946. SSHCommandClientEndpointTestsMixin.setUp(self)
  947. knownHosts = KnownHostsFile(FilePath(self.mktemp()))
  948. knownHosts.addHostKey(
  949. self.hostname, self.factory.publicKeys[b'ssh-rsa'])
  950. knownHosts.addHostKey(
  951. networkString(self.serverAddress.host),
  952. self.factory.publicKeys[b'ssh-rsa'])
  953. self.endpoint = SSHCommandClientEndpoint.newConnection(
  954. self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
  955. password=self.password, knownHosts=knownHosts,
  956. ui=FixedResponseUI(False))
  957. def create(self):
  958. """
  959. Create and return a new L{SSHCommandClientEndpoint} using the
  960. C{existingConnection} constructor.
  961. """
  962. factory = Factory()
  963. factory.protocol = Protocol
  964. connected = self.endpoint.connect(factory)
  965. # Please, let me in. This kinda sucks.
  966. channelLookup = self.realm.channelLookup.copy()
  967. try:
  968. self.realm.channelLookup[b'session'] = WorkingExecSession
  969. server, client, pump = self.connectedServerAndClient(
  970. self.factory, self.reactor.tcpClients[0][2])
  971. finally:
  972. self.realm.channelLookup.clear()
  973. self.realm.channelLookup.update(channelLookup)
  974. self._server = server
  975. self._client = client
  976. self._pump = pump
  977. protocol = self.successResultOf(connected)
  978. connection = protocol.transport.conn
  979. return SSHCommandClientEndpoint.existingConnection(
  980. connection, b"/bin/ls -l")
  981. def finishConnection(self):
  982. """
  983. Give back the connection established in L{create} over which the new
  984. command channel being tested will exchange data.
  985. """
  986. # The connection was set up and the first command channel set up, but
  987. # some more I/O needs to happen for the second command channel to be
  988. # ready. Make that I/O happen before giving back the objects.
  989. self._pump.pump()
  990. self._pump.pump()
  991. self._pump.pump()
  992. self._pump.pump()
  993. return self._server, self._client, self._pump
  994. def assertClientTransportState(self, client, immediateClose):
  995. """
  996. Assert that the transport for the given protocol is still connected.
  997. L{SSHCommandClientEndpoint.existingConnection} re-uses an SSH connected
  998. created by some other code, so other code is responsible for cleaning
  999. it up.
  1000. """
  1001. self.assertFalse(client.transport.disconnecting)
  1002. self.assertFalse(client.transport.aborted)
  1003. class ExistingConnectionHelperTests(TestCase):
  1004. """
  1005. Tests for L{_ExistingConnectionHelper}.
  1006. """
  1007. def test_interface(self):
  1008. """
  1009. L{_ExistingConnectionHelper} implements L{_ISSHConnectionCreator}.
  1010. """
  1011. self.assertTrue(
  1012. verifyClass(_ISSHConnectionCreator, _ExistingConnectionHelper))
  1013. def test_secureConnection(self):
  1014. """
  1015. L{_ExistingConnectionHelper.secureConnection} returns a L{Deferred}
  1016. which fires with whatever object was fed to
  1017. L{_ExistingConnectionHelper.__init__}.
  1018. """
  1019. result = object()
  1020. helper = _ExistingConnectionHelper(result)
  1021. self.assertIs(
  1022. result, self.successResultOf(helper.secureConnection()))
  1023. def test_cleanupConnectionNotImmediately(self):
  1024. """
  1025. L{_ExistingConnectionHelper.cleanupConnection} does nothing to the
  1026. existing connection if called with C{immediate} set to C{False}.
  1027. """
  1028. helper = _ExistingConnectionHelper(object())
  1029. # Bit hard to test nothing happens. However, since object() has no
  1030. # relevant methods or attributes, if the code is incorrect we can
  1031. # expect an AttributeError.
  1032. helper.cleanupConnection(object(), False)
  1033. def test_cleanupConnectionImmediately(self):
  1034. """
  1035. L{_ExistingConnectionHelper.cleanupConnection} does nothing to the
  1036. existing connection if called with C{immediate} set to C{True}.
  1037. """
  1038. helper = _ExistingConnectionHelper(object())
  1039. # Bit hard to test nothing happens. However, since object() has no
  1040. # relevant methods or attributes, if the code is incorrect we can
  1041. # expect an AttributeError.
  1042. helper.cleanupConnection(object(), True)
  1043. class _PTYPath(object):
  1044. """
  1045. A L{FilePath}-like object which can be opened to create a L{_ReadFile} with
  1046. certain contents.
  1047. """
  1048. def __init__(self, contents):
  1049. """
  1050. @param contents: L{bytes} which will be the contents of the
  1051. L{_ReadFile} this path can open.
  1052. """
  1053. self.contents = contents
  1054. def open(self, mode):
  1055. """
  1056. If the mode is r+, return a L{_ReadFile} with the contents given to
  1057. this path's initializer.
  1058. @raise OSError: If the mode is unsupported.
  1059. @return: A L{_ReadFile} instance
  1060. """
  1061. if mode == "rb+":
  1062. return _ReadFile(self.contents)
  1063. raise OSError(ENOSYS, "Function not implemented")
  1064. class NewConnectionHelperTests(TestCase):
  1065. """
  1066. Tests for L{_NewConnectionHelper}.
  1067. """
  1068. def test_interface(self):
  1069. """
  1070. L{_NewConnectionHelper} implements L{_ISSHConnectionCreator}.
  1071. """
  1072. self.assertTrue(
  1073. verifyClass(_ISSHConnectionCreator, _NewConnectionHelper))
  1074. def test_defaultPath(self):
  1075. """
  1076. The default I{known_hosts} path is I{~/.ssh/known_hosts}.
  1077. """
  1078. self.assertEqual(
  1079. "~/.ssh/known_hosts", _NewConnectionHelper._KNOWN_HOSTS)
  1080. def test_defaultKnownHosts(self):
  1081. """
  1082. L{_NewConnectionHelper._knownHosts} is used to create a
  1083. L{KnownHostsFile} if one is not passed to the initializer.
  1084. """
  1085. result = object()
  1086. self.patch(_NewConnectionHelper, '_knownHosts', lambda cls: result)
  1087. helper = _NewConnectionHelper(
  1088. None, None, None, None, None, None, None, None, None, None)
  1089. self.assertIs(result, helper.knownHosts)
  1090. def test_readExisting(self):
  1091. """
  1092. Existing entries in the I{known_hosts} file are reflected by the
  1093. L{KnownHostsFile} created by L{_NewConnectionHelper} when none is
  1094. supplied to it.
  1095. """
  1096. key = CommandFactory().publicKeys[b'ssh-rsa']
  1097. path = FilePath(self.mktemp())
  1098. knownHosts = KnownHostsFile(path)
  1099. knownHosts.addHostKey(b"127.0.0.1", key)
  1100. knownHosts.save()
  1101. msg("Created known_hosts file at %r" % (path.path,))
  1102. # Unexpand ${HOME} to make sure ~ syntax is respected.
  1103. home = os.path.expanduser("~/")
  1104. default = path.path.replace(home, "~/")
  1105. self.patch(_NewConnectionHelper, "_KNOWN_HOSTS", default)
  1106. msg("Patched _KNOWN_HOSTS with %r" % (default,))
  1107. loaded = _NewConnectionHelper._knownHosts()
  1108. self.assertTrue(loaded.hasHostKey(b"127.0.0.1", key))
  1109. def test_defaultConsoleUI(self):
  1110. """
  1111. If L{None} is passed for the C{ui} parameter to
  1112. L{_NewConnectionHelper}, a L{ConsoleUI} is used.
  1113. """
  1114. helper = _NewConnectionHelper(
  1115. None, None, None, None, None, None, None, None, None, None)
  1116. self.assertIsInstance(helper.ui, ConsoleUI)
  1117. def test_ttyConsoleUI(self):
  1118. """
  1119. If L{None} is passed for the C{ui} parameter to L{_NewConnectionHelper}
  1120. and /dev/tty is available, the L{ConsoleUI} used is associated with
  1121. /dev/tty.
  1122. """
  1123. tty = _PTYPath(b"yes")
  1124. helper = _NewConnectionHelper(
  1125. None, None, None, None, None, None, None, None, None, None, tty)
  1126. result = self.successResultOf(helper.ui.prompt(b"does this work?"))
  1127. self.assertTrue(result)
  1128. def test_nottyUI(self):
  1129. """
  1130. If L{None} is passed for the C{ui} parameter to L{_NewConnectionHelper}
  1131. and /dev/tty is not available, the L{ConsoleUI} used is associated with
  1132. some file which always produces a C{b"no"} response.
  1133. """
  1134. tty = FilePath(self.mktemp())
  1135. helper = _NewConnectionHelper(
  1136. None, None, None, None, None, None, None, None, None, None, tty)
  1137. result = self.successResultOf(helper.ui.prompt(b"did this break?"))
  1138. self.assertFalse(result)
  1139. def test_defaultTTYFilename(self):
  1140. """
  1141. If not passed the name of a tty in the filesystem,
  1142. L{_NewConnectionHelper} uses C{b"/dev/tty"}.
  1143. """
  1144. helper = _NewConnectionHelper(
  1145. None, None, None, None, None, None, None, None, None, None)
  1146. self.assertEqual(FilePath(b"/dev/tty"), helper.tty)
  1147. def test_cleanupConnectionNotImmediately(self):
  1148. """
  1149. L{_NewConnectionHelper.cleanupConnection} closes the transport cleanly
  1150. if called with C{immediate} set to C{False}.
  1151. """
  1152. helper = _NewConnectionHelper(
  1153. None, None, None, None, None, None, None, None, None, None)
  1154. connection = SSHConnection()
  1155. connection.transport = StringTransport()
  1156. helper.cleanupConnection(connection, False)
  1157. self.assertTrue(connection.transport.disconnecting)
  1158. def test_cleanupConnectionImmediately(self):
  1159. """
  1160. L{_NewConnectionHelper.cleanupConnection} closes the transport with
  1161. C{abortConnection} if called with C{immediate} set to C{True}.
  1162. """
  1163. class Abortable:
  1164. aborted = False
  1165. def abortConnection(self):
  1166. """
  1167. Abort the connection.
  1168. """
  1169. self.aborted = True
  1170. helper = _NewConnectionHelper(
  1171. None, None, None, None, None, None, None, None, None, None)
  1172. connection = SSHConnection()
  1173. connection.transport = SSHClientTransport()
  1174. connection.transport.transport = Abortable()
  1175. helper.cleanupConnection(connection, True)
  1176. self.assertTrue(connection.transport.transport.aborted)