test_userauth.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for the implementation of the ssh-userauth service.
  5. Maintainer: Paul Swartz
  6. """
  7. from __future__ import absolute_import, division
  8. from zope.interface import implementer
  9. from twisted.cred.checkers import ICredentialsChecker
  10. from twisted.cred.credentials import IUsernamePassword, ISSHPrivateKey
  11. from twisted.cred.credentials import IAnonymous
  12. from twisted.cred.error import UnauthorizedLogin
  13. from twisted.cred.portal import IRealm, Portal
  14. from twisted.conch.error import ConchError, ValidPublicKey
  15. from twisted.internet import defer, task
  16. from twisted.protocols import loopback
  17. from twisted.python.reflect import requireModule
  18. from twisted.trial import unittest
  19. from twisted.python.compat import _bytesChr as chr
  20. if requireModule('cryptography') and requireModule('pyasn1'):
  21. from twisted.conch.ssh.common import NS
  22. from twisted.conch.checkers import SSHProtocolChecker
  23. from twisted.conch.ssh import keys, userauth, transport
  24. from twisted.conch.test import keydata
  25. else:
  26. keys = None
  27. class transport:
  28. class SSHTransportBase:
  29. """
  30. A stub class so that later class definitions won't die.
  31. """
  32. class userauth:
  33. class SSHUserAuthClient:
  34. """
  35. A stub class so that later class definitions won't die.
  36. """
  37. class ClientUserAuth(userauth.SSHUserAuthClient):
  38. """
  39. A mock user auth client.
  40. """
  41. def getPublicKey(self):
  42. """
  43. If this is the first time we've been called, return a blob for
  44. the DSA key. Otherwise, return a blob
  45. for the RSA key.
  46. """
  47. if self.lastPublicKey:
  48. return keys.Key.fromString(keydata.publicRSA_openssh)
  49. else:
  50. return defer.succeed(
  51. keys.Key.fromString(keydata.publicDSA_openssh))
  52. def getPrivateKey(self):
  53. """
  54. Return the private key object for the RSA key.
  55. """
  56. return defer.succeed(keys.Key.fromString(keydata.privateRSA_openssh))
  57. def getPassword(self, prompt=None):
  58. """
  59. Return 'foo' as the password.
  60. """
  61. return defer.succeed(b'foo')
  62. def getGenericAnswers(self, name, information, answers):
  63. """
  64. Return 'foo' as the answer to two questions.
  65. """
  66. return defer.succeed(('foo', 'foo'))
  67. class OldClientAuth(userauth.SSHUserAuthClient):
  68. """
  69. The old SSHUserAuthClient returned a cryptography key object from
  70. getPrivateKey() and a string from getPublicKey
  71. """
  72. def getPrivateKey(self):
  73. return defer.succeed(keys.Key.fromString(
  74. keydata.privateRSA_openssh).keyObject)
  75. def getPublicKey(self):
  76. return keys.Key.fromString(keydata.publicRSA_openssh).blob()
  77. class ClientAuthWithoutPrivateKey(userauth.SSHUserAuthClient):
  78. """
  79. This client doesn't have a private key, but it does have a public key.
  80. """
  81. def getPrivateKey(self):
  82. return
  83. def getPublicKey(self):
  84. return keys.Key.fromString(keydata.publicRSA_openssh)
  85. class FakeTransport(transport.SSHTransportBase):
  86. """
  87. L{userauth.SSHUserAuthServer} expects an SSH transport which has a factory
  88. attribute which has a portal attribute. Because the portal is important for
  89. testing authentication, we need to be able to provide an interesting portal
  90. object to the L{SSHUserAuthServer}.
  91. In addition, we want to be able to capture any packets sent over the
  92. transport.
  93. @ivar packets: a list of 2-tuples: (messageType, data). Each 2-tuple is
  94. a sent packet.
  95. @type packets: C{list}
  96. @param lostConnecion: True if loseConnection has been called on us.
  97. @type lostConnection: L{bool}
  98. """
  99. class Service(object):
  100. """
  101. A mock service, representing the other service offered by the server.
  102. """
  103. name = b'nancy'
  104. def serviceStarted(self):
  105. pass
  106. class Factory(object):
  107. """
  108. A mock factory, representing the factory that spawned this user auth
  109. service.
  110. """
  111. def getService(self, transport, service):
  112. """
  113. Return our fake service.
  114. """
  115. if service == b'none':
  116. return FakeTransport.Service
  117. def __init__(self, portal):
  118. self.factory = self.Factory()
  119. self.factory.portal = portal
  120. self.lostConnection = False
  121. self.transport = self
  122. self.packets = []
  123. def sendPacket(self, messageType, message):
  124. """
  125. Record the packet sent by the service.
  126. """
  127. self.packets.append((messageType, message))
  128. def isEncrypted(self, direction):
  129. """
  130. Pretend that this transport encrypts traffic in both directions. The
  131. SSHUserAuthServer disables password authentication if the transport
  132. isn't encrypted.
  133. """
  134. return True
  135. def loseConnection(self):
  136. self.lostConnection = True
  137. @implementer(IRealm)
  138. class Realm(object):
  139. """
  140. A mock realm for testing L{userauth.SSHUserAuthServer}.
  141. This realm is not actually used in the course of testing, so it returns the
  142. simplest thing that could possibly work.
  143. """
  144. def requestAvatar(self, avatarId, mind, *interfaces):
  145. return defer.succeed((interfaces[0], None, lambda: None))
  146. @implementer(ICredentialsChecker)
  147. class PasswordChecker(object):
  148. """
  149. A very simple username/password checker which authenticates anyone whose
  150. password matches their username and rejects all others.
  151. """
  152. credentialInterfaces = (IUsernamePassword,)
  153. def requestAvatarId(self, creds):
  154. if creds.username == creds.password:
  155. return defer.succeed(creds.username)
  156. return defer.fail(UnauthorizedLogin("Invalid username/password pair"))
  157. @implementer(ICredentialsChecker)
  158. class PrivateKeyChecker(object):
  159. """
  160. A very simple public key checker which authenticates anyone whose
  161. public/private keypair is the same keydata.public/privateRSA_openssh.
  162. """
  163. credentialInterfaces = (ISSHPrivateKey,)
  164. def requestAvatarId(self, creds):
  165. if creds.blob == keys.Key.fromString(keydata.publicRSA_openssh).blob():
  166. if creds.signature is not None:
  167. obj = keys.Key.fromString(creds.blob)
  168. if obj.verify(creds.signature, creds.sigData):
  169. return creds.username
  170. else:
  171. raise ValidPublicKey()
  172. raise UnauthorizedLogin()
  173. @implementer(ICredentialsChecker)
  174. class AnonymousChecker(object):
  175. """
  176. A simple checker which isn't supported by L{SSHUserAuthServer}.
  177. """
  178. credentialInterfaces = (IAnonymous,)
  179. class SSHUserAuthServerTests(unittest.TestCase):
  180. """
  181. Tests for SSHUserAuthServer.
  182. """
  183. if keys is None:
  184. skip = "cannot run without cryptography"
  185. def setUp(self):
  186. self.realm = Realm()
  187. self.portal = Portal(self.realm)
  188. self.portal.registerChecker(PasswordChecker())
  189. self.portal.registerChecker(PrivateKeyChecker())
  190. self.authServer = userauth.SSHUserAuthServer()
  191. self.authServer.transport = FakeTransport(self.portal)
  192. self.authServer.serviceStarted()
  193. self.authServer.supportedAuthentications.sort() # give a consistent
  194. # order
  195. def tearDown(self):
  196. self.authServer.serviceStopped()
  197. self.authServer = None
  198. def _checkFailed(self, ignored):
  199. """
  200. Check that the authentication has failed.
  201. """
  202. self.assertEqual(self.authServer.transport.packets[-1],
  203. (userauth.MSG_USERAUTH_FAILURE,
  204. NS(b'password,publickey') + b'\x00'))
  205. def test_noneAuthentication(self):
  206. """
  207. A client may request a list of authentication 'method name' values
  208. that may continue by using the "none" authentication 'method name'.
  209. See RFC 4252 Section 5.2.
  210. """
  211. d = self.authServer.ssh_USERAUTH_REQUEST(NS(b'foo') + NS(b'service') +
  212. NS(b'none'))
  213. return d.addCallback(self._checkFailed)
  214. def test_successfulPasswordAuthentication(self):
  215. """
  216. When provided with correct password authentication information, the
  217. server should respond by sending a MSG_USERAUTH_SUCCESS message with
  218. no other data.
  219. See RFC 4252, Section 5.1.
  220. """
  221. packet = b''.join([NS(b'foo'), NS(b'none'), NS(b'password'), chr(0),
  222. NS(b'foo')])
  223. d = self.authServer.ssh_USERAUTH_REQUEST(packet)
  224. def check(ignored):
  225. self.assertEqual(
  226. self.authServer.transport.packets,
  227. [(userauth.MSG_USERAUTH_SUCCESS, b'')])
  228. return d.addCallback(check)
  229. def test_failedPasswordAuthentication(self):
  230. """
  231. When provided with invalid authentication details, the server should
  232. respond by sending a MSG_USERAUTH_FAILURE message which states whether
  233. the authentication was partially successful, and provides other, open
  234. options for authentication.
  235. See RFC 4252, Section 5.1.
  236. """
  237. # packet = username, next_service, authentication type, FALSE, password
  238. packet = b''.join([NS(b'foo'), NS(b'none'), NS(b'password'), chr(0),
  239. NS(b'bar')])
  240. self.authServer.clock = task.Clock()
  241. d = self.authServer.ssh_USERAUTH_REQUEST(packet)
  242. self.assertEqual(self.authServer.transport.packets, [])
  243. self.authServer.clock.advance(2)
  244. return d.addCallback(self._checkFailed)
  245. def test_successfulPrivateKeyAuthentication(self):
  246. """
  247. Test that private key authentication completes successfully,
  248. """
  249. blob = keys.Key.fromString(keydata.publicRSA_openssh).blob()
  250. obj = keys.Key.fromString(keydata.privateRSA_openssh)
  251. packet = (NS(b'foo') + NS(b'none') + NS(b'publickey') + b'\xff'
  252. + NS(obj.sshType()) + NS(blob))
  253. self.authServer.transport.sessionID = b'test'
  254. signature = obj.sign(NS(b'test') + chr(userauth.MSG_USERAUTH_REQUEST)
  255. + packet)
  256. packet += NS(signature)
  257. d = self.authServer.ssh_USERAUTH_REQUEST(packet)
  258. def check(ignored):
  259. self.assertEqual(self.authServer.transport.packets,
  260. [(userauth.MSG_USERAUTH_SUCCESS, b'')])
  261. return d.addCallback(check)
  262. def test_requestRaisesConchError(self):
  263. """
  264. ssh_USERAUTH_REQUEST should raise a ConchError if tryAuth returns
  265. None. Added to catch a bug noticed by pyflakes.
  266. """
  267. d = defer.Deferred()
  268. def mockCbFinishedAuth(self, ignored):
  269. self.fail('request should have raised ConochError')
  270. def mockTryAuth(kind, user, data):
  271. return None
  272. def mockEbBadAuth(reason):
  273. d.errback(reason.value)
  274. self.patch(self.authServer, 'tryAuth', mockTryAuth)
  275. self.patch(self.authServer, '_cbFinishedAuth', mockCbFinishedAuth)
  276. self.patch(self.authServer, '_ebBadAuth', mockEbBadAuth)
  277. packet = NS(b'user') + NS(b'none') + NS(b'public-key') + NS(b'data')
  278. # If an error other than ConchError is raised, this will trigger an
  279. # exception.
  280. self.authServer.ssh_USERAUTH_REQUEST(packet)
  281. return self.assertFailure(d, ConchError)
  282. def test_verifyValidPrivateKey(self):
  283. """
  284. Test that verifying a valid private key works.
  285. """
  286. blob = keys.Key.fromString(keydata.publicRSA_openssh).blob()
  287. packet = (NS(b'foo') + NS(b'none') + NS(b'publickey') + b'\x00'
  288. + NS(b'ssh-rsa') + NS(blob))
  289. d = self.authServer.ssh_USERAUTH_REQUEST(packet)
  290. def check(ignored):
  291. self.assertEqual(self.authServer.transport.packets,
  292. [(userauth.MSG_USERAUTH_PK_OK, NS(b'ssh-rsa') + NS(blob))])
  293. return d.addCallback(check)
  294. def test_failedPrivateKeyAuthenticationWithoutSignature(self):
  295. """
  296. Test that private key authentication fails when the public key
  297. is invalid.
  298. """
  299. blob = keys.Key.fromString(keydata.publicDSA_openssh).blob()
  300. packet = (NS(b'foo') + NS(b'none') + NS(b'publickey') + b'\x00'
  301. + NS(b'ssh-dsa') + NS(blob))
  302. d = self.authServer.ssh_USERAUTH_REQUEST(packet)
  303. return d.addCallback(self._checkFailed)
  304. def test_failedPrivateKeyAuthenticationWithSignature(self):
  305. """
  306. Test that private key authentication fails when the public key
  307. is invalid.
  308. """
  309. blob = keys.Key.fromString(keydata.publicRSA_openssh).blob()
  310. obj = keys.Key.fromString(keydata.privateRSA_openssh)
  311. packet = (NS(b'foo') + NS(b'none') + NS(b'publickey') + b'\xff'
  312. + NS(b'ssh-rsa') + NS(blob) + NS(obj.sign(blob)))
  313. self.authServer.transport.sessionID = b'test'
  314. d = self.authServer.ssh_USERAUTH_REQUEST(packet)
  315. return d.addCallback(self._checkFailed)
  316. def test_ignoreUnknownCredInterfaces(self):
  317. """
  318. L{SSHUserAuthServer} sets up
  319. C{SSHUserAuthServer.supportedAuthentications} by checking the portal's
  320. credentials interfaces and mapping them to SSH authentication method
  321. strings. If the Portal advertises an interface that
  322. L{SSHUserAuthServer} can't map, it should be ignored. This is a white
  323. box test.
  324. """
  325. server = userauth.SSHUserAuthServer()
  326. server.transport = FakeTransport(self.portal)
  327. self.portal.registerChecker(AnonymousChecker())
  328. server.serviceStarted()
  329. server.serviceStopped()
  330. server.supportedAuthentications.sort() # give a consistent order
  331. self.assertEqual(server.supportedAuthentications,
  332. [b'password', b'publickey'])
  333. def test_removePasswordIfUnencrypted(self):
  334. """
  335. Test that the userauth service does not advertise password
  336. authentication if the password would be send in cleartext.
  337. """
  338. self.assertIn(b'password', self.authServer.supportedAuthentications)
  339. # no encryption
  340. clearAuthServer = userauth.SSHUserAuthServer()
  341. clearAuthServer.transport = FakeTransport(self.portal)
  342. clearAuthServer.transport.isEncrypted = lambda x: False
  343. clearAuthServer.serviceStarted()
  344. clearAuthServer.serviceStopped()
  345. self.assertNotIn(b'password', clearAuthServer.supportedAuthentications)
  346. # only encrypt incoming (the direction the password is sent)
  347. halfAuthServer = userauth.SSHUserAuthServer()
  348. halfAuthServer.transport = FakeTransport(self.portal)
  349. halfAuthServer.transport.isEncrypted = lambda x: x == 'in'
  350. halfAuthServer.serviceStarted()
  351. halfAuthServer.serviceStopped()
  352. self.assertIn(b'password', halfAuthServer.supportedAuthentications)
  353. def test_unencryptedConnectionWithoutPasswords(self):
  354. """
  355. If the L{SSHUserAuthServer} is not advertising passwords, then an
  356. unencrypted connection should not cause any warnings or exceptions.
  357. This is a white box test.
  358. """
  359. # create a Portal without password authentication
  360. portal = Portal(self.realm)
  361. portal.registerChecker(PrivateKeyChecker())
  362. # no encryption
  363. clearAuthServer = userauth.SSHUserAuthServer()
  364. clearAuthServer.transport = FakeTransport(portal)
  365. clearAuthServer.transport.isEncrypted = lambda x: False
  366. clearAuthServer.serviceStarted()
  367. clearAuthServer.serviceStopped()
  368. self.assertEqual(clearAuthServer.supportedAuthentications,
  369. [b'publickey'])
  370. # only encrypt incoming (the direction the password is sent)
  371. halfAuthServer = userauth.SSHUserAuthServer()
  372. halfAuthServer.transport = FakeTransport(portal)
  373. halfAuthServer.transport.isEncrypted = lambda x: x == 'in'
  374. halfAuthServer.serviceStarted()
  375. halfAuthServer.serviceStopped()
  376. self.assertEqual(clearAuthServer.supportedAuthentications,
  377. [b'publickey'])
  378. def test_loginTimeout(self):
  379. """
  380. Test that the login times out.
  381. """
  382. timeoutAuthServer = userauth.SSHUserAuthServer()
  383. timeoutAuthServer.clock = task.Clock()
  384. timeoutAuthServer.transport = FakeTransport(self.portal)
  385. timeoutAuthServer.serviceStarted()
  386. timeoutAuthServer.clock.advance(11 * 60 * 60)
  387. timeoutAuthServer.serviceStopped()
  388. self.assertEqual(timeoutAuthServer.transport.packets,
  389. [(transport.MSG_DISCONNECT,
  390. b'\x00' * 3 +
  391. chr(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE) +
  392. NS(b"you took too long") + NS(b''))])
  393. self.assertTrue(timeoutAuthServer.transport.lostConnection)
  394. def test_cancelLoginTimeout(self):
  395. """
  396. Test that stopping the service also stops the login timeout.
  397. """
  398. timeoutAuthServer = userauth.SSHUserAuthServer()
  399. timeoutAuthServer.clock = task.Clock()
  400. timeoutAuthServer.transport = FakeTransport(self.portal)
  401. timeoutAuthServer.serviceStarted()
  402. timeoutAuthServer.serviceStopped()
  403. timeoutAuthServer.clock.advance(11 * 60 * 60)
  404. self.assertEqual(timeoutAuthServer.transport.packets, [])
  405. self.assertFalse(timeoutAuthServer.transport.lostConnection)
  406. def test_tooManyAttempts(self):
  407. """
  408. Test that the server disconnects if the client fails authentication
  409. too many times.
  410. """
  411. packet = b''.join([NS(b'foo'), NS(b'none'), NS(b'password'), chr(0),
  412. NS(b'bar')])
  413. self.authServer.clock = task.Clock()
  414. for i in range(21):
  415. d = self.authServer.ssh_USERAUTH_REQUEST(packet)
  416. self.authServer.clock.advance(2)
  417. def check(ignored):
  418. self.assertEqual(self.authServer.transport.packets[-1],
  419. (transport.MSG_DISCONNECT,
  420. b'\x00' * 3 +
  421. chr(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE) +
  422. NS(b"too many bad auths") + NS(b'')))
  423. return d.addCallback(check)
  424. def test_failIfUnknownService(self):
  425. """
  426. If the user requests a service that we don't support, the
  427. authentication should fail.
  428. """
  429. packet = NS(b'foo') + NS(b'') + NS(b'password') + chr(0) + NS(b'foo')
  430. self.authServer.clock = task.Clock()
  431. d = self.authServer.ssh_USERAUTH_REQUEST(packet)
  432. return d.addCallback(self._checkFailed)
  433. def test_tryAuthEdgeCases(self):
  434. """
  435. tryAuth() has two edge cases that are difficult to reach.
  436. 1) an authentication method auth_* returns None instead of a Deferred.
  437. 2) an authentication type that is defined does not have a matching
  438. auth_* method.
  439. Both these cases should return a Deferred which fails with a
  440. ConchError.
  441. """
  442. def mockAuth(packet):
  443. return None
  444. self.patch(self.authServer, 'auth_publickey', mockAuth) # first case
  445. self.patch(self.authServer, 'auth_password', None) # second case
  446. def secondTest(ignored):
  447. d2 = self.authServer.tryAuth(b'password', None, None)
  448. return self.assertFailure(d2, ConchError)
  449. d1 = self.authServer.tryAuth(b'publickey', None, None)
  450. return self.assertFailure(d1, ConchError).addCallback(secondTest)
  451. class SSHUserAuthClientTests(unittest.TestCase):
  452. """
  453. Tests for SSHUserAuthClient.
  454. """
  455. if keys is None:
  456. skip = "cannot run without cryptography"
  457. def setUp(self):
  458. self.authClient = ClientUserAuth(b'foo', FakeTransport.Service())
  459. self.authClient.transport = FakeTransport(None)
  460. self.authClient.transport.sessionID = b'test'
  461. self.authClient.serviceStarted()
  462. def tearDown(self):
  463. self.authClient.serviceStopped()
  464. self.authClient = None
  465. def test_init(self):
  466. """
  467. Test that client is initialized properly.
  468. """
  469. self.assertEqual(self.authClient.user, b'foo')
  470. self.assertEqual(self.authClient.instance.name, b'nancy')
  471. self.assertEqual(self.authClient.transport.packets,
  472. [(userauth.MSG_USERAUTH_REQUEST, NS(b'foo') + NS(b'nancy')
  473. + NS(b'none'))])
  474. def test_USERAUTH_SUCCESS(self):
  475. """
  476. Test that the client succeeds properly.
  477. """
  478. instance = [None]
  479. def stubSetService(service):
  480. instance[0] = service
  481. self.authClient.transport.setService = stubSetService
  482. self.authClient.ssh_USERAUTH_SUCCESS(b'')
  483. self.assertEqual(instance[0], self.authClient.instance)
  484. def test_publickey(self):
  485. """
  486. Test that the client can authenticate with a public key.
  487. """
  488. self.authClient.ssh_USERAUTH_FAILURE(NS(b'publickey') + b'\x00')
  489. self.assertEqual(self.authClient.transport.packets[-1],
  490. (userauth.MSG_USERAUTH_REQUEST, NS(b'foo') + NS(b'nancy')
  491. + NS(b'publickey') + b'\x00' + NS(b'ssh-dss')
  492. + NS(keys.Key.fromString(
  493. keydata.publicDSA_openssh).blob())))
  494. # that key isn't good
  495. self.authClient.ssh_USERAUTH_FAILURE(NS(b'publickey') + b'\x00')
  496. blob = NS(keys.Key.fromString(keydata.publicRSA_openssh).blob())
  497. self.assertEqual(self.authClient.transport.packets[-1],
  498. (userauth.MSG_USERAUTH_REQUEST, (NS(b'foo') + NS(b'nancy')
  499. + NS(b'publickey') + b'\x00' + NS(b'ssh-rsa') + blob)))
  500. self.authClient.ssh_USERAUTH_PK_OK(NS(b'ssh-rsa')
  501. + NS(keys.Key.fromString(keydata.publicRSA_openssh).blob()))
  502. sigData = (NS(self.authClient.transport.sessionID)
  503. + chr(userauth.MSG_USERAUTH_REQUEST) + NS(b'foo')
  504. + NS(b'nancy') + NS(b'publickey') + b'\x01' + NS(b'ssh-rsa')
  505. + blob)
  506. obj = keys.Key.fromString(keydata.privateRSA_openssh)
  507. self.assertEqual(self.authClient.transport.packets[-1],
  508. (userauth.MSG_USERAUTH_REQUEST, NS(b'foo') + NS(b'nancy')
  509. + NS(b'publickey') + b'\x01' + NS(b'ssh-rsa') + blob
  510. + NS(obj.sign(sigData))))
  511. def test_publickey_without_privatekey(self):
  512. """
  513. If the SSHUserAuthClient doesn't return anything from signData,
  514. the client should start the authentication over again by requesting
  515. 'none' authentication.
  516. """
  517. authClient = ClientAuthWithoutPrivateKey(b'foo',
  518. FakeTransport.Service())
  519. authClient.transport = FakeTransport(None)
  520. authClient.transport.sessionID = b'test'
  521. authClient.serviceStarted()
  522. authClient.tryAuth(b'publickey')
  523. authClient.transport.packets = []
  524. self.assertIsNone(authClient.ssh_USERAUTH_PK_OK(b''))
  525. self.assertEqual(authClient.transport.packets, [
  526. (userauth.MSG_USERAUTH_REQUEST, NS(b'foo') + NS(b'nancy') +
  527. NS(b'none'))])
  528. def test_no_publickey(self):
  529. """
  530. If there's no public key, auth_publickey should return a Deferred
  531. called back with a False value.
  532. """
  533. self.authClient.getPublicKey = lambda x: None
  534. d = self.authClient.tryAuth(b'publickey')
  535. def check(result):
  536. self.assertFalse(result)
  537. return d.addCallback(check)
  538. def test_password(self):
  539. """
  540. Test that the client can authentication with a password. This
  541. includes changing the password.
  542. """
  543. self.authClient.ssh_USERAUTH_FAILURE(NS(b'password') + b'\x00')
  544. self.assertEqual(self.authClient.transport.packets[-1],
  545. (userauth.MSG_USERAUTH_REQUEST, NS(b'foo') + NS(b'nancy')
  546. + NS(b'password') + b'\x00' + NS(b'foo')))
  547. self.authClient.ssh_USERAUTH_PK_OK(NS(b'') + NS(b''))
  548. self.assertEqual(self.authClient.transport.packets[-1],
  549. (userauth.MSG_USERAUTH_REQUEST, NS(b'foo') + NS(b'nancy')
  550. + NS(b'password') + b'\xff' + NS(b'foo') * 2))
  551. def test_no_password(self):
  552. """
  553. If getPassword returns None, tryAuth should return False.
  554. """
  555. self.authClient.getPassword = lambda: None
  556. self.assertFalse(self.authClient.tryAuth(b'password'))
  557. def test_keyboardInteractive(self):
  558. """
  559. Make sure that the client can authenticate with the keyboard
  560. interactive method.
  561. """
  562. self.authClient.ssh_USERAUTH_PK_OK_keyboard_interactive(
  563. NS(b'') + NS(b'') + NS(b'') + b'\x00\x00\x00\x01' +
  564. NS(b'Password: ') + b'\x00')
  565. self.assertEqual(
  566. self.authClient.transport.packets[-1],
  567. (userauth.MSG_USERAUTH_INFO_RESPONSE,
  568. b'\x00\x00\x00\x02' + NS(b'foo') + NS(b'foo')))
  569. def test_USERAUTH_PK_OK_unknown_method(self):
  570. """
  571. If C{SSHUserAuthClient} gets a MSG_USERAUTH_PK_OK packet when it's not
  572. expecting it, it should fail the current authentication and move on to
  573. the next type.
  574. """
  575. self.authClient.lastAuth = b'unknown'
  576. self.authClient.transport.packets = []
  577. self.authClient.ssh_USERAUTH_PK_OK(b'')
  578. self.assertEqual(self.authClient.transport.packets,
  579. [(userauth.MSG_USERAUTH_REQUEST, NS(b'foo') +
  580. NS(b'nancy') + NS(b'none'))])
  581. def test_USERAUTH_FAILURE_sorting(self):
  582. """
  583. ssh_USERAUTH_FAILURE should sort the methods by their position
  584. in SSHUserAuthClient.preferredOrder. Methods that are not in
  585. preferredOrder should be sorted at the end of that list.
  586. """
  587. def auth_firstmethod():
  588. self.authClient.transport.sendPacket(255, b'here is data')
  589. def auth_anothermethod():
  590. self.authClient.transport.sendPacket(254, b'other data')
  591. return True
  592. self.authClient.auth_firstmethod = auth_firstmethod
  593. self.authClient.auth_anothermethod = auth_anothermethod
  594. # although they shouldn't get called, method callbacks auth_* MUST
  595. # exist in order for the test to work properly.
  596. self.authClient.ssh_USERAUTH_FAILURE(NS(b'anothermethod,password') +
  597. b'\x00')
  598. # should send password packet
  599. self.assertEqual(self.authClient.transport.packets[-1],
  600. (userauth.MSG_USERAUTH_REQUEST, NS(b'foo') + NS(b'nancy')
  601. + NS(b'password') + b'\x00' + NS(b'foo')))
  602. self.authClient.ssh_USERAUTH_FAILURE(
  603. NS(b'firstmethod,anothermethod,password') + b'\xff')
  604. self.assertEqual(self.authClient.transport.packets[-2:],
  605. [(255, b'here is data'), (254, b'other data')])
  606. def test_disconnectIfNoMoreAuthentication(self):
  607. """
  608. If there are no more available user authentication messages,
  609. the SSHUserAuthClient should disconnect with code
  610. DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE.
  611. """
  612. self.authClient.ssh_USERAUTH_FAILURE(NS(b'password') + b'\x00')
  613. self.authClient.ssh_USERAUTH_FAILURE(NS(b'password') + b'\xff')
  614. self.assertEqual(self.authClient.transport.packets[-1],
  615. (transport.MSG_DISCONNECT, b'\x00\x00\x00\x0e' +
  616. NS(b'no more authentication methods available') +
  617. b'\x00\x00\x00\x00'))
  618. def test_ebAuth(self):
  619. """
  620. _ebAuth (the generic authentication error handler) should send
  621. a request for the 'none' authentication method.
  622. """
  623. self.authClient.transport.packets = []
  624. self.authClient._ebAuth(None)
  625. self.assertEqual(self.authClient.transport.packets,
  626. [(userauth.MSG_USERAUTH_REQUEST, NS(b'foo') + NS(b'nancy')
  627. + NS(b'none'))])
  628. def test_defaults(self):
  629. """
  630. getPublicKey() should return None. getPrivateKey() should return a
  631. failed Deferred. getPassword() should return a failed Deferred.
  632. getGenericAnswers() should return a failed Deferred.
  633. """
  634. authClient = userauth.SSHUserAuthClient(b'foo',
  635. FakeTransport.Service())
  636. self.assertIsNone(authClient.getPublicKey())
  637. def check(result):
  638. result.trap(NotImplementedError)
  639. d = authClient.getPassword()
  640. return d.addCallback(self.fail).addErrback(check2)
  641. def check2(result):
  642. result.trap(NotImplementedError)
  643. d = authClient.getGenericAnswers(None, None, None)
  644. return d.addCallback(self.fail).addErrback(check3)
  645. def check3(result):
  646. result.trap(NotImplementedError)
  647. d = authClient.getPrivateKey()
  648. return d.addCallback(self.fail).addErrback(check)
  649. class LoopbackTests(unittest.TestCase):
  650. if keys is None:
  651. skip = "cannot run without cryptography or PyASN1"
  652. class Factory:
  653. class Service:
  654. name = b'TestService'
  655. def serviceStarted(self):
  656. self.transport.loseConnection()
  657. def serviceStopped(self):
  658. pass
  659. def getService(self, avatar, name):
  660. return self.Service
  661. def test_loopback(self):
  662. """
  663. Test that the userauth server and client play nicely with each other.
  664. """
  665. server = userauth.SSHUserAuthServer()
  666. client = ClientUserAuth(b'foo', self.Factory.Service())
  667. # set up transports
  668. server.transport = transport.SSHTransportBase()
  669. server.transport.service = server
  670. server.transport.isEncrypted = lambda x: True
  671. client.transport = transport.SSHTransportBase()
  672. client.transport.service = client
  673. server.transport.sessionID = client.transport.sessionID = b''
  674. # don't send key exchange packet
  675. server.transport.sendKexInit = client.transport.sendKexInit = \
  676. lambda: None
  677. # set up server authentication
  678. server.transport.factory = self.Factory()
  679. server.passwordDelay = 0 # remove bad password delay
  680. realm = Realm()
  681. portal = Portal(realm)
  682. checker = SSHProtocolChecker()
  683. checker.registerChecker(PasswordChecker())
  684. checker.registerChecker(PrivateKeyChecker())
  685. checker.areDone = lambda aId: (
  686. len(checker.successfulCredentials[aId]) == 2)
  687. portal.registerChecker(checker)
  688. server.transport.factory.portal = portal
  689. d = loopback.loopbackAsync(server.transport, client.transport)
  690. server.transport.transport.logPrefix = lambda: '_ServerLoopback'
  691. client.transport.transport.logPrefix = lambda: '_ClientLoopback'
  692. server.serviceStarted()
  693. client.serviceStarted()
  694. def check(ignored):
  695. self.assertEqual(server.transport.service.name, b'TestService')
  696. return d.addCallback(check)
  697. class ModuleInitializationTests(unittest.TestCase):
  698. if keys is None:
  699. skip = "cannot run without cryptography or PyASN1"
  700. def test_messages(self):
  701. # Several message types have value 60, check that MSG_USERAUTH_PK_OK
  702. # is always the one which is mapped.
  703. self.assertEqual(userauth.SSHUserAuthServer.protocolMessages[60],
  704. 'MSG_USERAUTH_PK_OK')
  705. self.assertEqual(userauth.SSHUserAuthClient.protocolMessages[60],
  706. 'MSG_USERAUTH_PK_OK')