Debian Codegraph @

tests/_util.py

raw
1 import builtins
2 import os
3 import socket
4 import struct
5 import threading
6 import time
7 from contextlib import contextmanager
8 from os.path import dirname, join, realpath
9 from pathlib import Path
10
11 import pytest
12
13 from paramiko import (
14 AUTH_FAILED,
15 AUTH_PARTIALLY_SUCCESSFUL,
16 AUTH_SUCCESSFUL,
17 OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED,
18 OPEN_SUCCEEDED,
19 Ed25519Key,
20 InteractiveQuery,
21 RSAKey,
22 ServerInterface,
23 Transport,
24 )
25
26 from ._loop import LoopSocket
27
28 tests_dir = dirname(realpath(__file__))
29
30
31 def _support(filename):
32 base = Path(tests_dir)
33 top = base / filename
34 deeper = base / "_support" / filename
35 return str(deeper if deeper.exists() else top)
36
37
38 def _config(name):
39 return join(tests_dir, "configs", name)
40
41
42 def needs_builtin(name):
43 """
44 Skip decorated test if builtin name does not exist.
45 """
46 reason = "Test requires a builtin '{}'".format(name)
47 return pytest.mark.skipif(not hasattr(builtins, name), reason=reason)
48
49
50 slow = pytest.mark.slow
51
52
53 def update_env(testcase, mapping, env=os.environ):
54 """Modify os.environ during a test case and restore during cleanup."""
55 saved_env = env.copy()
56
57 def replace(target, source):
58 target.update(source)
59 for k in list(target):
60 if k not in source:
61 target.pop(k, None)
62
63 testcase.addCleanup(replace, env, saved_env)
64 env.update(mapping)
65 return testcase
66
67
68 def is_low_entropy():
69 """
70 Attempts to detect whether running interpreter is low-entropy.
71
72 "low-entropy" is defined as being in 32-bit mode and with the hash seed set
73 to zero.
74 """
75 is_32bit = struct.calcsize("P") == 32 / 8
76 # I don't see a way to tell internally if the hash seed was set this
77 # way, but env should be plenty sufficient, this is only for testing.
78 return is_32bit and os.environ.get("PYTHONHASHSEED", None) == "0"
79
80
81 # TODO: doublecheck where _disable_xxx helpers were in use; disabling sha1 no
82 # longer makes any sense, and presumably neither does en/dis abling sha2 but
83 # that's the question innit
84
85 unicodey = "\u2022"
86
87
88 class TestServer(ServerInterface):
89 paranoid_did_password = False
90 paranoid_did_public_key = False
91 paranoid_key = Ed25519Key.from_private_key_file(_support("ed25519.key"))
92
93 def __init__(self, allowed_keys=None):
94 self.allowed_keys = allowed_keys if allowed_keys is not None else []
95
96 def check_channel_request(self, kind, chanid):
97 if kind == "bogus":
98 return OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
99 return OPEN_SUCCEEDED
100
101 def check_channel_exec_request(self, channel, command):
102 if command != b"yes":
103 return False
104 return True
105
106 def check_channel_shell_request(self, channel):
107 return True
108
109 def check_global_request(self, kind, msg):
110 self._global_request = kind
111 # NOTE: for w/e reason, older impl of this returned False always, even
112 # tho that's only supposed to occur if the request cannot be served.
113 # For now, leaving that the default unless test supplies specific
114 # 'acceptable' request kind
115 return kind == "acceptable"
116
117 def check_channel_x11_request(
118 self,
119 channel,
120 single_connection,
121 auth_protocol,
122 auth_cookie,
123 screen_number,
124 ):
125 self._x11_single_connection = single_connection
126 self._x11_auth_protocol = auth_protocol
127 self._x11_auth_cookie = auth_cookie
128 self._x11_screen_number = screen_number
129 return True
130
131 def check_port_forward_request(self, addr, port):
132 self._listen = socket.socket()
133 self._listen.bind(("127.0.0.1", 0))
134 self._listen.listen(1)
135 return self._listen.getsockname()[1]
136
137 def cancel_port_forward_request(self, addr, port):
138 self._listen.close()
139 self._listen = None
140
141 def check_channel_direct_tcpip_request(self, chanid, origin, destination):
142 self._tcpip_dest = destination
143 return OPEN_SUCCEEDED
144
145 def get_allowed_auths(self, username):
146 if username == "slowdive":
147 return "publickey,password"
148 if username == "paranoid":
149 if (
150 not self.paranoid_did_password
151 and not self.paranoid_did_public_key
152 ):
153 return "publickey,password"
154 elif self.paranoid_did_password:
155 return "publickey"
156 else:
157 return "password"
158 if username == "commie":
159 return "keyboard-interactive"
160 if username == "utf8":
161 return "password"
162 if username == "non-utf8":
163 return "password"
164 return "publickey"
165
166 def check_auth_password(self, username, password):
167 if (username == "slowdive") and (password == "pygmalion"):
168 return AUTH_SUCCESSFUL
169 if (username == "paranoid") and (password == "paranoid"):
170 # 2-part auth (even openssh doesn't support this)
171 self.paranoid_did_password = True
172 if self.paranoid_did_public_key:
173 return AUTH_SUCCESSFUL
174 return AUTH_PARTIALLY_SUCCESSFUL
175 if (username == "utf8") and (password == unicodey):
176 return AUTH_SUCCESSFUL
177 if (username == "non-utf8") and (password == "\xff"):
178 return AUTH_SUCCESSFUL
179 if username == "bad-server":
180 raise Exception("Ack!")
181 if username == "unresponsive-server":
182 time.sleep(5)
183 return AUTH_SUCCESSFUL
184 return AUTH_FAILED
185
186 def check_auth_publickey(self, username, key):
187 if (username == "paranoid") and (key == self.paranoid_key):
188 # 2-part auth
189 self.paranoid_did_public_key = True
190 if self.paranoid_did_password:
191 return AUTH_SUCCESSFUL
192 return AUTH_PARTIALLY_SUCCESSFUL
193 # TODO: make sure all tests incidentally using this to pass, _without
194 # sending a username oops_, get updated somehow - probably via server()
195 # default always injecting a username
196 elif key in self.allowed_keys:
197 return AUTH_SUCCESSFUL
198 return AUTH_FAILED
199
200 def check_auth_interactive(self, username, submethods):
201 if username == "commie":
202 self.username = username
203 return InteractiveQuery(
204 "password", "Please enter a password.", ("Password", False)
205 )
206 return AUTH_FAILED
207
208 def check_auth_interactive_response(self, responses):
209 if self.username == "commie":
210 if (len(responses) == 1) and (responses[0] == "cat"):
211 return AUTH_SUCCESSFUL
212 return AUTH_FAILED
213
214
215 @contextmanager
216 def server(
217 hostkey=None,
218 init=None,
219 server_init=None,
220 client_init=None,
221 connect=None,
222 pubkeys=None,
223 catch_error=False,
224 transport_factory=None,
225 server_transport_factory=None,
226 defer=False,
227 skip_verify=False,
228 ):
229 """
230 SSH server contextmanager for testing.
231
232 Yields a tuple of ``(tc, ts)`` (client- and server-side `Transport`
233 objects), or ``(tc, ts, err)`` when ``catch_error==True``.
234
235 :param hostkey:
236 Host key to use for the server; if None, loads
237 ``rsa.key``.
238 :param init:
239 Default `Transport` constructor kwargs to use for both sides.
240 :param server_init:
241 Extends and/or overrides ``init`` for server transport only.
242 :param client_init:
243 Extends and/or overrides ``init`` for client transport only.
244 :param connect:
245 Kwargs to use for ``connect()`` on the client.
246 :param pubkeys:
247 List of public keys for auth.
248 :param catch_error:
249 Whether to capture connection errors & yield from contextmanager.
250 Necessary for connection_time exception testing.
251 :param transport_factory:
252 Like the same-named param in SSHClient: which Transport class to use.
253 :param server_transport_factory:
254 Like ``transport_factory``, but only impacts the server transport.
255 :param bool defer:
256 Whether to defer authentication during connecting.
257
258 This is really just shorthand for ``connect={}`` which would do roughly
259 the same thing. Also: this implies skip_verify=True automatically!
260 :param bool skip_verify:
261 Whether NOT to do the default "make sure auth passed" check.
262 """
263 if init is None:
264 init = {}
265 if server_init is None:
266 server_init = {}
267 if client_init is None:
268 client_init = {}
269 if connect is None:
270 # No auth at all please
271 if defer:
272 connect = dict()
273 # Default username based auth
274 else:
275 connect = dict(username="slowdive", password="pygmalion")
276 socks = LoopSocket()
277 sockc = LoopSocket()
278 sockc.link(socks)
279 if transport_factory is None:
280 transport_factory = Transport
281 if server_transport_factory is None:
282 server_transport_factory = transport_factory
283 tc = transport_factory(sockc, **dict(init, **client_init))
284 ts = server_transport_factory(socks, **dict(init, **server_init))
285
286 if hostkey is None:
287 hostkey = RSAKey.from_private_key_file(_support("rsa.key"))
288 ts.add_server_key(hostkey)
289 event = threading.Event()
290 server = TestServer(allowed_keys=pubkeys)
291 assert not event.is_set()
292 assert not ts.is_active()
293 assert tc.get_username() is None
294 assert ts.get_username() is None
295 assert not tc.is_authenticated()
296 assert not ts.is_authenticated()
297
298 err = None
299 # Trap errors and yield instead of raising right away; otherwise callers
300 # cannot usefully deal with problems at connect time which stem from errors
301 # in the server side.
302 try:
303 ts.start_server(event, server)
304 tc.connect(**connect)
305
306 event.wait(1.0)
307 assert event.is_set()
308 assert ts.is_active()
309 assert tc.is_active()
310
311 except Exception as e:
312 if not catch_error:
313 raise
314 err = e
315
316 yield (tc, ts, err) if catch_error else (tc, ts)
317
318 if not (catch_error or skip_verify or defer):
319 assert ts.is_authenticated()
320 assert tc.is_authenticated()
321
322 tc.close()
323 ts.close()
324 socks.close()
325 sockc.close()
326
327
328 def wait_until(condition, *, timeout=2):
329 """
330 Wait until `condition()` no longer raises an `AssertionError` or until
331 `timeout` seconds have passed, which causes a `TimeoutError` to be raised.
332 """
333 deadline = time.time() + timeout
334
335 while True:
336 try:
337 condition()
338 except AssertionError as e:
339 if time.time() > deadline:
340 timeout_message = f"Condition not reached after {timeout}s"
341 raise TimeoutError(timeout_message) from e
342 else:
343 return
344 time.sleep(0.01)