Debian Codegraph @

ncclient/transport/ssh.py

raw
1 # Copyright 2012 Vaibhav Bajpai
2 # Copyright 2009 Shikhar Bhushan
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 import base64
17 import getpass
18 import os
19 import re
20 import sys
21 import socket
22 import threading
23 from binascii import hexlify
24 from io import BytesIO as StringIO
25
26 try:
27 import selectors
28 except ImportError:
29 import selectors2 as selectors
30
31 from ncclient.capabilities import Capabilities
32 from ncclient.logging_ import SessionLoggerAdapter
33
34 import paramiko
35
36 from ncclient.transport.errors import AuthenticationError, SSHError, SSHUnknownHostError
37 from ncclient.transport.session import Session
38 from ncclient.transport.parser import DefaultXMLParser
39
40 import logging
41 logger = logging.getLogger("ncclient.transport.ssh")
42
43 PORT_NETCONF_DEFAULT = 830
44
45 BUF_SIZE = 4096
46
47 #
48 # Define delimiters for chunks and messages for netconf 1.1 chunk enoding.
49 # When matched:
50 #
51 # * result.group(0) will contain whole matched string
52 # * result.group(1) will contain the digit string for a chunk
53 # * result.group(2) will be defined if '##' found
54 #
55 RE_NC11_DELIM = re.compile(br'\n(?:#([0-9]+)|(##))\n')
56
57
58 def default_unknown_host_cb(host, fingerprint):
59 """An unknown host callback returns `True` if it finds the key acceptable, and `False` if not.
60
61 This default callback always returns `False`, which would lead to :meth:`connect` raising a :exc:`SSHUnknownHost` exception.
62
63 Supply another valid callback if you need to verify the host key programmatically.
64
65 *host* is the hostname that needs to be verified
66
67 *fingerprint* is a hex string representing the host key fingerprint, colon-delimited e.g. `"4b:69:6c:72:6f:79:20:77:61:73:20:68:65:72:65:21"`
68 """
69 return False
70
71
72 def _colonify(fp):
73 fp = fp.decode('UTF-8')
74 finga = fp[:2]
75 for idx in range(2, len(fp), 2):
76 finga += ":" + fp[idx:idx+2]
77 return finga
78
79
80 class SSHSession(Session):
81
82 "Implements a :rfc:`4742` NETCONF session over SSH."
83
84 def __init__(self, device_handler):
85 capabilities = Capabilities(device_handler.get_capabilities())
86 Session.__init__(self, capabilities)
87 self._host = None
88 self._host_keys = paramiko.HostKeys()
89 self._transport = None
90 self._connected = False
91 self._channel = None
92 self._channel_id = None
93 self._channel_name = None
94 self._buffer = StringIO()
95 self._device_handler = device_handler
96 self._message_list = []
97 self._closing = threading.Event()
98 self.parser = DefaultXMLParser(self) # SAX or DOM parser
99
100 self.logger = SessionLoggerAdapter(logger, {'session': self})
101
102 def _dispatch_message(self, raw):
103 # Provide basic response message
104 self.logger.info("Received message from host")
105 # Provide complete response from host at debug log level
106 self.logger.debug("Received:\n%s", raw)
107 return super(SSHSession, self)._dispatch_message(raw)
108
109 def _parse(self):
110 "Messages ae delimited by MSG_DELIM. The buffer could have grown by a maximum of BUF_SIZE bytes everytime this method is called. Retains state across method calls and if a byte has been read it will not be considered again."
111 return self.parser._parse10()
112
113 def load_known_hosts(self, filename=None):
114
115 """Load host keys from an openssh :file:`known_hosts`-style file. Can
116 be called multiple times.
117
118 If *filename* is not specified, looks in the default locations i.e. :file:`~/.ssh/known_hosts` and :file:`~/ssh/known_hosts` for Windows.
119 """
120
121 if filename is None:
122 filename = os.path.expanduser('~/.ssh/known_hosts')
123 try:
124 self._host_keys.load(filename)
125 except IOError:
126 # for windows
127 filename = os.path.expanduser('~/ssh/known_hosts')
128 try:
129 self._host_keys.load(filename)
130 except IOError:
131 pass
132 else:
133 self._host_keys.load(filename)
134
135 def close(self):
136 self._closing.set()
137 if self._transport.is_active():
138 self._transport.close()
139
140 # Wait for the transport thread to close.
141 while self.is_alive() and (self is not threading.current_thread()):
142 self.join(10)
143
144 if self._channel:
145 self._channel.close()
146 self._channel = None
147 self._connected = False
148
149 # REMEMBER to update transport.rst if sig. changes, since it is hardcoded there
150 def connect(
151 self,
152 host,
153 port = PORT_NETCONF_DEFAULT,
154 timeout = None,
155 unknown_host_cb = default_unknown_host_cb,
156 username = None,
157 password = None,
158 key_filename = None,
159 allow_agent = True,
160 hostkey_verify = True,
161 hostkey_b64 = None,
162 look_for_keys = True,
163 ssh_config = None,
164 sock_fd = None,
165 bind_addr = None,
166 sock = None,
167 keepalive = None,
168 environment = None):
169
170 """Connect via SSH and initialize the NETCONF session. First attempts the publickey authentication method and then password authentication.
171
172 To disable attempting publickey authentication altogether, call with *allow_agent* and *look_for_keys* as `False`.
173
174 *host* is the hostname or IP address to connect to
175
176 *port* is by default 830 (PORT_NETCONF_DEFAULT), but some devices use the default SSH port of 22 so this may need to be specified
177
178 *timeout* is an optional timeout for socket connect
179
180 *unknown_host_cb* is called when the server host key is not recognized. It takes two arguments, the hostname and the fingerprint (see the signature of :func:`default_unknown_host_cb`)
181
182 *username* is the username to use for SSH authentication
183
184 *password* is the password used if using password authentication, or the passphrase to use for unlocking keys that require it
185
186 *key_filename* is a filename where a the private key to be used can be found
187
188 *allow_agent* enables querying SSH agent (if found) for keys
189
190 *hostkey_verify* enables hostkey verification from ~/.ssh/known_hosts
191
192 *hostkey_b64* only connect when server presents a public hostkey matching this (obtain from server /etc/ssh/ssh_host_*pub or ssh-keyscan)
193
194 *look_for_keys* enables looking in the usual locations for ssh keys (e.g. :file:`~/.ssh/id_*`)
195
196 *ssh_config* enables parsing of an OpenSSH configuration file, if set to its path, e.g. :file:`~/.ssh/config` or to True (in this case, use :file:`~/.ssh/config`).
197
198 *sock_fd* is an already open socket which shall be used for this connection. Useful for NETCONF outbound ssh. Use host=None together with a valid sock_fd number
199
200 *bind_addr* is a (local) source IP address to use, must be reachable from the remote device.
201
202 *sock* is an already open Python socket to be used for this connection.
203
204 *keepalive* Turn on/off keepalive packets (default is off). If this is set, after interval seconds without sending any data over the connection, a "keepalive" packet will be sent (and ignored by the remote host). This can be useful to keep connections alive over a NAT.
205
206 *environment* a dictionary containing the name and respective values to set
207 """
208 if not (host or sock_fd or sock):
209 raise SSHError("Missing host, socket or socket fd")
210
211 self._host = host
212
213 # Optionally, parse .ssh/config
214 config = {}
215 if ssh_config is True:
216 ssh_config = "~/.ssh/config" if sys.platform != "win32" else "~/ssh/config"
217 if ssh_config is not None:
218 config = paramiko.SSHConfig()
219 with open(os.path.expanduser(ssh_config)) as ssh_config_file_obj:
220 config.parse(ssh_config_file_obj)
221
222 # Save default Paramiko SSH port so it can be reverted
223 paramiko_default_ssh_port = paramiko.config.SSH_PORT
224
225 # Change the default SSH port to the port specified by the user so expand_variables
226 # replaces %p with the passed in port rather than 22 (the defauld paramiko.config.SSH_PORT)
227
228 paramiko.config.SSH_PORT = port
229
230 config = config.lookup(host)
231
232 # paramiko.config.SSHconfig::expand_variables is called by lookup so we can set the SSH port
233 # back to the default
234 paramiko.config.SSH_PORT = paramiko_default_ssh_port
235
236 host = config.get("hostname", host)
237 if username is None:
238 username = config.get("user")
239 if key_filename is None:
240 key_filename = config.get("identityfile")
241 if timeout is None:
242 timeout = config.get("connecttimeout")
243 if timeout:
244 timeout = int(timeout)
245
246 if hostkey_verify:
247 userknownhostsfile = config.get("userknownhostsfile")
248 if userknownhostsfile:
249 self.load_known_hosts(os.path.expanduser(userknownhostsfile))
250 else:
251 self.load_known_hosts()
252
253 if username is None:
254 username = getpass.getuser()
255
256 if sock_fd is None and sock is None:
257 proxycommand = config.get("proxycommand")
258 if proxycommand:
259 self.logger.debug("Configuring Proxy. %s", proxycommand)
260 if not isinstance(proxycommand, str):
261 proxycommand = [os.path.expanduser(elem) for elem in proxycommand]
262 else:
263 proxycommand = os.path.expanduser(proxycommand)
264 sock = paramiko.proxy.ProxyCommand(proxycommand)
265 else:
266 for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
267 af, socktype, proto, canonname, sa = res
268 try:
269 sock = socket.socket(af, socktype, proto)
270 sock.settimeout(timeout)
271 except socket.error:
272 continue
273 try:
274 if bind_addr:
275 sock.bind((bind_addr, 0))
276 sock.connect(sa)
277 except socket.error:
278 sock.close()
279 continue
280 break
281 else:
282 raise SSHError("Could not open socket to %s:%s" % (host, port))
283 elif sock is None:
284 sock = socket.fromfd(int(sock_fd), socket.AF_INET, socket.SOCK_STREAM)
285 sock.settimeout(timeout)
286
287 self._transport = paramiko.Transport(sock)
288 self._transport.set_log_channel(logger.name)
289 if config.get("compression") == 'yes':
290 self._transport.use_compression()
291
292 if hostkey_b64:
293 # If we need to connect with a specific hostkey, negotiate for only its type
294 hostkey_obj = None
295 for key_cls in [paramiko.DSSKey, paramiko.Ed25519Key, paramiko.RSAKey, paramiko.ECDSAKey]:
296 try:
297 hostkey_obj = key_cls(data=base64.b64decode(hostkey_b64))
298 except paramiko.SSHException:
299 # Not a key of this type - try the next
300 pass
301 if not hostkey_obj:
302 # We've tried all known host key types and haven't found a suitable one to use - bail
303 raise SSHError("Couldn't find suitable paramiko key class for host key %s" % hostkey_b64)
304 self._transport._preferred_keys = [hostkey_obj.get_name()]
305 elif self._host_keys:
306 # Else set preferred host keys to those we possess for the host
307 # (avoids situation where known_hosts contains a valid key for the host, but that key type is not selected during negotiation)
308 known_host_keys_for_this_host = self._host_keys.lookup(host) or {}
309 host_port = '[%s]:%s' % (host, port)
310 known_host_keys_for_this_host.update(self._host_keys.lookup(host_port) or {})
311 if known_host_keys_for_this_host:
312 self._transport._preferred_keys = list(known_host_keys_for_this_host)
313
314 # Connect
315 try:
316 self._transport.start_client()
317 except paramiko.SSHException as e:
318 raise SSHError('Negotiation failed: %s' % e)
319
320 if hostkey_verify:
321 server_key_obj = self._transport.get_remote_server_key()
322 fingerprint = _colonify(hexlify(server_key_obj.get_fingerprint()))
323
324 is_known_host = False
325
326 # For looking up entries for nonstandard (22) ssh ports in known_hosts
327 # we enclose host in brackets and append port number
328 known_hosts_lookups = [host, '[%s]:%s' % (host, port)]
329
330 if hostkey_b64:
331 # If hostkey specified, remote host /must/ use that hostkey
332 if(hostkey_obj.get_name() == server_key_obj.get_name() and hostkey_obj.asbytes() == server_key_obj.asbytes()):
333 is_known_host = True
334 else:
335 # Check known_hosts
336 is_known_host = any(self._host_keys.check(lookup, server_key_obj) for lookup in known_hosts_lookups)
337
338 if not is_known_host and not unknown_host_cb(host, fingerprint):
339 raise SSHUnknownHostError(known_hosts_lookups[0], fingerprint)
340
341 # Authenticating with our private key/identity
342 if key_filename is None:
343 key_filenames = []
344 elif isinstance(key_filename, (str, bytes)):
345 key_filenames = [key_filename]
346 else:
347 key_filenames = key_filename
348
349 self._auth(username, password, key_filenames, allow_agent, look_for_keys)
350
351 self._connected = True # there was no error authenticating
352 self._closing.clear()
353
354 if keepalive:
355 self._transport.set_keepalive(keepalive)
356
357 # TODO: leopoul: Review, test, and if needed rewrite this part
358 subsystem_names = self._device_handler.get_ssh_subsystem_names()
359 for subname in subsystem_names:
360 self._channel = self._transport.open_session()
361 self._channel_id = self._channel.get_id()
362 channel_name = "%s-subsystem-%s" % (subname, str(self._channel_id))
363 self._channel.set_name(channel_name)
364 if environment:
365 try:
366 self._channel.update_environment(environment)
367 except paramiko.SSHException as e:
368 self.logger.info("%s (environment update rejected)", e)
369 handle_exception = self._device_handler.handle_connection_exceptions(self)
370 # Ignore the exception, since we continue to try the different
371 # subsystem names until we find one that can connect.
372 # have to handle exception for each vendor here
373 if not handle_exception:
374 continue
375 try:
376 self._channel.invoke_subsystem(subname)
377 except paramiko.SSHException as e:
378 self.logger.info("%s (subsystem request rejected)", e)
379 handle_exception = self._device_handler.handle_connection_exceptions(self)
380 # Ignore the exception, since we continue to try the different
381 # subsystem names until we find one that can connect.
382 # have to handle exception for each vendor here
383 if not handle_exception:
384 continue
385 self._channel_name = self._channel.get_name()
386 self._post_connect(timeout)
387 # for further upcoming RPC responses, vendor can chose their
388 # choice of parser. Say DOM or SAX
389 self.parser = self._device_handler.get_xml_parser(self)
390 return
391 raise SSHError("Could not open connection, possibly due to unacceptable"
392 " SSH subsystem name.")
393
394 def _auth(self, username, password, key_filenames, allow_agent,
395 look_for_keys):
396 saved_exception = None
397
398 for key_filename in key_filenames:
399 try:
400 key = paramiko.PKey.from_path(key_filename, password.encode("utf-8"))
401 self.logger.debug("Trying key %s from %s",
402 hexlify(key.get_fingerprint()),
403 key_filename)
404 self._transport.auth_publickey(username, key)
405 return
406 except Exception as e:
407 saved_exception = e
408 self.logger.debug(e)
409
410 if allow_agent:
411 # resequence keys from agent using private key names
412 prepend_agent_keys=[]
413 append_agent_keys=list(paramiko.Agent().get_keys())
414
415 for key_filename in key_filenames:
416 pubkey_filename=key_filename.strip(".pub")+".pub"
417 try:
418 file_key=paramiko.PublicBlob.from_file(pubkey_filename).key_blob
419 except (FileNotFoundError, ValueError):
420 continue
421
422 for idx, agent_key in enumerate(append_agent_keys):
423 if agent_key.asbytes() == file_key:
424 self.logger.debug("Prioritising SSH agent key found in %s",key_filename )
425 prepend_agent_keys.append(append_agent_keys.pop(idx))
426 break
427
428 agent_keys=tuple(prepend_agent_keys+append_agent_keys)
429
430 for key in agent_keys:
431 try:
432 self.logger.debug("Trying SSH agent key %s",
433 hexlify(key.get_fingerprint()))
434 self._transport.auth_publickey(username, key)
435 return
436 except Exception as e:
437 saved_exception = e
438 self.logger.debug(e)
439
440 keyfiles = []
441 if look_for_keys:
442 rsa_key = os.path.expanduser("~/.ssh/id_rsa")
443 dsa_key = os.path.expanduser("~/.ssh/id_dsa")
444 ecdsa_key = os.path.expanduser("~/.ssh/id_ecdsa")
445 ed25519_key = os.path.expanduser("~/.ssh/id_ed25519")
446 if os.path.isfile(rsa_key):
447 keyfiles.append(rsa_key)
448 if os.path.isfile(dsa_key):
449 keyfiles.append(dsa_key)
450 if os.path.isfile(ecdsa_key):
451 keyfiles.append(ecdsa_key)
452 if os.path.isfile(ed25519_key):
453 keyfiles.append(ed25519_key)
454 # look in ~/ssh/ for windows users:
455 rsa_key = os.path.expanduser("~/ssh/id_rsa")
456 dsa_key = os.path.expanduser("~/ssh/id_dsa")
457 ecdsa_key = os.path.expanduser("~/ssh/id_ecdsa")
458 ed25519_key = os.path.expanduser("~/ssh/id_ed25519")
459 if os.path.isfile(rsa_key):
460 keyfiles.append(rsa_key)
461 if os.path.isfile(dsa_key):
462 keyfiles.append(dsa_key)
463 if os.path.isfile(ecdsa_key):
464 keyfiles.append(ecdsa_key)
465 if os.path.isfile(ed25519_key):
466 keyfiles.append(ed25519_key)
467
468 for filename in keyfiles:
469 try:
470 key = paramiko.PKey.from_path(filename, password.encode("utf-8"))
471 self.logger.debug("Trying discovered key %s in %s",
472 hexlify(key.get_fingerprint()), filename)
473 self._transport.auth_publickey(username, key)
474 return
475 except Exception as e:
476 saved_exception = e
477 self.logger.debug(e)
478
479 if password is not None:
480 try:
481 self._transport.auth_password(username, password)
482 return
483 except Exception as e:
484 saved_exception = e
485 self.logger.debug(e)
486
487 if saved_exception is not None:
488 # need pep-3134 to do this right
489 raise AuthenticationError(repr(saved_exception))
490
491 raise AuthenticationError("No authentication methods available")
492
493 def _transport_read(self):
494 return self._channel.recv(BUF_SIZE)
495
496 def _transport_write(self, data):
497 return self._channel.send(data)
498
499 def _transport_register(self, selector, event):
500 selector.register(self._channel, event)
501
502 def _send_ready(self):
503 return self._channel.send_ready()
504
505 @property
506 def host(self):
507 """Host this session is connected to, or None if not connected."""
508 if hasattr(self, '_host'):
509 return self._host
510 return None
511
512 @property
513 def transport(self):
514 "Underlying `paramiko.Transport <http://www.lag.net/paramiko/docs/paramiko.Transport-class.html>`_ object. This makes it possible to call methods like :meth:`~paramiko.Transport.set_keepalive` on it."
515 return self._transport