test_conch.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. # -*- test-case-name: twisted.conch.test.test_conch -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. import os, sys, socket
  5. import subprocess
  6. from itertools import count
  7. from zope.interface import implementer
  8. from twisted.conch.error import ConchError
  9. from twisted.conch.avatar import ConchUser
  10. from twisted.conch.ssh.session import ISession, SSHSession, wrapProtocol
  11. from twisted.cred import portal
  12. from twisted.internet import reactor, defer, protocol
  13. from twisted.internet.error import ProcessExitedAlready
  14. from twisted.internet.task import LoopingCall
  15. from twisted.internet.utils import getProcessValue
  16. from twisted.python import filepath, log, runtime
  17. from twisted.python.compat import unicode
  18. from twisted.trial import unittest
  19. try:
  20. from twisted.conch.scripts.conch import SSHSession as StdioInteractingSession
  21. except ImportError as e:
  22. StdioInteractingSession = None
  23. _reason = str(e)
  24. del e
  25. from twisted.conch.test.test_ssh import ConchTestRealm
  26. from twisted.python.procutils import which
  27. from twisted.conch.test.keydata import publicRSA_openssh, privateRSA_openssh
  28. from twisted.conch.test.keydata import publicDSA_openssh, privateDSA_openssh
  29. try:
  30. from twisted.conch.test.test_ssh import ConchTestServerFactory, \
  31. conchTestPublicKeyChecker
  32. except ImportError:
  33. pass
  34. try:
  35. import cryptography
  36. except ImportError:
  37. cryptography = None
  38. try:
  39. import pyasn1
  40. except ImportError:
  41. pyasn1 = None
  42. def _has_ipv6():
  43. """ Returns True if the system can bind an IPv6 address."""
  44. sock = None
  45. has_ipv6 = False
  46. try:
  47. sock = socket.socket(socket.AF_INET6)
  48. sock.bind(('::1', 0))
  49. has_ipv6 = True
  50. except socket.error:
  51. pass
  52. if sock:
  53. sock.close()
  54. return has_ipv6
  55. HAS_IPV6 = _has_ipv6()
  56. class FakeStdio(object):
  57. """
  58. A fake for testing L{twisted.conch.scripts.conch.SSHSession.eofReceived} and
  59. L{twisted.conch.scripts.cftp.SSHSession.eofReceived}.
  60. @ivar writeConnLost: A flag which records whether L{loserWriteConnection}
  61. has been called.
  62. """
  63. writeConnLost = False
  64. def loseWriteConnection(self):
  65. """
  66. Record the call to loseWriteConnection.
  67. """
  68. self.writeConnLost = True
  69. class StdioInteractingSessionTests(unittest.TestCase):
  70. """
  71. Tests for L{twisted.conch.scripts.conch.SSHSession}.
  72. """
  73. if StdioInteractingSession is None:
  74. skip = _reason
  75. def test_eofReceived(self):
  76. """
  77. L{twisted.conch.scripts.conch.SSHSession.eofReceived} loses the
  78. write half of its stdio connection.
  79. """
  80. stdio = FakeStdio()
  81. channel = StdioInteractingSession()
  82. channel.stdio = stdio
  83. channel.eofReceived()
  84. self.assertTrue(stdio.writeConnLost)
  85. class Echo(protocol.Protocol):
  86. def connectionMade(self):
  87. log.msg('ECHO CONNECTION MADE')
  88. def connectionLost(self, reason):
  89. log.msg('ECHO CONNECTION DONE')
  90. def dataReceived(self, data):
  91. self.transport.write(data)
  92. if b'\n' in data:
  93. self.transport.loseConnection()
  94. class EchoFactory(protocol.Factory):
  95. protocol = Echo
  96. class ConchTestOpenSSHProcess(protocol.ProcessProtocol):
  97. """
  98. Test protocol for launching an OpenSSH client process.
  99. @ivar deferred: Set by whatever uses this object. Accessed using
  100. L{_getDeferred}, which destroys the value so the Deferred is not
  101. fired twice. Fires when the process is terminated.
  102. """
  103. deferred = None
  104. buf = b''
  105. def _getDeferred(self):
  106. d, self.deferred = self.deferred, None
  107. return d
  108. def outReceived(self, data):
  109. self.buf += data
  110. def processEnded(self, reason):
  111. """
  112. Called when the process has ended.
  113. @param reason: a Failure giving the reason for the process' end.
  114. """
  115. if reason.value.exitCode != 0:
  116. self._getDeferred().errback(
  117. ConchError("exit code was not 0: {}".format(
  118. reason.value.exitCode)))
  119. else:
  120. buf = self.buf.replace(b'\r\n', b'\n')
  121. self._getDeferred().callback(buf)
  122. class ConchTestForwardingProcess(protocol.ProcessProtocol):
  123. """
  124. Manages a third-party process which launches a server.
  125. Uses L{ConchTestForwardingPort} to connect to the third-party server.
  126. Once L{ConchTestForwardingPort} has disconnected, kill the process and fire
  127. a Deferred with the data received by the L{ConchTestForwardingPort}.
  128. @ivar deferred: Set by whatever uses this object. Accessed using
  129. L{_getDeferred}, which destroys the value so the Deferred is not
  130. fired twice. Fires when the process is terminated.
  131. """
  132. deferred = None
  133. def __init__(self, port, data):
  134. """
  135. @type port: L{int}
  136. @param port: The port on which the third-party server is listening.
  137. (it is assumed that the server is running on localhost).
  138. @type data: L{str}
  139. @param data: This is sent to the third-party server. Must end with '\n'
  140. in order to trigger a disconnect.
  141. """
  142. self.port = port
  143. self.buffer = None
  144. self.data = data
  145. def _getDeferred(self):
  146. d, self.deferred = self.deferred, None
  147. return d
  148. def connectionMade(self):
  149. self._connect()
  150. def _connect(self):
  151. """
  152. Connect to the server, which is often a third-party process.
  153. Tries to reconnect if it fails because we have no way of determining
  154. exactly when the port becomes available for listening -- we can only
  155. know when the process starts.
  156. """
  157. cc = protocol.ClientCreator(reactor, ConchTestForwardingPort, self,
  158. self.data)
  159. d = cc.connectTCP('127.0.0.1', self.port)
  160. d.addErrback(self._ebConnect)
  161. return d
  162. def _ebConnect(self, f):
  163. reactor.callLater(.1, self._connect)
  164. def forwardingPortDisconnected(self, buffer):
  165. """
  166. The network connection has died; save the buffer of output
  167. from the network and attempt to quit the process gracefully,
  168. and then (after the reactor has spun) send it a KILL signal.
  169. """
  170. self.buffer = buffer
  171. self.transport.write(b'\x03')
  172. self.transport.loseConnection()
  173. reactor.callLater(0, self._reallyDie)
  174. def _reallyDie(self):
  175. try:
  176. self.transport.signalProcess('KILL')
  177. except ProcessExitedAlready:
  178. pass
  179. def processEnded(self, reason):
  180. """
  181. Fire the Deferred at self.deferred with the data collected
  182. from the L{ConchTestForwardingPort} connection, if any.
  183. """
  184. self._getDeferred().callback(self.buffer)
  185. class ConchTestForwardingPort(protocol.Protocol):
  186. """
  187. Connects to server launched by a third-party process (managed by
  188. L{ConchTestForwardingProcess}) sends data, then reports whatever it
  189. received back to the L{ConchTestForwardingProcess} once the connection
  190. is ended.
  191. """
  192. def __init__(self, protocol, data):
  193. """
  194. @type protocol: L{ConchTestForwardingProcess}
  195. @param protocol: The L{ProcessProtocol} which made this connection.
  196. @type data: str
  197. @param data: The data to be sent to the third-party server.
  198. """
  199. self.protocol = protocol
  200. self.data = data
  201. def connectionMade(self):
  202. self.buffer = b''
  203. self.transport.write(self.data)
  204. def dataReceived(self, data):
  205. self.buffer += data
  206. def connectionLost(self, reason):
  207. self.protocol.forwardingPortDisconnected(self.buffer)
  208. def _makeArgs(args, mod="conch"):
  209. start = [sys.executable, '-c'
  210. """
  211. ### Twisted Preamble
  212. import sys, os
  213. path = os.path.abspath(sys.argv[0])
  214. while os.path.dirname(path) != path:
  215. if os.path.basename(path).startswith('Twisted'):
  216. sys.path.insert(0, path)
  217. break
  218. path = os.path.dirname(path)
  219. from twisted.conch.scripts.%s import run
  220. run()""" % mod]
  221. madeArgs = []
  222. for arg in start + list(args):
  223. if isinstance(arg, unicode):
  224. arg = arg.encode("utf-8")
  225. madeArgs.append(arg)
  226. return madeArgs
  227. class ConchServerSetupMixin:
  228. if not cryptography:
  229. skip = "can't run without cryptography"
  230. if not pyasn1:
  231. skip = "Cannot run without PyASN1"
  232. realmFactory = staticmethod(lambda: ConchTestRealm(b'testuser'))
  233. def _createFiles(self):
  234. for f in ['rsa_test','rsa_test.pub','dsa_test','dsa_test.pub',
  235. 'kh_test']:
  236. if os.path.exists(f):
  237. os.remove(f)
  238. with open('rsa_test','wb') as f:
  239. f.write(privateRSA_openssh)
  240. with open('rsa_test.pub','wb') as f:
  241. f.write(publicRSA_openssh)
  242. with open('dsa_test.pub','wb') as f:
  243. f.write(publicDSA_openssh)
  244. with open('dsa_test','wb') as f:
  245. f.write(privateDSA_openssh)
  246. os.chmod('dsa_test', 33152)
  247. os.chmod('rsa_test', 33152)
  248. with open('kh_test','wb') as f:
  249. f.write(b'127.0.0.1 '+publicRSA_openssh)
  250. def _getFreePort(self):
  251. s = socket.socket()
  252. s.bind(('', 0))
  253. port = s.getsockname()[1]
  254. s.close()
  255. return port
  256. def _makeConchFactory(self):
  257. """
  258. Make a L{ConchTestServerFactory}, which allows us to start a
  259. L{ConchTestServer} -- i.e. an actually listening conch.
  260. """
  261. realm = self.realmFactory()
  262. p = portal.Portal(realm)
  263. p.registerChecker(conchTestPublicKeyChecker())
  264. factory = ConchTestServerFactory()
  265. factory.portal = p
  266. return factory
  267. def setUp(self):
  268. self._createFiles()
  269. self.conchFactory = self._makeConchFactory()
  270. self.conchFactory.expectedLoseConnection = 1
  271. self.conchServer = reactor.listenTCP(0, self.conchFactory,
  272. interface="127.0.0.1")
  273. self.echoServer = reactor.listenTCP(0, EchoFactory())
  274. self.echoPort = self.echoServer.getHost().port
  275. if HAS_IPV6:
  276. self.echoServerV6 = reactor.listenTCP(0, EchoFactory(), interface="::1")
  277. self.echoPortV6 = self.echoServerV6.getHost().port
  278. def tearDown(self):
  279. try:
  280. self.conchFactory.proto.done = 1
  281. except AttributeError:
  282. pass
  283. else:
  284. self.conchFactory.proto.transport.loseConnection()
  285. deferreds = [
  286. defer.maybeDeferred(self.conchServer.stopListening),
  287. defer.maybeDeferred(self.echoServer.stopListening),
  288. ]
  289. if HAS_IPV6:
  290. deferreds.append(defer.maybeDeferred(self.echoServerV6.stopListening))
  291. return defer.gatherResults(deferreds)
  292. class ForwardingMixin(ConchServerSetupMixin):
  293. """
  294. Template class for tests of the Conch server's ability to forward arbitrary
  295. protocols over SSH.
  296. These tests are integration tests, not unit tests. They launch a Conch
  297. server, a custom TCP server (just an L{EchoProtocol}) and then call
  298. L{execute}.
  299. L{execute} is implemented by subclasses of L{ForwardingMixin}. It should
  300. cause an SSH client to connect to the Conch server, asking it to forward
  301. data to the custom TCP server.
  302. """
  303. def test_exec(self):
  304. """
  305. Test that we can use whatever client to send the command "echo goodbye"
  306. to the Conch server. Make sure we receive "goodbye" back from the
  307. server.
  308. """
  309. d = self.execute('echo goodbye', ConchTestOpenSSHProcess())
  310. return d.addCallback(self.assertEqual, b'goodbye\n')
  311. def test_localToRemoteForwarding(self):
  312. """
  313. Test that we can use whatever client to forward a local port to a
  314. specified port on the server.
  315. """
  316. localPort = self._getFreePort()
  317. process = ConchTestForwardingProcess(localPort, b'test\n')
  318. d = self.execute('', process,
  319. sshArgs='-N -L%i:127.0.0.1:%i'
  320. % (localPort, self.echoPort))
  321. d.addCallback(self.assertEqual, b'test\n')
  322. return d
  323. def test_remoteToLocalForwarding(self):
  324. """
  325. Test that we can use whatever client to forward a port from the server
  326. to a port locally.
  327. """
  328. localPort = self._getFreePort()
  329. process = ConchTestForwardingProcess(localPort, b'test\n')
  330. d = self.execute('', process,
  331. sshArgs='-N -R %i:127.0.0.1:%i'
  332. % (localPort, self.echoPort))
  333. d.addCallback(self.assertEqual, b'test\n')
  334. return d
  335. # Conventionally there is a separate adapter object which provides ISession for
  336. # the user, but making the user provide ISession directly works too. This isn't
  337. # a full implementation of ISession though, just enough to make these tests
  338. # pass.
  339. @implementer(ISession)
  340. class RekeyAvatar(ConchUser):
  341. """
  342. This avatar implements a shell which sends 60 numbered lines to whatever
  343. connects to it, then closes the session with a 0 exit status.
  344. 60 lines is selected as being enough to send more than 2kB of traffic, the
  345. amount the client is configured to initiate a rekey after.
  346. """
  347. def __init__(self):
  348. ConchUser.__init__(self)
  349. self.channelLookup[b'session'] = SSHSession
  350. def openShell(self, transport):
  351. """
  352. Write 60 lines of data to the transport, then exit.
  353. """
  354. proto = protocol.Protocol()
  355. proto.makeConnection(transport)
  356. transport.makeConnection(wrapProtocol(proto))
  357. # Send enough bytes to the connection so that a rekey is triggered in
  358. # the client.
  359. def write(counter):
  360. i = next(counter)
  361. if i == 60:
  362. call.stop()
  363. transport.session.conn.sendRequest(
  364. transport.session, b'exit-status', b'\x00\x00\x00\x00')
  365. transport.loseConnection()
  366. else:
  367. line = "line #%02d\n" % (i,)
  368. line = line.encode("utf-8")
  369. transport.write(line)
  370. # The timing for this loop is an educated guess (and/or the result of
  371. # experimentation) to exercise the case where a packet is generated
  372. # mid-rekey. Since the other side of the connection is (so far) the
  373. # OpenSSH command line client, there's no easy way to determine when the
  374. # rekey has been initiated. If there were, then generating a packet
  375. # immediately at that time would be a better way to test the
  376. # functionality being tested here.
  377. call = LoopingCall(write, count())
  378. call.start(0.01)
  379. def closed(self):
  380. """
  381. Ignore the close of the session.
  382. """
  383. class RekeyRealm:
  384. """
  385. This realm gives out new L{RekeyAvatar} instances for any avatar request.
  386. """
  387. def requestAvatar(self, avatarID, mind, *interfaces):
  388. return interfaces[0], RekeyAvatar(), lambda: None
  389. class RekeyTestsMixin(ConchServerSetupMixin):
  390. """
  391. TestCase mixin which defines tests exercising L{SSHTransportBase}'s handling
  392. of rekeying messages.
  393. """
  394. realmFactory = RekeyRealm
  395. def test_clientRekey(self):
  396. """
  397. After a client-initiated rekey is completed, application data continues
  398. to be passed over the SSH connection.
  399. """
  400. process = ConchTestOpenSSHProcess()
  401. d = self.execute("", process, '-o RekeyLimit=2K')
  402. def finished(result):
  403. expectedResult = '\n'.join(['line #%02d' % (i,) for i in range(60)]) + '\n'
  404. expectedResult = expectedResult.encode("utf-8")
  405. self.assertEqual(result, expectedResult)
  406. d.addCallback(finished)
  407. return d
  408. class OpenSSHClientMixin:
  409. if not which('ssh'):
  410. skip = "no ssh command-line client available"
  411. def execute(self, remoteCommand, process, sshArgs=''):
  412. """
  413. Connects to the SSH server started in L{ConchServerSetupMixin.setUp} by
  414. running the 'ssh' command line tool.
  415. @type remoteCommand: str
  416. @param remoteCommand: The command (with arguments) to run on the
  417. remote end.
  418. @type process: L{ConchTestOpenSSHProcess}
  419. @type sshArgs: str
  420. @param sshArgs: Arguments to pass to the 'ssh' process.
  421. @return: L{defer.Deferred}
  422. """
  423. # PubkeyAcceptedKeyTypes does not exist prior to OpenSSH 7.0 so we
  424. # first need to check if we can set it. If we can, -V will just print
  425. # the version without doing anything else; if we can't, we will get a
  426. # configuration error.
  427. d = getProcessValue(
  428. which('ssh')[0], ('-o', 'PubkeyAcceptedKeyTypes=ssh-dss', '-V'))
  429. def hasPAKT(status):
  430. if status == 0:
  431. opts = '-oPubkeyAcceptedKeyTypes=ssh-dss '
  432. else:
  433. opts = ''
  434. process.deferred = defer.Deferred()
  435. # Pass -F /dev/null to avoid the user's configuration file from
  436. # being loaded, as it may contain settings that cause our tests to
  437. # fail or hang.
  438. cmdline = ('ssh -2 -l testuser -p %i '
  439. '-F /dev/null '
  440. '-oUserKnownHostsFile=kh_test '
  441. '-oPasswordAuthentication=no '
  442. # Always use the RSA key, since that's the one in kh_test.
  443. '-oHostKeyAlgorithms=ssh-rsa '
  444. '-a '
  445. '-i dsa_test ') + opts + sshArgs + \
  446. ' 127.0.0.1 ' + remoteCommand
  447. port = self.conchServer.getHost().port
  448. cmds = (cmdline % port).split()
  449. encodedCmds = []
  450. for cmd in cmds:
  451. if isinstance(cmd, unicode):
  452. cmd = cmd.encode("utf-8")
  453. encodedCmds.append(cmd)
  454. reactor.spawnProcess(process, which('ssh')[0], encodedCmds)
  455. return process.deferred
  456. return d.addCallback(hasPAKT)
  457. class OpenSSHKeyExchangeTests(ConchServerSetupMixin, OpenSSHClientMixin,
  458. unittest.TestCase):
  459. """
  460. Tests L{SSHTransportBase}'s key exchange algorithm compatibility with
  461. OpenSSH.
  462. """
  463. def assertExecuteWithKexAlgorithm(self, keyExchangeAlgo):
  464. """
  465. Call execute() method of L{OpenSSHClientMixin} with an ssh option that
  466. forces the exclusive use of the key exchange algorithm specified by
  467. keyExchangeAlgo
  468. @type keyExchangeAlgo: L{str}
  469. @param keyExchangeAlgo: The key exchange algorithm to use
  470. @return: L{defer.Deferred}
  471. """
  472. kexAlgorithms = []
  473. try:
  474. output = subprocess.check_output([which('ssh')[0], '-Q', 'kex'],
  475. stderr=subprocess.STDOUT)
  476. if not isinstance(output, str):
  477. output = output.decode("utf-8")
  478. kexAlgorithms = output.split()
  479. except:
  480. pass
  481. if keyExchangeAlgo not in kexAlgorithms:
  482. raise unittest.SkipTest(
  483. "{} not supported by ssh client".format(
  484. keyExchangeAlgo))
  485. d = self.execute('echo hello', ConchTestOpenSSHProcess(),
  486. '-oKexAlgorithms=' + keyExchangeAlgo)
  487. return d.addCallback(self.assertEqual, b'hello\n')
  488. def test_ECDHSHA256(self):
  489. """
  490. The ecdh-sha2-nistp256 key exchange algorithm is compatible with
  491. OpenSSH
  492. """
  493. return self.assertExecuteWithKexAlgorithm(
  494. 'ecdh-sha2-nistp256')
  495. def test_ECDHSHA384(self):
  496. """
  497. The ecdh-sha2-nistp384 key exchange algorithm is compatible with
  498. OpenSSH
  499. """
  500. return self.assertExecuteWithKexAlgorithm(
  501. 'ecdh-sha2-nistp384')
  502. def test_ECDHSHA521(self):
  503. """
  504. The ecdh-sha2-nistp521 key exchange algorithm is compatible with
  505. OpenSSH
  506. """
  507. return self.assertExecuteWithKexAlgorithm(
  508. 'ecdh-sha2-nistp521')
  509. def test_DH_GROUP14(self):
  510. """
  511. The diffie-hellman-group14-sha1 key exchange algorithm is compatible
  512. with OpenSSH.
  513. """
  514. return self.assertExecuteWithKexAlgorithm(
  515. 'diffie-hellman-group14-sha1')
  516. def test_DH_GROUP_EXCHANGE_SHA1(self):
  517. """
  518. The diffie-hellman-group-exchange-sha1 key exchange algorithm is
  519. compatible with OpenSSH.
  520. """
  521. return self.assertExecuteWithKexAlgorithm(
  522. 'diffie-hellman-group-exchange-sha1')
  523. def test_DH_GROUP_EXCHANGE_SHA256(self):
  524. """
  525. The diffie-hellman-group-exchange-sha256 key exchange algorithm is
  526. compatible with OpenSSH.
  527. """
  528. return self.assertExecuteWithKexAlgorithm(
  529. 'diffie-hellman-group-exchange-sha256')
  530. def test_unsupported_algorithm(self):
  531. """
  532. The list of key exchange algorithms supported
  533. by OpenSSH client is obtained with C{ssh -Q kex}.
  534. """
  535. self.assertRaises(unittest.SkipTest,
  536. self.assertExecuteWithKexAlgorithm,
  537. 'unsupported-algorithm')
  538. class OpenSSHClientForwardingTests(ForwardingMixin, OpenSSHClientMixin,
  539. unittest.TestCase):
  540. """
  541. Connection forwarding tests run against the OpenSSL command line client.
  542. """
  543. def test_localToRemoteForwardingV6(self):
  544. """
  545. Forwarding of arbitrary IPv6 TCP connections via SSH.
  546. """
  547. localPort = self._getFreePort()
  548. process = ConchTestForwardingProcess(localPort, b'test\n')
  549. d = self.execute('', process,
  550. sshArgs='-N -L%i:[::1]:%i'
  551. % (localPort, self.echoPortV6))
  552. d.addCallback(self.assertEqual, b'test\n')
  553. return d
  554. if not HAS_IPV6:
  555. test_localToRemoteForwardingV6.skip = "Requires IPv6 support"
  556. class OpenSSHClientRekeyTests(RekeyTestsMixin, OpenSSHClientMixin,
  557. unittest.TestCase):
  558. """
  559. Rekeying tests run against the OpenSSL command line client.
  560. """
  561. class CmdLineClientTests(ForwardingMixin, unittest.TestCase):
  562. """
  563. Connection forwarding tests run against the Conch command line client.
  564. """
  565. if runtime.platformType == 'win32':
  566. skip = "can't run cmdline client on win32"
  567. def execute(self, remoteCommand, process, sshArgs='', conchArgs=None):
  568. """
  569. As for L{OpenSSHClientTestCase.execute}, except it runs the 'conch'
  570. command line tool, not 'ssh'.
  571. """
  572. if conchArgs is None:
  573. conchArgs = []
  574. process.deferred = defer.Deferred()
  575. port = self.conchServer.getHost().port
  576. cmd = ('-p {} -l testuser '
  577. '--known-hosts kh_test '
  578. '--user-authentications publickey '
  579. '-a '
  580. '-i dsa_test '
  581. '-v '.format(port) + sshArgs +
  582. ' 127.0.0.1 ' + remoteCommand)
  583. cmds = _makeArgs(conchArgs + cmd.split())
  584. env = os.environ.copy()
  585. env['PYTHONPATH'] = os.pathsep.join(sys.path)
  586. encodedCmds = []
  587. encodedEnv = {}
  588. for cmd in cmds:
  589. if isinstance(cmd, unicode):
  590. cmd = cmd.encode("utf-8")
  591. encodedCmds.append(cmd)
  592. for var in env:
  593. val = env[var]
  594. if isinstance(var, unicode):
  595. var = var.encode("utf-8")
  596. if isinstance(val, unicode):
  597. val = val.encode("utf-8")
  598. encodedEnv[var] = val
  599. reactor.spawnProcess(process, sys.executable, encodedCmds, env=encodedEnv)
  600. return process.deferred
  601. def test_runWithLogFile(self):
  602. """
  603. It can store logs to a local file.
  604. """
  605. def cb_check_log(result):
  606. logContent = logPath.getContent()
  607. self.assertIn(b'Log opened.', logContent)
  608. logPath = filepath.FilePath(self.mktemp())
  609. d = self.execute(
  610. remoteCommand='echo goodbye',
  611. process=ConchTestOpenSSHProcess(),
  612. conchArgs=['--log', '--logfile', logPath.path,
  613. '--host-key-algorithms', 'ssh-rsa']
  614. )
  615. d.addCallback(self.assertEqual, b'goodbye\n')
  616. d.addCallback(cb_check_log)
  617. return d
  618. def test_runWithNoHostAlgorithmsSpecified(self):
  619. """
  620. Do not use --host-key-algorithms flag on command line.
  621. """
  622. d = self.execute(
  623. remoteCommand='echo goodbye',
  624. process=ConchTestOpenSSHProcess()
  625. )
  626. d.addCallback(self.assertEqual, b'goodbye\n')
  627. return d