Debian Codegraph @

test/unit/transport/test_ssh.py

raw
1 # -*- coding: utf-8 -*-
2 import unittest
3 from unittest.mock import MagicMock, patch, call
4
5 from ncclient.transport.ssh import SSHSession
6 from ncclient.transport import AuthenticationError, SessionCloseError, NetconfBase
7 import paramiko
8 from ncclient.devices.junos import JunosDeviceHandler
9
10 try:
11 import selectors
12 except ImportError:
13 import selectors2 as selectors
14
15
16 reply_data = """<rpc-reply xmlns:junos="http://xml.juniper.net/junos/12.1X46/junos" attrib1 = "test">
17 <software-information>
18 <host-name>R1</host-name>
19 <product-model>firefly-perimeter</product-model>
20 <product-name>firefly-perimeter</product-name>
21 <package-information>
22 <name>junos</name>
23 <comment>JUNOS Software Release [12.1X46-D10.2]</comment>
24 </package-information>
25 </software-information>
26 <cli>
27 <banner></banner>
28 </cli>
29 </rpc-reply>"""
30
31 reply_ok = """<rpc-reply>
32 <ok/>
33 <rpc-reply/>"""
34
35 # A buffer of data with two complete messages and an incomplete message
36 rpc_reply = reply_data + "\n]]>]]>\n" + reply_ok + "\n]]>]]>\n" + reply_ok
37
38 reply_ok_chunk = "\n#%d\n%s\n##\n" % (len(reply_ok), reply_ok)
39
40 # einarnn: this test message had to be reduced in size as the improved
41 # 1.1 parsing finds a whole fragment in it, so needed to have less
42 # data in it than the terminating '>'
43 reply_ok_partial_chunk = "\n#%d\n%s" % (len(reply_ok), reply_ok[:-1])
44
45 # A buffer of data with two complete messages and an incomplete message
46 rpc_reply11 = "\n#%d\n%s\n#%d\n%s\n##\n%s%s" % (
47 30, reply_data[:30], len(reply_data[30:]), reply_data[30:],
48 reply_ok_chunk, reply_ok_partial_chunk)
49
50
51 rpc_reply_part_1 = """<rpc-reply xmlns:junos="http://xml.juniper.net/junos/12.1X46/junos" attrib1 = "test">
52 <software-information>
53 <host-name>R1</host-name>
54 <product-model>firefly-perimeter</product-model>
55 <product-name>firefly-perimeter</product-name>
56 <package-information>
57 <name>junos</name>
58 <comment>JUNOS Software Release [12.1X46-D10.2]</comment>
59 </package-information>
60 </software-information>
61 <cli>
62 <banner></banner>
63 </cli>
64 </rpc-reply>
65 ]]>]]"""
66
67 rpc_reply_part_2 = """>
68 <rpc-reply>
69 <ok/>
70 <rpc-reply/>"""
71
72
73 class TestSSH(unittest.TestCase):
74
75 def _test_parsemethod(self, mock_dispatch, parsemethod, reply, ok_chunk,
76 expected_messages):
77 device_handler = JunosDeviceHandler({'name': 'junos'})
78 obj = SSHSession(device_handler)
79 obj._buffer.write(bytes(reply, "utf-8"))
80 remainder = bytes(ok_chunk, "utf-8")
81 parsemethod(obj)
82
83 for i in range(0, len(expected_messages)):
84 call = mock_dispatch.call_args_list[i][0][0]
85 self.assertEqual(call, expected_messages[i])
86
87 self.assertEqual(obj._buffer.getvalue(), remainder)
88
89 @patch('ncclient.transport.ssh.Session._dispatch_message')
90 def test_parse(self, mock_dispatch):
91 self._test_parsemethod(mock_dispatch, SSHSession._parse, rpc_reply,
92 "\n" + reply_ok, [reply_data])
93
94 @patch('ncclient.transport.ssh.Session._dispatch_message')
95 def test_parse11(self, mock_dispatch):
96 device_handler = JunosDeviceHandler({'name': 'junos'})
97 obj = SSHSession(device_handler)
98 obj._buffer.write(bytes(rpc_reply11, "utf-8"))
99 remainder = bytes(reply_ok_partial_chunk, "utf-8")
100 obj.parser._parse11()
101
102 expected_messages = [reply_data, reply_ok]
103 for i in range(0, len(expected_messages)):
104 call = mock_dispatch.call_args_list[i][0][0]
105 self.assertEqual(call, expected_messages[i])
106
107 self.assertEqual(obj._buffer.getvalue(), remainder)
108
109 @patch('ncclient.transport.ssh.Session._dispatch_message')
110 def test_parse_incomplete_delimiter(self, mock_dispatch):
111 device_handler = JunosDeviceHandler({'name': 'junos'})
112 obj = SSHSession(device_handler)
113 b = bytes(rpc_reply_part_1, "utf-8")
114 obj._buffer.write(b)
115 obj._parse()
116 self.assertFalse(mock_dispatch.called)
117 b = bytes(rpc_reply_part_2, "utf-8")
118 obj._buffer.write(b)
119 obj._parse()
120 self.assertTrue(mock_dispatch.called)
121
122 @patch('paramiko.transport.Transport.auth_publickey')
123 @patch('paramiko.agent.AgentSSH.get_keys')
124 def test_auth_agent(self, mock_get_key, mock_auth_public_key):
125 key = paramiko.PKey(msg="hello")
126 mock_get_key.return_value = [key]
127 device_handler = JunosDeviceHandler({'name': 'junos'})
128 obj = SSHSession(device_handler)
129 obj._transport = paramiko.Transport(MagicMock())
130 obj._auth('user', 'password', [], True, True)
131 self.assertEqual(
132 (mock_auth_public_key.call_args_list[0][0][1]).__repr__(),
133 key.__repr__())
134
135 @patch('paramiko.transport.Transport.auth_publickey')
136 @patch('paramiko.agent.AgentSSH.get_keys')
137 def test_auth_agent_exception(self, mock_get_key, mock_auth_public_key):
138 key = paramiko.PKey()
139 mock_get_key.return_value = [key]
140 mock_auth_public_key.side_effect = paramiko.ssh_exception.AuthenticationException
141 device_handler = JunosDeviceHandler({'name': 'junos'})
142 obj = SSHSession(device_handler)
143 obj._transport = paramiko.Transport(MagicMock())
144 self.assertRaises(AuthenticationError,
145 obj._auth,'user', None, [], True, False)
146
147 @patch('paramiko.transport.Transport.auth_publickey')
148 @patch('paramiko.PKey.from_path')
149 def test_auth_keyfiles(self, mock_get_key, mock_auth_public_key):
150 key = paramiko.PKey()
151 mock_get_key.return_value = key
152 device_handler = JunosDeviceHandler({'name': 'junos'})
153 obj = SSHSession(device_handler)
154 obj._transport = paramiko.Transport(MagicMock())
155 obj._auth('user', 'password', ["key_file_name"], False, True)
156 self.assertEqual(
157 (mock_auth_public_key.call_args_list[0][0][1]).__repr__(),
158 key.__repr__())
159
160 @patch('paramiko.transport.Transport.auth_publickey')
161 @patch('paramiko.PKey.from_path')
162 def test_auth_keyfiles_exception(self, mock_get_key, mock_auth_public_key):
163 key = paramiko.PKey()
164 mock_get_key.side_effect = paramiko.ssh_exception.PasswordRequiredException
165 device_handler = JunosDeviceHandler({'name': 'junos'})
166 obj = SSHSession(device_handler)
167 obj._transport = paramiko.Transport(MagicMock())
168 self.assertRaises(AuthenticationError,
169 obj._auth,'user', None, ["key_file_name"], False, True)
170
171 @patch('os.path.isfile')
172 @patch('paramiko.transport.Transport.auth_publickey')
173 @patch('paramiko.PKey.from_path')
174 def test_auth_default_keyfiles(self, mock_get_key, mock_auth_public_key,
175 mock_is_file):
176 key = paramiko.PKey()
177 mock_get_key.return_value = key
178 mock_is_file.return_value = True
179 device_handler = JunosDeviceHandler({'name': 'junos'})
180 obj = SSHSession(device_handler)
181 obj._transport = paramiko.Transport(MagicMock())
182 obj._auth('user', 'password', [], False, True)
183 self.assertEqual(
184 (mock_auth_public_key.call_args_list[0][0][1]).__repr__(),
185 key.__repr__())
186
187 @patch('os.path.isfile')
188 @patch('paramiko.transport.Transport.auth_publickey')
189 @patch('paramiko.PKey.from_path')
190 def test_auth_default_keyfiles_exception(self, mock_get_key,
191 mock_auth_public_key, mock_is_file):
192 key = paramiko.PKey()
193 mock_is_file.return_value = True
194 mock_get_key.side_effect = paramiko.ssh_exception.PasswordRequiredException
195 device_handler = JunosDeviceHandler({'name': 'junos'})
196 obj = SSHSession(device_handler)
197 obj._transport = paramiko.Transport(MagicMock())
198 self.assertRaises(AuthenticationError,
199 obj._auth,'user', None, [], False, True)
200
201 @patch('paramiko.transport.Transport.auth_password')
202 def test_auth_password(self, mock_auth_password):
203 device_handler = JunosDeviceHandler({'name': 'junos'})
204 obj = SSHSession(device_handler)
205 obj._transport = paramiko.Transport(MagicMock())
206 obj._auth('user', 'password', [], False, True)
207 self.assertEqual(
208 mock_auth_password.call_args_list[0][0],
209 ('user',
210 'password'))
211
212 @patch('paramiko.transport.Transport.auth_password')
213 def test_auth_exception(self, mock_auth_password):
214 mock_auth_password.side_effect = Exception
215 device_handler = JunosDeviceHandler({'name': 'junos'})
216 obj = SSHSession(device_handler)
217 obj._transport = paramiko.Transport(MagicMock())
218 self.assertRaises(AuthenticationError,
219 obj._auth, 'user', 'password', [], False, True)
220
221 def test_auth_no_methods_exception(self):
222 device_handler = JunosDeviceHandler({'name': 'junos'})
223 obj = SSHSession(device_handler)
224 obj._transport = paramiko.Transport(MagicMock())
225 self.assertRaises(AuthenticationError,
226 obj._auth,'user', None, [], False, False)
227
228 @patch('paramiko.transport.Transport.close')
229 def test_close(self, mock_close):
230 device_handler = JunosDeviceHandler({'name': 'junos'})
231 obj = SSHSession(device_handler)
232 obj._transport = paramiko.Transport(MagicMock())
233 obj._transport.active = True
234 obj._connected = True
235 obj.close()
236 mock_close.assert_called_once_with()
237 self.assertFalse(obj._connected)
238
239 @patch('paramiko.hostkeys.HostKeys.load')
240 def test_load_host_key(self, mock_load):
241 device_handler = JunosDeviceHandler({'name': 'junos'})
242 obj = SSHSession(device_handler)
243 obj.load_known_hosts("file_name")
244 mock_load.assert_called_once_with("file_name")
245
246 @patch('os.path.expanduser')
247 @patch('paramiko.hostkeys.HostKeys.load')
248 def test_load_host_key_2(self, mock_load, mock_os):
249 mock_os.return_value = "file_name"
250 device_handler = JunosDeviceHandler({'name': 'junos'})
251 obj = SSHSession(device_handler)
252 obj.load_known_hosts()
253 mock_load.assert_called_once_with("file_name")
254
255 @patch('os.path.expanduser')
256 @patch('paramiko.hostkeys.HostKeys.load')
257 def test_load_host_key_IOError(self, mock_load, mock_os):
258 mock_os.return_value = "file_name"
259 mock_load.side_effect = IOError
260 device_handler = JunosDeviceHandler({'name': 'junos'})
261 obj = SSHSession(device_handler)
262 obj.load_known_hosts()
263 mock_load.assert_called_with("file_name")
264
265 @patch('ncclient.transport.ssh.hexlify')
266 @patch('os.path.expanduser')
267 @patch('paramiko.HostKeys')
268 @patch('paramiko.Transport')
269 @patch('ncclient.transport.ssh.SSHSession._post_connect')
270 @patch('ncclient.transport.ssh.SSHSession._auth')
271 def test_ssh_known_hosts(self, mock_auth, mock_pc,
272 mock_transport, mock_hk,
273 mock_os, mock_hex):
274 mock_os.return_value = "file_name"
275 hk_inst = MagicMock(check=MagicMock(return_value=True))
276 mock_hk.return_value = hk_inst
277 device_handler = JunosDeviceHandler({'name': 'junos'})
278 obj = SSHSession(device_handler)
279 obj.connect(host='h', sock=MagicMock())
280 hk_inst.load.assert_called_once_with('file_name')
281 mock_os.assert_called_once_with('~/.ssh/known_hosts')
282
283 @patch('ncclient.transport.ssh.hexlify')
284 @patch('ncclient.transport.ssh.open')
285 @patch('os.path.expanduser')
286 @patch('paramiko.HostKeys')
287 @patch('paramiko.Transport')
288 @patch('paramiko.SSHConfig')
289 @patch('ncclient.transport.ssh.SSHSession._post_connect')
290 @patch('ncclient.transport.ssh.SSHSession._auth')
291 def test_ssh_known_hosts_2(self, mock_auth, mock_pc,
292 mock_sshc, mock_transport, mock_hk,
293 mock_os, mock_open, mock_hex):
294 mock_os.return_value = "file_name"
295 hk_inst = MagicMock(check=MagicMock(return_value=True))
296 mock_hk.return_value = hk_inst
297 config = {'userknownhostsfile': 'known_hosts_file'}
298 mock_sshc.return_value = MagicMock(lookup=lambda _h: config)
299 device_handler = JunosDeviceHandler({'name': 'junos'})
300 obj = SSHSession(device_handler)
301 obj.connect(host='h', sock=MagicMock(), ssh_config=True)
302 hk_inst.load.assert_called_once_with('file_name')
303 mock_os.mock_calls == [call('~/.ssh/config'), call('known_hosts_file')]
304
305 @patch('ncclient.transport.ssh.SSHSession.close')
306 @patch('paramiko.channel.Channel.recv')
307 @patch('selectors.DefaultSelector.select')
308 @patch('ncclient.transport.ssh.Session._dispatch_error')
309 def test_run_receive_py3(self, mock_error, mock_selector, mock_recv, mock_close):
310 mock_selector.return_value = True
311 mock_recv.return_value = 0
312 device_handler = JunosDeviceHandler({'name': 'junos'})
313 obj = SSHSession(device_handler)
314 obj._channel = paramiko.Channel("c100")
315 obj.run()
316 self.assertTrue(
317 isinstance(
318 mock_error.call_args_list[0][0][0],
319 SessionCloseError))
320
321 def test_run_send_py3_10(self):
322 self._test_run_send_py3(NetconfBase.BASE_10,
323 lambda msg: msg.encode() + b"]]>]]>")
324
325 def test_run_send_py3_11(self):
326 def chunker(msg):
327 encmsg = msg.encode()
328 chunks = b"\n#%i\n%b\n##\n" % (len(encmsg), encmsg)
329 return chunks
330 self._test_run_send_py3(NetconfBase.BASE_11, chunker)
331
332 @patch('ncclient.transport.ssh.SSHSession.close')
333 @patch('paramiko.channel.Channel.send_ready')
334 @patch('paramiko.channel.Channel.send')
335 @patch('selectors.DefaultSelector.select')
336 @patch('ncclient.transport.ssh.Session._dispatch_error')
337 def _test_run_send_py3(self, base, chunker, mock_error, mock_selector,
338 mock_send, mock_ready, mock_close):
339 mock_selector.return_value = False
340 mock_ready.return_value = True
341 mock_send.return_value = -1
342 device_handler = JunosDeviceHandler({'name': 'junos'})
343 obj = SSHSession(device_handler)
344 obj._channel = paramiko.Channel("c100")
345 msg = "naïve garçon"
346 obj._q.put(msg)
347 obj._base = base
348 obj.run()
349 self.assertEqual(mock_send.call_args_list[0][0][0], chunker(msg))
350 self.assertTrue(
351 isinstance(
352 mock_error.call_args_list[0][0][0],
353 SessionCloseError))
354
355 @unittest.skip("test currently non-functional")
356 @patch('ncclient.transport.ssh.SSHSession.close')
357 @patch('paramiko.channel.Channel.send_ready')
358 @patch('paramiko.channel.Channel.send')
359 @patch('selectors2.DefaultSelector')
360 @patch('ncclient.transport.ssh.Session._dispatch_error')
361 def test_run_send_py2(self, mock_error, mock_selector, mock_send, mock_ready, mock_close):
362 mock_selector.select.return_value = False
363 mock_ready.return_value = True
364 mock_send.return_value = -1
365 device_handler = JunosDeviceHandler({'name': 'junos'})
366 obj = SSHSession(device_handler)
367 obj._channel = paramiko.Channel("c100")
368 obj._q.put("rpc")
369 obj.run()
370 self.assertEqual(mock_send.call_args_list[0][0][0], "rpc]]>]]>")
371 self.assertTrue(
372 isinstance(
373 mock_error.call_args_list[0][0][0],
374 SessionCloseError))