test_agent.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for L{twisted.conch.ssh.agent}.
  5. """
  6. from __future__ import absolute_import, division
  7. import struct
  8. from twisted.trial import unittest
  9. from twisted.test import iosim
  10. try:
  11. import cryptography
  12. except ImportError:
  13. cryptography = None
  14. try:
  15. import pyasn1
  16. except ImportError:
  17. pyasn1 = None
  18. if cryptography and pyasn1:
  19. from twisted.conch.ssh import keys, agent
  20. else:
  21. keys = agent = None
  22. from twisted.conch.test import keydata
  23. from twisted.conch.error import ConchError, MissingKeyStoreError
  24. class StubFactory(object):
  25. """
  26. Mock factory that provides the keys attribute required by the
  27. SSHAgentServerProtocol
  28. """
  29. def __init__(self):
  30. self.keys = {}
  31. class AgentTestBase(unittest.TestCase):
  32. """
  33. Tests for SSHAgentServer/Client.
  34. """
  35. if iosim is None:
  36. skip = "iosim requires SSL, but SSL is not available"
  37. elif agent is None or keys is None:
  38. skip = "Cannot run without cryptography or PyASN1"
  39. def setUp(self):
  40. # wire up our client <-> server
  41. self.client, self.server, self.pump = iosim.connectedServerAndClient(
  42. agent.SSHAgentServer, agent.SSHAgentClient)
  43. # the server's end of the protocol is stateful and we store it on the
  44. # factory, for which we only need a mock
  45. self.server.factory = StubFactory()
  46. # pub/priv keys of each kind
  47. self.rsaPrivate = keys.Key.fromString(keydata.privateRSA_openssh)
  48. self.dsaPrivate = keys.Key.fromString(keydata.privateDSA_openssh)
  49. self.rsaPublic = keys.Key.fromString(keydata.publicRSA_openssh)
  50. self.dsaPublic = keys.Key.fromString(keydata.publicDSA_openssh)
  51. class ServerProtocolContractWithFactoryTests(AgentTestBase):
  52. """
  53. The server protocol is stateful and so uses its factory to track state
  54. across requests. This test asserts that the protocol raises if its factory
  55. doesn't provide the necessary storage for that state.
  56. """
  57. def test_factorySuppliesKeyStorageForServerProtocol(self):
  58. # need a message to send into the server
  59. msg = struct.pack('!LB',1, agent.AGENTC_REQUEST_IDENTITIES)
  60. del self.server.factory.__dict__['keys']
  61. self.assertRaises(MissingKeyStoreError,
  62. self.server.dataReceived, msg)
  63. class UnimplementedVersionOneServerTests(AgentTestBase):
  64. """
  65. Tests for methods with no-op implementations on the server. We need these
  66. for clients, such as openssh, that try v1 methods before going to v2.
  67. Because the client doesn't expose these operations with nice method names,
  68. we invoke sendRequest directly with an op code.
  69. """
  70. def test_agentc_REQUEST_RSA_IDENTITIES(self):
  71. """
  72. assert that we get the correct op code for an RSA identities request
  73. """
  74. d = self.client.sendRequest(agent.AGENTC_REQUEST_RSA_IDENTITIES, b'')
  75. self.pump.flush()
  76. def _cb(packet):
  77. self.assertEqual(
  78. agent.AGENT_RSA_IDENTITIES_ANSWER, ord(packet[0:1]))
  79. return d.addCallback(_cb)
  80. def test_agentc_REMOVE_RSA_IDENTITY(self):
  81. """
  82. assert that we get the correct op code for an RSA remove identity request
  83. """
  84. d = self.client.sendRequest(agent.AGENTC_REMOVE_RSA_IDENTITY, b'')
  85. self.pump.flush()
  86. return d.addCallback(self.assertEqual, b'')
  87. def test_agentc_REMOVE_ALL_RSA_IDENTITIES(self):
  88. """
  89. assert that we get the correct op code for an RSA remove all identities
  90. request.
  91. """
  92. d = self.client.sendRequest(agent.AGENTC_REMOVE_ALL_RSA_IDENTITIES, b'')
  93. self.pump.flush()
  94. return d.addCallback(self.assertEqual, b'')
  95. if agent is not None:
  96. class CorruptServer(agent.SSHAgentServer):
  97. """
  98. A misbehaving server that returns bogus response op codes so that we can
  99. verify that our callbacks that deal with these op codes handle such
  100. miscreants.
  101. """
  102. def agentc_REQUEST_IDENTITIES(self, data):
  103. self.sendResponse(254, b'')
  104. def agentc_SIGN_REQUEST(self, data):
  105. self.sendResponse(254, b'')
  106. class ClientWithBrokenServerTests(AgentTestBase):
  107. """
  108. verify error handling code in the client using a misbehaving server
  109. """
  110. def setUp(self):
  111. AgentTestBase.setUp(self)
  112. self.client, self.server, self.pump = iosim.connectedServerAndClient(
  113. CorruptServer, agent.SSHAgentClient)
  114. # the server's end of the protocol is stateful and we store it on the
  115. # factory, for which we only need a mock
  116. self.server.factory = StubFactory()
  117. def test_signDataCallbackErrorHandling(self):
  118. """
  119. Assert that L{SSHAgentClient.signData} raises a ConchError
  120. if we get a response from the server whose opcode doesn't match
  121. the protocol for data signing requests.
  122. """
  123. d = self.client.signData(self.rsaPublic.blob(), b"John Hancock")
  124. self.pump.flush()
  125. return self.assertFailure(d, ConchError)
  126. def test_requestIdentitiesCallbackErrorHandling(self):
  127. """
  128. Assert that L{SSHAgentClient.requestIdentities} raises a ConchError
  129. if we get a response from the server whose opcode doesn't match
  130. the protocol for identity requests.
  131. """
  132. d = self.client.requestIdentities()
  133. self.pump.flush()
  134. return self.assertFailure(d, ConchError)
  135. class AgentKeyAdditionTests(AgentTestBase):
  136. """
  137. Test adding different flavors of keys to an agent.
  138. """
  139. def test_addRSAIdentityNoComment(self):
  140. """
  141. L{SSHAgentClient.addIdentity} adds the private key it is called
  142. with to the SSH agent server to which it is connected, associating
  143. it with the comment it is called with.
  144. This test asserts that omitting the comment produces an
  145. empty string for the comment on the server.
  146. """
  147. d = self.client.addIdentity(self.rsaPrivate.privateBlob())
  148. self.pump.flush()
  149. def _check(ignored):
  150. serverKey = self.server.factory.keys[self.rsaPrivate.blob()]
  151. self.assertEqual(self.rsaPrivate, serverKey[0])
  152. self.assertEqual(b'', serverKey[1])
  153. return d.addCallback(_check)
  154. def test_addDSAIdentityNoComment(self):
  155. """
  156. L{SSHAgentClient.addIdentity} adds the private key it is called
  157. with to the SSH agent server to which it is connected, associating
  158. it with the comment it is called with.
  159. This test asserts that omitting the comment produces an
  160. empty string for the comment on the server.
  161. """
  162. d = self.client.addIdentity(self.dsaPrivate.privateBlob())
  163. self.pump.flush()
  164. def _check(ignored):
  165. serverKey = self.server.factory.keys[self.dsaPrivate.blob()]
  166. self.assertEqual(self.dsaPrivate, serverKey[0])
  167. self.assertEqual(b'', serverKey[1])
  168. return d.addCallback(_check)
  169. def test_addRSAIdentityWithComment(self):
  170. """
  171. L{SSHAgentClient.addIdentity} adds the private key it is called
  172. with to the SSH agent server to which it is connected, associating
  173. it with the comment it is called with.
  174. This test asserts that the server receives/stores the comment
  175. as sent by the client.
  176. """
  177. d = self.client.addIdentity(
  178. self.rsaPrivate.privateBlob(), comment=b'My special key')
  179. self.pump.flush()
  180. def _check(ignored):
  181. serverKey = self.server.factory.keys[self.rsaPrivate.blob()]
  182. self.assertEqual(self.rsaPrivate, serverKey[0])
  183. self.assertEqual(b'My special key', serverKey[1])
  184. return d.addCallback(_check)
  185. def test_addDSAIdentityWithComment(self):
  186. """
  187. L{SSHAgentClient.addIdentity} adds the private key it is called
  188. with to the SSH agent server to which it is connected, associating
  189. it with the comment it is called with.
  190. This test asserts that the server receives/stores the comment
  191. as sent by the client.
  192. """
  193. d = self.client.addIdentity(
  194. self.dsaPrivate.privateBlob(), comment=b'My special key')
  195. self.pump.flush()
  196. def _check(ignored):
  197. serverKey = self.server.factory.keys[self.dsaPrivate.blob()]
  198. self.assertEqual(self.dsaPrivate, serverKey[0])
  199. self.assertEqual(b'My special key', serverKey[1])
  200. return d.addCallback(_check)
  201. class AgentClientFailureTests(AgentTestBase):
  202. def test_agentFailure(self):
  203. """
  204. verify that the client raises ConchError on AGENT_FAILURE
  205. """
  206. d = self.client.sendRequest(254, b'')
  207. self.pump.flush()
  208. return self.assertFailure(d, ConchError)
  209. class AgentIdentityRequestsTests(AgentTestBase):
  210. """
  211. Test operations against a server with identities already loaded.
  212. """
  213. def setUp(self):
  214. AgentTestBase.setUp(self)
  215. self.server.factory.keys[self.dsaPrivate.blob()] = (
  216. self.dsaPrivate, b'a comment')
  217. self.server.factory.keys[self.rsaPrivate.blob()] = (
  218. self.rsaPrivate, b'another comment')
  219. def test_signDataRSA(self):
  220. """
  221. Sign data with an RSA private key and then verify it with the public
  222. key.
  223. """
  224. d = self.client.signData(self.rsaPublic.blob(), b"John Hancock")
  225. self.pump.flush()
  226. signature = self.successResultOf(d)
  227. expected = self.rsaPrivate.sign(b"John Hancock")
  228. self.assertEqual(expected, signature)
  229. self.assertTrue(self.rsaPublic.verify(signature, b"John Hancock"))
  230. def test_signDataDSA(self):
  231. """
  232. Sign data with a DSA private key and then verify it with the public
  233. key.
  234. """
  235. d = self.client.signData(self.dsaPublic.blob(), b"John Hancock")
  236. self.pump.flush()
  237. def _check(sig):
  238. # Cannot do this b/c DSA uses random numbers when signing
  239. # expected = self.dsaPrivate.sign("John Hancock")
  240. # self.assertEqual(expected, sig)
  241. self.assertTrue(self.dsaPublic.verify(sig, b"John Hancock"))
  242. return d.addCallback(_check)
  243. def test_signDataRSAErrbackOnUnknownBlob(self):
  244. """
  245. Assert that we get an errback if we try to sign data using a key that
  246. wasn't added.
  247. """
  248. del self.server.factory.keys[self.rsaPublic.blob()]
  249. d = self.client.signData(self.rsaPublic.blob(), b"John Hancock")
  250. self.pump.flush()
  251. return self.assertFailure(d, ConchError)
  252. def test_requestIdentities(self):
  253. """
  254. Assert that we get all of the keys/comments that we add when we issue a
  255. request for all identities.
  256. """
  257. d = self.client.requestIdentities()
  258. self.pump.flush()
  259. def _check(keyt):
  260. expected = {}
  261. expected[self.dsaPublic.blob()] = b'a comment'
  262. expected[self.rsaPublic.blob()] = b'another comment'
  263. received = {}
  264. for k in keyt:
  265. received[keys.Key.fromString(k[0], type='blob').blob()] = k[1]
  266. self.assertEqual(expected, received)
  267. return d.addCallback(_check)
  268. class AgentKeyRemovalTests(AgentTestBase):
  269. """
  270. Test support for removing keys in a remote server.
  271. """
  272. def setUp(self):
  273. AgentTestBase.setUp(self)
  274. self.server.factory.keys[self.dsaPrivate.blob()] = (
  275. self.dsaPrivate, b'a comment')
  276. self.server.factory.keys[self.rsaPrivate.blob()] = (
  277. self.rsaPrivate, b'another comment')
  278. def test_removeRSAIdentity(self):
  279. """
  280. Assert that we can remove an RSA identity.
  281. """
  282. # only need public key for this
  283. d = self.client.removeIdentity(self.rsaPrivate.blob())
  284. self.pump.flush()
  285. def _check(ignored):
  286. self.assertEqual(1, len(self.server.factory.keys))
  287. self.assertIn(self.dsaPrivate.blob(), self.server.factory.keys)
  288. self.assertNotIn(self.rsaPrivate.blob(), self.server.factory.keys)
  289. return d.addCallback(_check)
  290. def test_removeDSAIdentity(self):
  291. """
  292. Assert that we can remove a DSA identity.
  293. """
  294. # only need public key for this
  295. d = self.client.removeIdentity(self.dsaPrivate.blob())
  296. self.pump.flush()
  297. def _check(ignored):
  298. self.assertEqual(1, len(self.server.factory.keys))
  299. self.assertIn(self.rsaPrivate.blob(), self.server.factory.keys)
  300. return d.addCallback(_check)
  301. def test_removeAllIdentities(self):
  302. """
  303. Assert that we can remove all identities.
  304. """
  305. d = self.client.removeAllIdentities()
  306. self.pump.flush()
  307. def _check(ignored):
  308. self.assertEqual(0, len(self.server.factory.keys))
  309. return d.addCallback(_check)