1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 """
20 `.ServerInterface` is an interface to override for server support.
21 """
22
23 import threading
24 from paramiko import util
25 from paramiko.common import DEBUG, ERROR, OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED, AUTH_FAILED
26 from paramiko.py3compat import string_types
27
28
30 """
31 This class defines an interface for controlling the behavior of Paramiko
32 in server mode.
33
34 Methods on this class are called from Paramiko's primary thread, so you
35 shouldn't do too much work in them. (Certainly nothing that blocks or
36 sleeps.)
37 """
38
40 """
41 Determine if a channel request of a given type will be granted, and
42 return ``OPEN_SUCCEEDED`` or an error code. This method is
43 called in server mode when the client requests a channel, after
44 authentication is complete.
45
46 If you allow channel requests (and an ssh server that didn't would be
47 useless), you should also override some of the channel request methods
48 below, which are used to determine which services will be allowed on
49 a given channel:
50
51 - `check_channel_pty_request`
52 - `check_channel_shell_request`
53 - `check_channel_subsystem_request`
54 - `check_channel_window_change_request`
55 - `check_channel_x11_request`
56 - `check_channel_forward_agent_request`
57
58 The ``chanid`` parameter is a small number that uniquely identifies the
59 channel within a `.Transport`. A `.Channel` object is not created
60 unless this method returns ``OPEN_SUCCEEDED`` -- once a
61 `.Channel` object is created, you can call `.Channel.get_id` to
62 retrieve the channel ID.
63
64 The return value should either be ``OPEN_SUCCEEDED`` (or
65 ``0``) to allow the channel request, or one of the following error
66 codes to reject it:
67
68 - ``OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED``
69 - ``OPEN_FAILED_CONNECT_FAILED``
70 - ``OPEN_FAILED_UNKNOWN_CHANNEL_TYPE``
71 - ``OPEN_FAILED_RESOURCE_SHORTAGE``
72
73 The default implementation always returns
74 ``OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED``.
75
76 :param str kind:
77 the kind of channel the client would like to open (usually
78 ``"session"``).
79 :param int chanid: ID of the channel
80 :return: an `int` success or failure code (listed above)
81 """
82 return OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
83
85 """
86 Return a list of authentication methods supported by the server.
87 This list is sent to clients attempting to authenticate, to inform them
88 of authentication methods that might be successful.
89
90 The "list" is actually a string of comma-separated names of types of
91 authentication. Possible values are ``"password"``, ``"publickey"``,
92 and ``"none"``.
93
94 The default implementation always returns ``"password"``.
95
96 :param str username: the username requesting authentication.
97 :return: a comma-separated `str` of authentication types
98 """
99 return 'password'
100
102 """
103 Determine if a client may open channels with no (further)
104 authentication.
105
106 Return `.AUTH_FAILED` if the client must authenticate, or
107 `.AUTH_SUCCESSFUL` if it's okay for the client to not
108 authenticate.
109
110 The default implementation always returns `.AUTH_FAILED`.
111
112 :param str username: the username of the client.
113 :return:
114 `.AUTH_FAILED` if the authentication fails; `.AUTH_SUCCESSFUL` if
115 it succeeds.
116 :rtype: int
117 """
118 return AUTH_FAILED
119
121 """
122 Determine if a given username and password supplied by the client is
123 acceptable for use in authentication.
124
125 Return `.AUTH_FAILED` if the password is not accepted,
126 `.AUTH_SUCCESSFUL` if the password is accepted and completes
127 the authentication, or `.AUTH_PARTIALLY_SUCCESSFUL` if your
128 authentication is stateful, and this key is accepted for
129 authentication, but more authentication is required. (In this latter
130 case, `get_allowed_auths` will be called to report to the client what
131 options it has for continuing the authentication.)
132
133 The default implementation always returns `.AUTH_FAILED`.
134
135 :param str username: the username of the authenticating client.
136 :param str password: the password given by the client.
137 :return:
138 `.AUTH_FAILED` if the authentication fails; `.AUTH_SUCCESSFUL` if
139 it succeeds; `.AUTH_PARTIALLY_SUCCESSFUL` if the password auth is
140 successful, but authentication must continue.
141 :rtype: int
142 """
143 return AUTH_FAILED
144
146 """
147 Determine if a given key supplied by the client is acceptable for use
148 in authentication. You should override this method in server mode to
149 check the username and key and decide if you would accept a signature
150 made using this key.
151
152 Return `.AUTH_FAILED` if the key is not accepted,
153 `.AUTH_SUCCESSFUL` if the key is accepted and completes the
154 authentication, or `.AUTH_PARTIALLY_SUCCESSFUL` if your
155 authentication is stateful, and this password is accepted for
156 authentication, but more authentication is required. (In this latter
157 case, `get_allowed_auths` will be called to report to the client what
158 options it has for continuing the authentication.)
159
160 Note that you don't have to actually verify any key signtature here.
161 If you're willing to accept the key, Paramiko will do the work of
162 verifying the client's signature.
163
164 The default implementation always returns `.AUTH_FAILED`.
165
166 :param str username: the username of the authenticating client
167 :param .PKey key: the key object provided by the client
168 :return:
169 `.AUTH_FAILED` if the client can't authenticate with this key;
170 `.AUTH_SUCCESSFUL` if it can; `.AUTH_PARTIALLY_SUCCESSFUL` if it
171 can authenticate with this key but must continue with
172 authentication
173 :rtype: int
174 """
175 return AUTH_FAILED
176
178 """
179 Begin an interactive authentication challenge, if supported. You
180 should override this method in server mode if you want to support the
181 ``"keyboard-interactive"`` auth type, which requires you to send a
182 series of questions for the client to answer.
183
184 Return `.AUTH_FAILED` if this auth method isn't supported. Otherwise,
185 you should return an `.InteractiveQuery` object containing the prompts
186 and instructions for the user. The response will be sent via a call
187 to `check_auth_interactive_response`.
188
189 The default implementation always returns `.AUTH_FAILED`.
190
191 :param str username: the username of the authenticating client
192 :param str submethods:
193 a comma-separated list of methods preferred by the client (usually
194 empty)
195 :return:
196 `.AUTH_FAILED` if this auth method isn't supported; otherwise an
197 object containing queries for the user
198 :rtype: int or `.InteractiveQuery`
199 """
200 return AUTH_FAILED
201
203 """
204 Continue or finish an interactive authentication challenge, if
205 supported. You should override this method in server mode if you want
206 to support the ``"keyboard-interactive"`` auth type.
207
208 Return `.AUTH_FAILED` if the responses are not accepted,
209 `.AUTH_SUCCESSFUL` if the responses are accepted and complete
210 the authentication, or `.AUTH_PARTIALLY_SUCCESSFUL` if your
211 authentication is stateful, and this set of responses is accepted for
212 authentication, but more authentication is required. (In this latter
213 case, `get_allowed_auths` will be called to report to the client what
214 options it has for continuing the authentication.)
215
216 If you wish to continue interactive authentication with more questions,
217 you may return an `.InteractiveQuery` object, which should cause the
218 client to respond with more answers, calling this method again. This
219 cycle can continue indefinitely.
220
221 The default implementation always returns `.AUTH_FAILED`.
222
223 :param list responses: list of `str` responses from the client
224 :return:
225 `.AUTH_FAILED` if the authentication fails; `.AUTH_SUCCESSFUL` if
226 it succeeds; `.AUTH_PARTIALLY_SUCCESSFUL` if the interactive auth
227 is successful, but authentication must continue; otherwise an
228 object containing queries for the user
229 :rtype: int or `.InteractiveQuery`
230 """
231 return AUTH_FAILED
232
234 """
235 Handle a request for port forwarding. The client is asking that
236 connections to the given address and port be forwarded back across
237 this ssh connection. An address of ``"0.0.0.0"`` indicates a global
238 address (any address associated with this server) and a port of ``0``
239 indicates that no specific port is requested (usually the OS will pick
240 a port).
241
242 The default implementation always returns ``False``, rejecting the
243 port forwarding request. If the request is accepted, you should return
244 the port opened for listening.
245
246 :param str address: the requested address
247 :param int port: the requested port
248 :return:
249 the port number (`int`) that was opened for listening, or ``False``
250 to reject
251 """
252 return False
253
255 """
256 The client would like to cancel a previous port-forwarding request.
257 If the given address and port is being forwarded across this ssh
258 connection, the port should be closed.
259
260 :param str address: the forwarded address
261 :param int port: the forwarded port
262 """
263 pass
264
266 """
267 Handle a global request of the given ``kind``. This method is called
268 in server mode and client mode, whenever the remote host makes a global
269 request. If there are any arguments to the request, they will be in
270 ``msg``.
271
272 There aren't any useful global requests defined, aside from port
273 forwarding, so usually this type of request is an extension to the
274 protocol.
275
276 If the request was successful and you would like to return contextual
277 data to the remote host, return a tuple. Items in the tuple will be
278 sent back with the successful result. (Note that the items in the
279 tuple can only be strings, ints, longs, or bools.)
280
281 The default implementation always returns ``False``, indicating that it
282 does not support any global requests.
283
284 .. note:: Port forwarding requests are handled separately, in
285 `check_port_forward_request`.
286
287 :param str kind: the kind of global request being made.
288 :param .Message msg: any extra arguments to the request.
289 :return:
290 ``True`` or a `tuple` of data if the request was granted; ``False``
291 otherwise.
292 """
293 return False
294
295
296
299 """
300 Determine if a pseudo-terminal of the given dimensions (usually
301 requested for shell access) can be provided on the given channel.
302
303 The default implementation always returns ``False``.
304
305 :param .Channel channel: the `.Channel` the pty request arrived on.
306 :param str term: type of terminal requested (for example, ``"vt100"``).
307 :param int width: width of screen in characters.
308 :param int height: height of screen in characters.
309 :param int pixelwidth:
310 width of screen in pixels, if known (may be ``0`` if unknown).
311 :param int pixelheight:
312 height of screen in pixels, if known (may be ``0`` if unknown).
313 :return:
314 ``True`` if the psuedo-terminal has been allocated; ``False``
315 otherwise.
316 """
317 return False
318
320 """
321 Determine if a shell will be provided to the client on the given
322 channel. If this method returns ``True``, the channel should be
323 connected to the stdin/stdout of a shell (or something that acts like
324 a shell).
325
326 The default implementation always returns ``False``.
327
328 :param .Channel channel: the `.Channel` the request arrived on.
329 :return:
330 ``True`` if this channel is now hooked up to a shell; ``False`` if
331 a shell can't or won't be provided.
332 """
333 return False
334
336 """
337 Determine if a shell command will be executed for the client. If this
338 method returns ``True``, the channel should be connected to the stdin,
339 stdout, and stderr of the shell command.
340
341 The default implementation always returns ``False``.
342
343 :param .Channel channel: the `.Channel` the request arrived on.
344 :param str command: the command to execute.
345 :return:
346 ``True`` if this channel is now hooked up to the stdin, stdout, and
347 stderr of the executing command; ``False`` if the command will not
348 be executed.
349
350 .. versionadded:: 1.1
351 """
352 return False
353
355 """
356 Determine if a requested subsystem will be provided to the client on
357 the given channel. If this method returns ``True``, all future I/O
358 through this channel will be assumed to be connected to the requested
359 subsystem. An example of a subsystem is ``sftp``.
360
361 The default implementation checks for a subsystem handler assigned via
362 `.Transport.set_subsystem_handler`.
363 If one has been set, the handler is invoked and this method returns
364 ``True``. Otherwise it returns ``False``.
365
366 .. note:: Because the default implementation uses the `.Transport` to
367 identify valid subsystems, you probably won't need to override this
368 method.
369
370 :param .Channel channel: the `.Channel` the pty request arrived on.
371 :param str name: name of the requested subsystem.
372 :return:
373 ``True`` if this channel is now hooked up to the requested
374 subsystem; ``False`` if that subsystem can't or won't be provided.
375 """
376 handler_class, larg, kwarg = channel.get_transport()._get_subsystem_handler(name)
377 if handler_class is None:
378 return False
379 handler = handler_class(channel, name, self, *larg, **kwarg)
380 handler.start()
381 return True
382
384 """
385 Determine if the pseudo-terminal on the given channel can be resized.
386 This only makes sense if a pty was previously allocated on it.
387
388 The default implementation always returns ``False``.
389
390 :param .Channel channel: the `.Channel` the pty request arrived on.
391 :param int width: width of screen in characters.
392 :param int height: height of screen in characters.
393 :param int pixelwidth:
394 width of screen in pixels, if known (may be ``0`` if unknown).
395 :param int pixelheight:
396 height of screen in pixels, if known (may be ``0`` if unknown).
397 :return: ``True`` if the terminal was resized; ``False`` if not.
398 """
399 return False
400
402 """
403 Determine if the client will be provided with an X11 session. If this
404 method returns ``True``, X11 applications should be routed through new
405 SSH channels, using `.Transport.open_x11_channel`.
406
407 The default implementation always returns ``False``.
408
409 :param .Channel channel: the `.Channel` the X11 request arrived on
410 :param bool single_connection:
411 ``True`` if only a single X11 channel should be opened, else
412 ``False``.
413 :param str auth_protocol: the protocol used for X11 authentication
414 :param str auth_cookie: the cookie used to authenticate to X11
415 :param int screen_number: the number of the X11 screen to connect to
416 :return: ``True`` if the X11 session was opened; ``False`` if not
417 """
418 return False
419
421 """
422 Determine if the client will be provided with an forward agent session.
423 If this method returns ``True``, the server will allow SSH Agent
424 forwarding.
425
426 The default implementation always returns ``False``.
427
428 :param .Channel channel: the `.Channel` the request arrived on
429 :return: ``True`` if the AgentForward was loaded; ``False`` if not
430 """
431 return False
432
434 """
435 Determine if a local port forwarding channel will be granted, and
436 return ``OPEN_SUCCEEDED`` or an error code. This method is
437 called in server mode when the client requests a channel, after
438 authentication is complete.
439
440 The ``chanid`` parameter is a small number that uniquely identifies the
441 channel within a `.Transport`. A `.Channel` object is not created
442 unless this method returns ``OPEN_SUCCEEDED`` -- once a
443 `.Channel` object is created, you can call `.Channel.get_id` to
444 retrieve the channel ID.
445
446 The origin and destination parameters are (ip_address, port) tuples
447 that correspond to both ends of the TCP connection in the forwarding
448 tunnel.
449
450 The return value should either be ``OPEN_SUCCEEDED`` (or
451 ``0``) to allow the channel request, or one of the following error
452 codes to reject it:
453
454 - ``OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED``
455 - ``OPEN_FAILED_CONNECT_FAILED``
456 - ``OPEN_FAILED_UNKNOWN_CHANNEL_TYPE``
457 - ``OPEN_FAILED_RESOURCE_SHORTAGE``
458
459 The default implementation always returns
460 ``OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED``.
461
462 :param int chanid: ID of the channel
463 :param tuple origin:
464 2-tuple containing the IP address and port of the originator
465 (client side)
466 :param tuple destination:
467 2-tuple containing the IP address and port of the destination
468 (server side)
469 :return: an `int` success or failure code (listed above)
470 """
471 return OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
472
474 """
475 Check whether a given environment variable can be specified for the
476 given channel. This method should return C{True} if the server
477 is willing to set the specified environment variable. Note that
478 some environment variables (e.g., PATH) can be exceedingly
479 dangerous, so blindly allowing the client to set the environment
480 is almost certainly not a good idea.
481
482 The default implementation always returns C{False}.
483
484 @param channel: the L{Channel} the env request arrived on
485 @type channel: L{Channel}
486 @param name: foo bar baz
487 @type name: str
488 @param value: flklj
489 @type value: str
490 @rtype: bool
491 """
492 return False
493
494
496 """
497 A query (set of prompts) for a user during interactive authentication.
498 """
499
500 - def __init__(self, name='', instructions='', *prompts):
501 """
502 Create a new interactive query to send to the client. The name and
503 instructions are optional, but are generally displayed to the end
504 user. A list of prompts may be included, or they may be added via
505 the `add_prompt` method.
506
507 :param str name: name of this query
508 :param str instructions:
509 user instructions (usually short) about this query
510 :param str prompts: one or more authentication prompts
511 """
512 self.name = name
513 self.instructions = instructions
514 self.prompts = []
515 for x in prompts:
516 if isinstance(x, string_types):
517 self.add_prompt(x)
518 else:
519 self.add_prompt(x[0], x[1])
520
522 """
523 Add a prompt to this query. The prompt should be a (reasonably short)
524 string. Multiple prompts can be added to the same query.
525
526 :param str prompt: the user prompt
527 :param bool echo:
528 ``True`` (default) if the user's response should be echoed;
529 ``False`` if not (for a password or similar)
530 """
531 self.prompts.append((prompt, echo))
532
533
535 """
536 Handler for a subsytem in server mode. If you create a subclass of this
537 class and pass it to `.Transport.set_subsystem_handler`, an object of this
538 class will be created for each request for this subsystem. Each new object
539 will be executed within its own new thread by calling `start_subsystem`.
540 When that method completes, the channel is closed.
541
542 For example, if you made a subclass ``MP3Handler`` and registered it as the
543 handler for subsystem ``"mp3"``, then whenever a client has successfully
544 authenticated and requests subsytem ``"mp3"``, an object of class
545 ``MP3Handler`` will be created, and `start_subsystem` will be called on
546 it from a new thread.
547 """
548 - def __init__(self, channel, name, server):
549 """
550 Create a new handler for a channel. This is used by `.ServerInterface`
551 to start up a new handler when a channel requests this subsystem. You
552 don't need to override this method, but if you do, be sure to pass the
553 ``channel`` and ``name`` parameters through to the original ``__init__``
554 method here.
555
556 :param .Channel channel: the channel associated with this subsystem request.
557 :param str name: name of the requested subsystem.
558 :param .ServerInterface server:
559 the server object for the session that started this subsystem
560 """
561 threading.Thread.__init__(self, target=self._run)
562 self.__channel = channel
563 self.__transport = channel.get_transport()
564 self.__name = name
565 self.__server = server
566
568 """
569 Return the `.ServerInterface` object associated with this channel and
570 subsystem.
571 """
572 return self.__server
573
575 try:
576 self.__transport._log(DEBUG, 'Starting handler for subsystem %s' % self.__name)
577 self.start_subsystem(self.__name, self.__transport, self.__channel)
578 except Exception as e:
579 self.__transport._log(ERROR, 'Exception in subsystem handler for "%s": %s' %
580 (self.__name, str(e)))
581 self.__transport._log(ERROR, util.tb_strings())
582 try:
583 self.finish_subsystem()
584 except:
585 pass
586
588 """
589 Process an ssh subsystem in server mode. This method is called on a
590 new object (and in a new thread) for each subsystem request. It is
591 assumed that all subsystem logic will take place here, and when the
592 subsystem is finished, this method will return. After this method
593 returns, the channel is closed.
594
595 The combination of ``transport`` and ``channel`` are unique; this handler
596 corresponds to exactly one `.Channel` on one `.Transport`.
597
598 .. note::
599 It is the responsibility of this method to exit if the underlying
600 `.Transport` is closed. This can be done by checking
601 `.Transport.is_active` or noticing an EOF on the `.Channel`. If
602 this method loops forever without checking for this case, your
603 Python interpreter may refuse to exit because this thread will
604 still be running.
605
606 :param str name: name of the requested subsystem.
607 :param .Transport transport: the server-mode `.Transport`.
608 :param .Channel channel: the channel associated with this subsystem request.
609 """
610 pass
611
613 """
614 Perform any cleanup at the end of a subsystem. The default
615 implementation just closes the channel.
616
617 .. versionadded:: 1.1
618 """
619 self.__channel.close()
620