Package x2go :: Module _paramiko

[frames] | no frames]

# Source Code for Module x2go._paramiko

      1  # -*- coding: utf-8 -*-
      2
      3  # Copyright (C) 2010-2013 by Mike Gabriel <mike.gabriel@das-netzwerkteam.de>
      4  #
      5  # Python X2Go is free software; you can redistribute it and/or modify
      6  # it under the terms of the GNU Affero General Public License as published by
      7  # the Free Software Foundation; either version 3 of the License, or
      8  # (at your option) any later version.
      9  #
     10  # Python X2Go is distributed in the hope that it will be useful,
     11  # but WITHOUT ANY WARRANTY; without even the implied warranty of
     12  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     13  # GNU Affero General Public License for more details.
     14  #
     15  # You should have received a copy of the GNU Affero General Public License
     16  # along with this program; if not, write to the
     17  # Free Software Foundation, Inc.,
     18  # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
     19
     20  """\
     21  Monkey Patch and feature map for Python Paramiko
     22
     23  """
     24
     25  import paramiko
     26  import re
     27  from paramiko.config import SSH_PORT
     28  import platform
     29  from utils import compare_versions
     30
     31  PARAMIKO_VERSION = paramiko.__version__.split()[0]
     32  PARAMIKO_FEATURE = {
     33      'forward-ssh-agent': compare_versions(PARAMIKO_VERSION, ">=", '1.8.0') and (platform.system() != "Windows"),
     34      'use-compression': compare_versions(PARAMIKO_VERSION, ">=", '1.7.7.1'),
     35      'hash-host-entries': compare_versions(PARAMIKO_VERSION, ">=", '99'),
     36      'host-entries-reloadable': compare_versions(PARAMIKO_VERSION, ">=", '1.11.0'),
     37      'preserve-known-hosts': compare_versions(PARAMIKO_VERSION, ">=", '1.11.0'),
     38  }
     39
     40 -def _SSHClient_save_host_keys(self, filename):
     41      """\
     42      Available since paramiko 1.11.0...
     43
     44      This method has been taken from SSHClient class in Paramiko and
     45      has been improved and adapted to latest SSH implementations.
     46
     47      Save the host keys back to a file.
     48      Only the host keys loaded with
     49      L{load_host_keys} (plus any added directly) will be saved -- not any
     50      host keys loaded with L{load_system_host_keys}.
     51
     52      @param filename: the filename to save to
     53      @type filename: str
     54
     55      @raise IOError: if the file could not be written
     56
     57      """
     58      # update local host keys from file (in case other SSH clients
     59      # have written to the known_hosts file meanwhile.
     60      if self.known_hosts is not None:
     61          self.load_host_keys(self.known_hosts)
     62
     63      f = open(filename, 'w')
     64      #f.write('# SSH host keys collected by paramiko\n')
     65      _host_keys = self.get_host_keys()
     66      for hostname, keys in _host_keys.iteritems():
     67
     68          for keytype, key in keys.iteritems():
     69              f.write('%s %s %s\n' % (hostname, keytype, key.get_base64()))
     70
     71      f.close()
     72
     73
     74 -def _HostKeys_load(self, filename):
     75      """\
     76      Available since paramiko 1.11.0...
     77
     78      Read a file of known SSH host keys, in the format used by openssh.
     79      This type of file unfortunately doesn't exist on Windows, but on
     80      posix, it will usually be stored in
     81      C{os.path.expanduser("~/.ssh/known_hosts")}.
     82
     83      If this method is called multiple times, the host keys are merged,
     84      not cleared. So multiple calls to C{load} will just call L{add},
     85      replacing any existing entries and adding new ones.
     86
     87      @param filename: name of the file to read host keys from
     88      @type filename: str
     89
     90      @raise IOError: if there was an error reading the file
     91
     92      """
     93      f = open(filename, 'r')
     94      for line in f:
     95          line = line.strip()
     96          if (len(line) == 0) or (line[0] == '#'):
     97              continue
     98          e = paramiko.hostkeys.HostKeyEntry.from_line(line)
     99          if e is not None:
    100              _hostnames = e.hostnames
    101              for h in _hostnames:
    102                  if self.check(h, e.key):
    103                      e.hostnames.remove(h)
    104              if len(e.hostnames):
    105                  self._entries.append(e)
    106      f.close()
    107
    108
    109 -def _HostKeys_add(self, hostname, keytype, key, hash_hostname=True):
    110      """\
    111      Add a host key entry to the table. Any existing entry for a
    112      C{(hostname, keytype)} pair will be replaced.
    113
    114      @param hostname: the hostname (or IP) to add
    115      @type hostname: str
    116      @param keytype: key type (C{"ssh-rsa"} or C{"ssh-dss"})
    117      @type keytype: str
    118      @param key: the key to add
    119      @type key: L{PKey}
    120
    121      """
    122      # IPv4 and IPv6 addresses using the SSH default port need to be stripped off the port number
    123      if re.match('^\[.*\]\:'+str(SSH_PORT)+'$', hostname):
    124          # so stripping off the port and the square brackets here...
    125          hostname = hostname.split(':')[-2].lstrip('[').rstrip(']')
    126
    127      for e in self._entries:
    128          if (hostname in e.hostnames) and (e.key.get_name() == keytype):
    129              e.key = key
    130              return
    131      if not hostname.startswith('|1|') and hash_hostname:
    132          hostname = self.hash_host(hostname)
    133      self._entries.append(paramiko.hostkeys.HostKeyEntry([hostname], key))
    134
    135
    136 -def monkey_patch_paramiko():
    137      if not PARAMIKO_FEATURE['preserve-known-hosts']:
    138          paramiko.SSHClient.save_host_keys = _SSHClient_save_host_keys
    139      if not PARAMIKO_FEATURE['host-entries-reloadable']:
    140          paramiko.hostkeys.HostKeys.load = _HostKeys_load
    141      if not PARAMIKO_FEATURE['hash-host-entries']:
    142          paramiko.hostkeys.HostKeys.add = _HostKeys_add
    143