コード例 #1
0
    def download_payments(self):
        # # Add destination server host key
        if settings.LASKE_SERVERS['payments']['key_type'] == 'ssh-ed25519':
            key = paramiko.ed25519key.Ed25519Key(
                data=decodebytes(settings.LASKE_SERVERS['payments']['key']))
        elif 'ecdsa' in settings.LASKE_SERVERS['payments']['key_type']:
            key = paramiko.ecdsakey.ECDSAKey(
                data=decodebytes(settings.LASKE_SERVERS['payments']['key']))
        else:
            key = paramiko.rsakey.RSAKey(
                data=decodebytes(settings.LASKE_SERVERS['payments']['key']))

        hostkeys = paramiko.hostkeys.HostKeys()
        hostkeys.add(settings.LASKE_SERVERS['payments']['host'],
                     settings.LASKE_SERVERS['payments']['key_type'], key)

        cnopts = pysftp.CnOpts()
        cnopts.hostkeys = hostkeys
        # Or Disable key check:
        # cnopts.hostkeys = None

        with pysftp.Connection(
                settings.LASKE_SERVERS['payments']['host'],
                port=settings.LASKE_SERVERS['payments']['port'],
                username=settings.LASKE_SERVERS['payments']['username'],
                password=settings.LASKE_SERVERS['payments']['password'],
                cnopts=cnopts) as sftp:
            sftp.get_d(settings.LASKE_SERVERS['payments']['directory'],
                       get_import_dir(),
                       preserve_mtime=True)
コード例 #2
0
ファイル: exporter.py プロジェクト: City-of-Helsinki/mvj
    def send(self, filename):
        # Add destination server host key
        if settings.LASKE_SERVERS["export"]["key_type"] == "ssh-ed25519":
            key = paramiko.ed25519key.Ed25519Key(
                data=decodebytes(settings.LASKE_SERVERS["export"]["key"]))
        elif "ecdsa" in settings.LASKE_SERVERS["export"]["key_type"]:
            key = paramiko.ecdsakey.ECDSAKey(
                data=decodebytes(settings.LASKE_SERVERS["export"]["key"]))
        else:
            key = paramiko.rsakey.RSAKey(
                data=decodebytes(settings.LASKE_SERVERS["export"]["key"]))

        hostkeys = paramiko.hostkeys.HostKeys()
        hostkeys.add(
            settings.LASKE_SERVERS["export"]["host"],
            settings.LASKE_SERVERS["export"]["key_type"],
            key,
        )

        cnopts = pysftp.CnOpts()
        cnopts.hostkeys = hostkeys
        # Or Disable key check:
        # cnopts.hostkeys = None

        with pysftp.Connection(
                settings.LASKE_SERVERS["export"]["host"],
                port=settings.LASKE_SERVERS["export"]["port"],
                username=settings.LASKE_SERVERS["export"]["username"],
                password=settings.LASKE_SERVERS["export"]["password"],
                cnopts=cnopts,
        ) as sftp:
            with sftp.cd(settings.LASKE_SERVERS["export"]["directory"]):
                sftp.put(os.path.join(settings.LASKE_EXPORT_ROOT, filename))
コード例 #3
0
ファイル: exporter.py プロジェクト: hkotkanen/mvj
    def send(self, filename):
        # Add destination server host key
        if settings.LASKE_SERVERS['export']['key_type'] == 'ssh-ed25519':
            key = paramiko.ed25519key.Ed25519Key(
                data=decodebytes(settings.LASKE_SERVERS['export']['key']))
        elif 'ecdsa' in settings.LASKE_SERVERS['export']['key_type']:
            key = paramiko.ecdsakey.ECDSAKey(
                data=decodebytes(settings.LASKE_SERVERS['export']['key']))
        else:
            key = paramiko.rsakey.RSAKey(
                data=decodebytes(settings.LASKE_SERVERS['export']['key']))

        hostkeys = paramiko.hostkeys.HostKeys()
        hostkeys.add(settings.LASKE_SERVERS['export']['host'],
                     settings.LASKE_SERVERS['export']['key_type'], key)

        cnopts = pysftp.CnOpts()
        cnopts.hostkeys = hostkeys
        # Or Disable key check:
        # cnopts.hostkeys = None

        with pysftp.Connection(
                settings.LASKE_SERVERS['export']['host'],
                port=settings.LASKE_SERVERS['export']['port'],
                username=settings.LASKE_SERVERS['export']['username'],
                password=settings.LASKE_SERVERS['export']['password'],
                cnopts=cnopts) as sftp:
            with sftp.cd(settings.LASKE_SERVERS['export']['directory']):
                sftp.put(os.path.join(settings.LASKE_EXPORT_ROOT, filename))
コード例 #4
0
ファイル: sshserver.py プロジェクト: divyanshumehta/webssh
class Server(paramiko.ServerInterface):
    # 'data' is the output of base64.b64encode(key)
    # (using the "user_rsa_key" files)
    data = (b'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp'
            b'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC'
            b'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT'
            b'UWT10hcuO4Ks8=')
    good_pub_key = paramiko.RSAKey(data=decodebytes(data))

    langs = ['en_US.UTF-8', 'zh_CN.GBK']

    def __init__(self):
        self.shell_event = threading.Event()
        self.exec_event = threading.Event()
        self.lang = random.choice(self.langs)
        self.encoding = self.lang.split('.')[-1]

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        print('Auth attempt with username: {!r} & password: {!r}'.format(username, password)) # noqa
        if (username in ['robey', 'bar']) and (password == 'foo'):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def check_auth_publickey(self, username, key):
        print('Auth attempt with username: {!r} & key: {!r}'.format(username, u(hexlify(key.get_fingerprint())))) # noqa
        if (username == 'robey') and (key == self.good_pub_key):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def get_allowed_auths(self, username):
        return 'password,publickey'

    def check_channel_exec_request(self, channel, command):
        if command != b'locale':
            ret = False
        else:
            ret = True
            result = 'LANG={lang}\nLANGUAGE=\nLC_CTYPE="{lang}"\n'.format(lang=self.lang)  # noqa
            channel.send(result)
            channel.shutdown(1)
        self.exec_event.set()
        return ret

    def check_channel_shell_request(self, channel):
        self.shell_event.set()
        return True

    def check_channel_pty_request(self, channel, term, width, height,
                                  pixelwidth, pixelheight, modes):
        return True

    def check_channel_window_change_request(self, channel, width, height,
                                            pixelwidth, pixelheight):
        channel.send('resized')
        return True
コード例 #5
0
ファイル: pkey.py プロジェクト: YiJie0430/AM_HIVE_TCP
 def from_string(cls, string):
     """
     Create a public blob from a ``-cert.pub``-style string.
     """
     fields = string.split(None, 2)
     if len(fields) < 2:
         msg = "Not enough fields for public blob: {}"
         raise ValueError(msg.format(fields))
     key_type = fields[0]
     key_blob = decodebytes(b(fields[1]))
     try:
         comment = fields[2].strip()
     except IndexError:
         comment = None
     # Verify that the blob message first (string) field matches the
     # key_type
     m = Message(key_blob)
     blob_type = m.get_text()
     if blob_type != key_type:
         deets = "key type={!r}, but blob type={!r}".format(
             key_type, blob_type
         )
         raise ValueError("Invalid PublicBlob contents: {}".format(deets))
     # All good? All good.
     return cls(type_=key_type, blob=key_blob, comment=comment)
コード例 #6
0
ファイル: demo_server.py プロジェクト: leirenjieyi/pythonhack
class Server (paramiko.ServerInterface):
    # 'data' is the output of base64.b64encode(key)
    # (using the "user_rsa_key" files)
    data = (b'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp'
            b'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC'
            b'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT'
            b'UWT10hcuO4Ks8=')
    good_pub_key = paramiko.RSAKey(data=decodebytes(data))

    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        if (username == 'robey') and (password == 'foo'):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def check_auth_publickey(self, username, key):
#        print('Auth attempt with key: ' + u(hexlify(key.get_fingerprint())))
        if (username == 'robey') and (key == self.good_pub_key):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED
コード例 #7
0
    def download_payments_sftp(self):
        import paramiko
        import pysftp
        from paramiko import SSHException
        from paramiko.py3compat import decodebytes

        try:
            # Add destination server host key
            if settings.LASKE_SERVERS["payments"]["key_type"] == "ssh-ed25519":
                key = paramiko.ed25519key.Ed25519Key(
                    data=decodebytes(settings.LASKE_SERVERS["payments"]["key"])
                )
            elif "ecdsa" in settings.LASKE_SERVERS["payments"]["key_type"]:
                key = paramiko.ecdsakey.ECDSAKey(
                    data=decodebytes(settings.LASKE_SERVERS["payments"]["key"])
                )
            else:
                key = paramiko.rsakey.RSAKey(
                    data=decodebytes(settings.LASKE_SERVERS["payments"]["key"])
                )

            hostkeys = paramiko.hostkeys.HostKeys()
            hostkeys.add(
                settings.LASKE_SERVERS["payments"]["host"],
                settings.LASKE_SERVERS["payments"]["key_type"],
                key,
            )

            cnopts = pysftp.CnOpts()
            cnopts.hostkeys = hostkeys
            # Or Disable key check:
            # cnopts.hostkeys = None

            with pysftp.Connection(
                settings.LASKE_SERVERS["payments"]["host"],
                port=settings.LASKE_SERVERS["payments"]["port"],
                username=settings.LASKE_SERVERS["payments"]["username"],
                password=settings.LASKE_SERVERS["payments"]["password"],
                cnopts=cnopts,
            ) as sftp:
                sftp.get_d(
                    settings.LASKE_SERVERS["payments"]["directory"],
                    get_import_dir(),
                    preserve_mtime=True,
                )
        except SSHException as e:
            self.stdout.write("Error with the Laske payments server: {}".format(e))
コード例 #8
0
ファイル: tasks.py プロジェクト: ericswpark/shipper
def backup_build(self, build_id):
    build = Build.objects.get(id=build_id)
    mirrors = MirrorServer.objects.filter(enabled=True)

    # Check if there are any servers to back up to
    if len(mirrors) == 0:
        print("No mirror servers found to back up to. Exiting...")
        return

    # Setup lock
    lock_id = '{}-lock-{}'.format(self.name, build.id)
    with memcache_lock(lock_id, self.app.oid) as acquired:
        if acquired:
            for mirror in mirrors:
                # Check if a previous run has already completed a backup
                if mirror in build.mirrored_on.all():
                    continue

                keydata = str.encode(mirror.ssh_host_fingerprint)
                key = paramiko.RSAKey(data=decodebytes(keydata))
                cnopts = pysftp.CnOpts()
                cnopts.hostkeys.add(mirror.hostname,
                                    mirror.ssh_host_fingerprint_type, key)

                with pysftp.Connection(
                        host=mirror.hostname,
                        username=mirror.ssh_username,
                        private_key='/home/shipper/ssh/{}'.format(
                            mirror.ssh_keyfile),
                        cnopts=cnopts) as sftp:
                    sftp.cwd(mirror.upload_path)

                    if not sftp.exists(build.device.codename):
                        sftp.mkdir(build.device.codename)

                    sftp.cwd(build.device.codename)

                    def print_progress(transferred, total):
                        print("{} transferred out of {} ({:.2f}%)".format(
                            humanize.naturalsize(transferred),
                            humanize.naturalsize(total),
                            transferred * 100 / total))

                    sftp.put(
                        os.path.join(settings.MEDIA_ROOT, build.zip_file.name),
                        callback=lambda x, y: print_progress(x, y),
                    )
                    sftp.put(
                        os.path.join(settings.MEDIA_ROOT, build.md5_file.name))

                # Fetch build one more time and lock until save completes
                with transaction.atomic():
                    build = Build.objects.select_for_update().get(id=build_id)
                    build.mirrored_on.add(mirror)
                    build.save()
        else:
            print(
                "Build {} is already being backed up by another process, exiting!"
                .format(build.file_name))
コード例 #9
0
ファイル: test_hostkeys.py プロジェクト: eysteinn13/paramiko
 def test_clear(self):
     hostdict = paramiko.HostKeys()
     hh = '|1|BMsIC6cUIP2zBuXR3t2LRcJYjzM=|hpkJMysjTk/+zzUUzxQEa2ieq6c='
     key = paramiko.RSAKey(data=decodebytes(keyblob))
     hostdict.add(hh, 'ssh-rsa', key)
     self.assertEqual(1, len(list(hostdict)))
     hostdict.clear()
     self.assertEqual(0, len(list(hostdict)))
コード例 #10
0
ファイル: hostkeys.py プロジェクト: EdgeKing810/paramiko
    def from_line(cls, line, lineno=None):
        """
        Parses the given line of text to find the names for the host,
        the type of key, and the key data. The line is expected to be in the
        format used by the OpenSSH known_hosts file.

        Lines are expected to not have leading or trailing whitespace.
        We don't bother to check for comments or empty lines.  All of
        that should be taken care of before sending the line to us.

        :param str line: a line from an OpenSSH known_hosts file
        """
        log = get_logger("paramiko.hostkeys")
        fields = line.split(" ")
        if len(fields) < 3:
            # Bad number of fields
            msg = "Not enough fields found in known_hosts in line {} ({!r})"
            log.info(msg.format(lineno, line))
            return None
        fields = fields[:3]

        names, keytype, key = fields
        names = names.split(",")

        # Decide what kind of key we're looking at and create an object
        # to hold it accordingly.
        try:
            key = b(key)
            if keytype == "ssh-rsa":
                key = RSAKey(data=decodebytes(key))
            elif keytype == "ssh-dss":
                key = DSSKey(data=decodebytes(key))
            elif keytype in ECDSAKey.supported_key_format_identifiers():
                key = ECDSAKey(data=decodebytes(key), validate_point=False)
            elif keytype == "ssh-ed25519":
                key = Ed25519Key(data=decodebytes(key))
            elif keytype == "ssh-xmss":
                key = XMSS(data=decodebytes(key))
            else:
                log.info("Unable to handle key of type {}".format(keytype))
                return None

        except binascii.Error as e:
            raise InvalidHostKey(line, e)

        return cls(names, key)
コード例 #11
0
    def test_dict_set(self):
        hostdict = paramiko.HostKeys("hostfile.temp")
        key = paramiko.RSAKey(data=decodebytes(keyblob))
        key_dss = paramiko.DSSKey(data=decodebytes(keyblob_dss))
        hostdict["secure.example.com"] = {"ssh-rsa": key, "ssh-dss": key_dss}
        hostdict["fake.example.com"] = {}
        hostdict["fake.example.com"]["ssh-rsa"] = key

        self.assertEqual(3, len(hostdict))
        self.assertEqual(2, len(list(hostdict.values())[0]))
        self.assertEqual(1, len(list(hostdict.values())[1]))
        self.assertEqual(1, len(list(hostdict.values())[2]))
        fp = hexlify(hostdict["secure.example.com"]
                     ["ssh-rsa"].get_fingerprint()).upper()
        self.assertEqual(b"7EC91BB336CB6D810B124B1353C32396", fp)
        fp = hexlify(hostdict["secure.example.com"]
                     ["ssh-dss"].get_fingerprint()).upper()
        self.assertEqual(b"4478F0B9A23CC5182009FF755BC1D26C", fp)
コード例 #12
0
ファイル: pkey.py プロジェクト: YiJie0430/AM_HIVE_TCP
 def _read_private_key(self, tag, f, password=None):
     lines = f.readlines()
     start = 0
     beginning_of_key = "-----BEGIN " + tag + " PRIVATE KEY-----"
     while start < len(lines) and lines[start].strip() != beginning_of_key:
         start += 1
     if start >= len(lines):
         raise SSHException("not a valid " + tag + " private key file")
     # parse any headers first
     headers = {}
     start += 1
     while start < len(lines):
         l = lines[start].split(": ")
         if len(l) == 1:
             break
         headers[l[0].lower()] = l[1].strip()
         start += 1
     # find end
     end = start
     ending_of_key = "-----END " + tag + " PRIVATE KEY-----"
     while end < len(lines) and lines[end].strip() != ending_of_key:
         end += 1
     # if we trudged to the end of the file, just try to cope.
     try:
         data = decodebytes(b("".join(lines[start:end])))
     except base64.binascii.Error as e:
         raise SSHException("base64 decoding error: " + str(e))
     if "proc-type" not in headers:
         # unencryped: done
         return data
     # encrypted keyfile: will need a password
     proc_type = headers["proc-type"]
     if proc_type != "4,ENCRYPTED":
         raise SSHException(
             'Unknown private key structure "{}"'.format(proc_type)
         )
     try:
         encryption_type, saltstr = headers["dek-info"].split(",")
     except:
         raise SSHException("Can't parse DEK-info in private key file")
     if encryption_type not in self._CIPHER_TABLE:
         raise SSHException(
             'Unknown private key cipher "{}"'.format(encryption_type)
         )
     # if no password was passed in,
     # raise an exception pointing out that we need one
     if password is None:
         raise PasswordRequiredException("Private key file is encrypted")
     cipher = self._CIPHER_TABLE[encryption_type]["cipher"]
     keysize = self._CIPHER_TABLE[encryption_type]["keysize"]
     mode = self._CIPHER_TABLE[encryption_type]["mode"]
     salt = unhexlify(b(saltstr))
     key = util.generate_key_bytes(md5, salt, password, keysize)
     decryptor = Cipher(
         cipher(key), mode(salt), backend=default_backend()
     ).decryptor()
     return decryptor.update(data) + decryptor.finalize()
コード例 #13
0
ファイル: test_hostkeys.py プロジェクト: intgr/paramiko
    def test_dict_set(self):
        hostdict = paramiko.HostKeys('hostfile.temp')
        key = paramiko.RSAKey(data=decodebytes(keyblob))
        key_dss = paramiko.DSSKey(data=decodebytes(keyblob_dss))
        hostdict['secure.example.com'] = {'ssh-rsa': key, 'ssh-dss': key_dss}
        hostdict['fake.example.com'] = {}
        hostdict['fake.example.com']['ssh-rsa'] = key

        self.assertEqual(3, len(hostdict))
        self.assertEqual(2, len(list(hostdict.values())[0]))
        self.assertEqual(1, len(list(hostdict.values())[1]))
        self.assertEqual(1, len(list(hostdict.values())[2]))
        fp = hexlify(hostdict['secure.example.com']
                     ['ssh-rsa'].get_fingerprint()).upper()
        self.assertEqual(b'7EC91BB336CB6D810B124B1353C32396', fp)
        fp = hexlify(hostdict['secure.example.com']
                     ['ssh-dss'].get_fingerprint()).upper()
        self.assertEqual(b'4478F0B9A23CC5182009FF755BC1D26C', fp)
コード例 #14
0
ファイル: hostkeys.py プロジェクト: gaudenz/paramiko
    def from_line(cls, line, lineno=None):
        """
        Parses the given line of text to find the names for the host,
        the type of key, and the key data. The line is expected to be in the
        format used by the OpenSSH known_hosts file.

        Lines are expected to not have leading or trailing whitespace.
        We don't bother to check for comments or empty lines.  All of
        that should be taken care of before sending the line to us.

        :param str line: a line from an OpenSSH known_hosts file
        """
        log = get_logger("paramiko.hostkeys")
        fields = line.split(" ")
        if len(fields) < 3:
            # Bad number of fields
            msg = "Not enough fields found in known_hosts in line {} ({!r})"
            log.info(msg.format(lineno, line))
            return None
        fields = fields[:3]

        names, keytype, key = fields
        names = names.split(",")

        # Decide what kind of key we're looking at and create an object
        # to hold it accordingly.
        try:
            key = b(key)
            if keytype == "ssh-rsa":
                key = RSAKey(data=decodebytes(key))
            elif keytype == "ssh-dss":
                key = DSSKey(data=decodebytes(key))
            elif keytype in ECDSAKey.supported_key_format_identifiers():
                key = ECDSAKey(data=decodebytes(key), validate_point=False)
            elif keytype == "ssh-ed25519":
                key = Ed25519Key(data=decodebytes(key))
            else:
                log.info("Unable to handle key of type {}".format(keytype))
                return None

        except binascii.Error as e:
            raise InvalidHostKey(line, e)

        return cls(names, key)
コード例 #15
0
ファイル: server.py プロジェクト: rbran/ssh-relay
class Server(paramiko.ServerInterface):
    # 'data' is the output of base64.encodestring(str(key))
    # (using the "user_rsa_key" files)
    # TODO: use key provided by user
    data = (b'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp'
            b'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC'
            b'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT'
            b'UWT10hcuO4Ks8=')
    good_pub_key = paramiko.RSAKey(data=decodebytes(data))

    def __init__(self):
        self.command = b''
        self.username = ''
        self.password = ''
        self.term = "xterm-256color"
        self.width = 80
        self.height = 20
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        ok('Auth attempt with user:'******'Client request shell')
        self.event.set()
        return True

    def check_channel_pty_request(self, channel, term, width, height,
                                  pixelwidth, pixelheight, modes):
        ok('Client request pty')
        self.term = term
        self.width = width
        self.height = height
        return True
コード例 #16
0
ファイル: test_hostkeys.py プロジェクト: gaudenz/paramiko
 def test_2_add(self):
     hostdict = paramiko.HostKeys("hostfile.temp")
     hh = "|1|BMsIC6cUIP2zBuXR3t2LRcJYjzM=|hpkJMysjTk/+zzUUzxQEa2ieq6c="
     key = paramiko.RSAKey(data=decodebytes(keyblob))
     hostdict.add(hh, "ssh-rsa", key)
     self.assertEqual(3, len(list(hostdict)))
     x = hostdict["foo.example.com"]
     fp = hexlify(x["ssh-rsa"].get_fingerprint()).upper()
     self.assertEqual(b"7EC91BB336CB6D810B124B1353C32396", fp)
     self.assertTrue(hostdict.check("foo.example.com", key))
コード例 #17
0
 def test_add(self):
     hostdict = paramiko.HostKeys("hostfile.temp")
     hh = "|1|BMsIC6cUIP2zBuXR3t2LRcJYjzM=|hpkJMysjTk/+zzUUzxQEa2ieq6c="
     key = paramiko.RSAKey(data=decodebytes(keyblob))
     hostdict.add(hh, "ssh-rsa", key)
     self.assertEqual(3, len(list(hostdict)))
     x = hostdict["foo.example.com"]
     fp = hexlify(x["ssh-rsa"].get_fingerprint()).upper()
     self.assertEqual(b"7EC91BB336CB6D810B124B1353C32396", fp)
     self.assertTrue(hostdict.check("foo.example.com", key))
コード例 #18
0
ファイル: test_hostkeys.py プロジェクト: merlin852/paramiko-1
 def test_2_add(self):
     hostdict = paramiko.HostKeys('hostfile.temp')
     hh = '|1|BMsIC6cUIP2zBuXR3t2LRcJYjzM=|hpkJMysjTk/+zzUUzxQEa2ieq6c='
     key = paramiko.RSAKey(data=decodebytes(keyblob))
     hostdict.add(hh, 'ssh-rsa', key)
     self.assertEqual(3, len(list(hostdict)))
     x = hostdict['foo.example.com']
     fp = hexlify(x['ssh-rsa'].get_fingerprint()).upper()
     self.assertEqual(b'7EC91BB336CB6D810B124B1353C32396', fp)
     self.assertTrue(hostdict.check('foo.example.com', key))
コード例 #19
0
ファイル: test_hostkeys.py プロジェクト: DanLipsitt/paramiko
 def test_4_dict_set(self):
     hostdict = paramiko.HostKeys('hostfile.temp')
     key = paramiko.RSAKey(data=decodebytes(keyblob))
     key_dss = paramiko.DSSKey(data=decodebytes(keyblob_dss))
     hostdict['secure.example.com'] = {
         'ssh-rsa': key,
         'ssh-dss': key_dss
     }
     hostdict['fake.example.com'] = {}
     hostdict['fake.example.com']['ssh-rsa'] = key
     
     self.assertEqual(3, len(hostdict))
     self.assertEqual(2, len(list(hostdict.values())[0]))
     self.assertEqual(1, len(list(hostdict.values())[1]))
     self.assertEqual(1, len(list(hostdict.values())[2]))
     fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper()
     self.assertEqual(b'7EC91BB336CB6D810B124B1353C32396', fp)
     fp = hexlify(hostdict['secure.example.com']['ssh-dss'].get_fingerprint()).upper()
     self.assertEqual(b'4478F0B9A23CC5182009FF755BC1D26C', fp)
コード例 #20
0
ファイル: hostkeys.py プロジェクト: Defman21/KomodoEdit
    def from_line(cls, line, lineno=None):
        """
        Parses the given line of text to find the names for the host,
        the type of key, and the key data. The line is expected to be in the
        format used by the OpenSSH known_hosts file.

        Lines are expected to not have leading or trailing whitespace.
        We don't bother to check for comments or empty lines.  All of
        that should be taken care of before sending the line to us.

        :param str line: a line from an OpenSSH known_hosts file
        """
        log = get_logger('paramiko.hostkeys')
        fields = line.split(' ')
        if len(fields) < 3:
            # Bad number of fields
            log.info("Not enough fields found in known_hosts in line %s (%r)" %
                     (lineno, line))
            return None
        fields = fields[:3]

        names, keytype, key = fields
        names = names.split(',')

        # Decide what kind of key we're looking at and create an object
        # to hold it accordingly.
        try:
            key = b(key)
            if keytype == 'ssh-rsa':
                key = RSAKey(data=decodebytes(key))
            elif keytype == 'ssh-dss':
                key = DSSKey(data=decodebytes(key))
            elif keytype == 'ecdsa-sha2-nistp256':
                key = ECDSAKey(data=decodebytes(key), validate_point=False)
            else:
                log.info("Unable to handle key of type %s" % (keytype,))
                return None

        except binascii.Error as e:
            raise InvalidHostKey(line, e)

        return cls(names, key)
コード例 #21
0
    def from_line(cls, line, lineno=None):
        """
        Parses the given line of text to find the names for the host,
        the type of key, and the key data. The line is expected to be in the
        format used by the OpenSSH known_hosts file.

        Lines are expected to not have leading or trailing whitespace.
        We don't bother to check for comments or empty lines.  All of
        that should be taken care of before sending the line to us.

        :param str line: a line from an OpenSSH known_hosts file
        """
        log = get_logger('paramiko.hostkeys')
        fields = line.split(' ')
        if len(fields) < 3:
            # Bad number of fields
            log.info("Not enough fields found in known_hosts in line %s (%r)" %
                     (lineno, line))
            return None
        fields = fields[:3]

        names, keytype, key = fields
        names = names.split(',')

        # Decide what kind of key we're looking at and create an object
        # to hold it accordingly.
        try:
            key = b(key)
            if keytype == 'ssh-rsa':
                key = RSAKey(data=decodebytes(key))
            elif keytype == 'ssh-dss':
                key = DSSKey(data=decodebytes(key))
            elif keytype == 'ecdsa-sha2-nistp256':
                key = ECDSAKey(data=decodebytes(key), validate_point=False)
            else:
                log.info("Unable to handle key of type %s" % (keytype,))
                return None

        except binascii.Error as e:
            raise InvalidHostKey(line, e)

        return cls(names, key)
コード例 #22
0
ファイル: test_hostkeys.py プロジェクト: gaudenz/paramiko
    def test_4_dict_set(self):
        hostdict = paramiko.HostKeys("hostfile.temp")
        key = paramiko.RSAKey(data=decodebytes(keyblob))
        key_dss = paramiko.DSSKey(data=decodebytes(keyblob_dss))
        hostdict["secure.example.com"] = {"ssh-rsa": key, "ssh-dss": key_dss}
        hostdict["fake.example.com"] = {}
        hostdict["fake.example.com"]["ssh-rsa"] = key

        self.assertEqual(3, len(hostdict))
        self.assertEqual(2, len(list(hostdict.values())[0]))
        self.assertEqual(1, len(list(hostdict.values())[1]))
        self.assertEqual(1, len(list(hostdict.values())[2]))
        fp = hexlify(
            hostdict["secure.example.com"]["ssh-rsa"].get_fingerprint()
        ).upper()
        self.assertEqual(b"7EC91BB336CB6D810B124B1353C32396", fp)
        fp = hexlify(
            hostdict["secure.example.com"]["ssh-dss"].get_fingerprint()
        ).upper()
        self.assertEqual(b"4478F0B9A23CC5182009FF755BC1D26C", fp)
コード例 #23
0
ファイル: pkey.py プロジェクト: reaperhulk/paramiko
 def _read_private_key(self, tag, f, password=None):
     lines = f.readlines()
     start = 0
     beginning_of_key = '-----BEGIN ' + tag + ' PRIVATE KEY-----'
     while start < len(lines) and lines[start].strip() != beginning_of_key:
         start += 1
     if start >= len(lines):
         raise SSHException('not a valid ' + tag + ' private key file')
     # parse any headers first
     headers = {}
     start += 1
     while start < len(lines):
         l = lines[start].split(': ')
         if len(l) == 1:
             break
         headers[l[0].lower()] = l[1].strip()
         start += 1
     # find end
     end = start
     ending_of_key = '-----END ' + tag + ' PRIVATE KEY-----'
     while end < len(lines) and lines[end].strip() != ending_of_key:
         end += 1
     # if we trudged to the end of the file, just try to cope.
     try:
         data = decodebytes(b(''.join(lines[start:end])))
     except base64.binascii.Error as e:
         raise SSHException('base64 decoding error: ' + str(e))
     if 'proc-type' not in headers:
         # unencryped: done
         return data
     # encrypted keyfile: will need a password
     if headers['proc-type'] != '4,ENCRYPTED':
         raise SSHException(
             'Unknown private key structure "%s"' % headers['proc-type'])
     try:
         encryption_type, saltstr = headers['dek-info'].split(',')
     except:
         raise SSHException("Can't parse DEK-info in private key file")
     if encryption_type not in self._CIPHER_TABLE:
         raise SSHException(
             'Unknown private key cipher "%s"' % encryption_type)
     # if no password was passed in,
     # raise an exception pointing out that we need one
     if password is None:
         raise PasswordRequiredException('Private key file is encrypted')
     cipher = self._CIPHER_TABLE[encryption_type]['cipher']
     keysize = self._CIPHER_TABLE[encryption_type]['keysize']
     mode = self._CIPHER_TABLE[encryption_type]['mode']
     salt = unhexlify(b(saltstr))
     key = util.generate_key_bytes(md5, salt, password, keysize)
     decryptor = Cipher(
         cipher(key), mode(salt), backend=default_backend()
     ).decryptor()
     return decryptor.update(data) + decryptor.finalize()
コード例 #24
0
ファイル: pkey.py プロジェクト: reaperhulk/paramiko
 def _read_private_key(self, tag, f, password=None):
     lines = f.readlines()
     start = 0
     beginning_of_key = '-----BEGIN ' + tag + ' PRIVATE KEY-----'
     while start < len(lines) and lines[start].strip() != beginning_of_key:
         start += 1
     if start >= len(lines):
         raise SSHException('not a valid ' + tag + ' private key file')
     # parse any headers first
     headers = {}
     start += 1
     while start < len(lines):
         l = lines[start].split(': ')
         if len(l) == 1:
             break
         headers[l[0].lower()] = l[1].strip()
         start += 1
     # find end
     end = start
     ending_of_key = '-----END ' + tag + ' PRIVATE KEY-----'
     while end < len(lines) and lines[end].strip() != ending_of_key:
         end += 1
     # if we trudged to the end of the file, just try to cope.
     try:
         data = decodebytes(b(''.join(lines[start:end])))
     except base64.binascii.Error as e:
         raise SSHException('base64 decoding error: ' + str(e))
     if 'proc-type' not in headers:
         # unencryped: done
         return data
     # encrypted keyfile: will need a password
     if headers['proc-type'] != '4,ENCRYPTED':
         raise SSHException('Unknown private key structure "%s"' %
                            headers['proc-type'])
     try:
         encryption_type, saltstr = headers['dek-info'].split(',')
     except:
         raise SSHException("Can't parse DEK-info in private key file")
     if encryption_type not in self._CIPHER_TABLE:
         raise SSHException('Unknown private key cipher "%s"' %
                            encryption_type)
     # if no password was passed in,
     # raise an exception pointing out that we need one
     if password is None:
         raise PasswordRequiredException('Private key file is encrypted')
     cipher = self._CIPHER_TABLE[encryption_type]['cipher']
     keysize = self._CIPHER_TABLE[encryption_type]['keysize']
     mode = self._CIPHER_TABLE[encryption_type]['mode']
     salt = unhexlify(b(saltstr))
     key = util.generate_key_bytes(md5, salt, password, keysize)
     decryptor = Cipher(cipher(key), mode(salt),
                        backend=default_backend()).decryptor()
     return decryptor.update(data) + decryptor.finalize()
コード例 #25
0
class SimpleSSHServer (paramiko.ServerInterface):
    # 'data' is the output of base64.encodestring(str(key))
    # (using the "user_rsa_key" files)
    data = (b'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp'
            b'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC'
            b'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT'
            b'UWT10hcuO4Ks8=')
    good_pub_key = paramiko.RSAKey(data=decodebytes(data))

    def __init__(self, connector):
        self.event = threading.Event()
        self.connector = connector

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        self.username = username
        self.password = password
        return paramiko.AUTH_SUCCESSFUL

    def check_auth_publickey(self, username, key):
        self.username = username
        self.key = key
        return paramiko.AUTH_SUCCESSFUL
    
    def check_auth_gssapi_with_mic(self, username,
                                   gss_authenticated=paramiko.AUTH_FAILED,
                                   cc_file=None):
        return paramiko.AUTH_FAILED

    def check_auth_gssapi_keyex(self, username,
                                gss_authenticated=paramiko.AUTH_FAILED,
                                cc_file=None):
        return paramiko.AUTH_FAILED

    def enable_auth_gssapi(self):
        return False

    def get_allowed_auths(self, username):
        return 'password,publickey'

    def check_channel_shell_request(self, channel):
        self.event.set()
        return True

    def check_channel_pty_request(self, channel, term, width, height, pixelwidth,
                                  pixelheight, modes):
        return True
コード例 #26
0
    def __init__(self, authorized_keys_file):
        self.authorized_keys = {}

        try:
            with open(authorized_keys_file) as authorized_keys:
                for key_info in authorized_keys.readlines():
                    key_type, key_contents, key_user = key_info.split()
                    if key_type == "ssh-rsa":
                        user = key_user.lower()
                        self.authorized_keys[user] = paramiko.RSAKey(
                            data=decodebytes(key_contents))
        except IOError as e:
            logging.error(str(e))
            traceback.print_exc()
            sys.exit(1)
コード例 #27
0
 def check_auth_publickey(self, username, key):
     user = self.env['res.users'].search([('login', '=', username)])
     if not user:
         return AUTH_FAILED
     for line in (user.authorized_keys or '').split('\n'):
         if not line or line.startswith('#'):
             continue
         key_type, key_data = line.split(' ', 2)[:2]
         if key_type != 'ssh-rsa':
             self.logger.info('Ignoring key of unknown type for line %s',
                              line)
             continue
         if RSAKey(data=decodebytes(key_data)) == key:
             return AUTH_SUCCESSFUL
     return AUTH_FAILED
コード例 #28
0
ファイル: sshserver.py プロジェクト: tasmail/python-sshserver
    def add_key(self, data, user):
        """ Decode key, and make it paramiko RSA key
        Map key for given user.

        @param data Key as string
        @param user User to map the key for
        @returns True on success, False otherwise
        """
        try:
            key = paramiko.RSAKey(data=decodebytes(data))
            if user not in self.ssh_keys:
                self.ssh_keys[user] = []
            self.ssh_keys[user].append(key)

            return True
        except:
            return False
コード例 #29
0
ファイル: __init__.py プロジェクト: vault-the/pyrexecd
def get_authorized_keys(path):
    keys = []
    with open(path) as fp:
        for line in fp:
            flds = line.split(' ')
            if len(flds) < 2: continue
            if flds[0] == 'ssh-rsa':
                f = paramiko.RSAKey
            elif flds[0] == 'ssh-dss':
                f = paramiko.DSSKey
            elif flds[0].startswith('ecdsa-'):
                f = paramiko.ECDSAKey
            else:
                continue
            data = decodebytes(flds[1].encode('ascii'))
            keys.append(f(data=data))
    return keys
コード例 #30
0
ファイル: __init__.py プロジェクト: euske/pyrexecd
def get_authorized_keys(path):
    keys = []
    with open(path) as fp:
        for line in fp:
            flds = line.split(' ')
            if len(flds) < 2: continue
            if flds[0] == 'ssh-rsa':
                f = paramiko.RSAKey
            elif flds[0] == 'ssh-dss':
                f = paramiko.DSSKey
            elif flds[0].startswith('ecdsa-'):
                f = paramiko.ECDSAKey
            else:
                continue
            data = decodebytes(flds[1].encode('ascii'))
            keys.append(f(data=data))
    return keys
コード例 #31
0
 def _read_private_key_old_format(self, lines, end, password):
     start = 0
     # parse any headers first
     headers = {}
     start += 1
     while start < len(lines):
         l = lines[start].split(': ')
         if len(l) == 1:
             break
         headers[l[0].lower()] = l[1].strip()
         start += 1
     # if we trudged to the end of the file, just try to cope.
     try:
         data = decodebytes(b(''.join(lines[start:end])))
     except base64.binascii.Error as e:
         raise SSHException('base64 decoding error: ' + str(e))
     if 'proc-type' not in headers:
         # unencryped: done
         return data
     # encrypted keyfile: will need a password
     proc_type = headers['proc-type']
     if proc_type != '4,ENCRYPTED':
         raise SSHException(
             'Unknown private key structure "{}"'.format(proc_type))
     try:
         encryption_type, saltstr = headers['dek-info'].split(',')
     except:
         raise SSHException("Can't parse DEK-info in private key file")
     if encryption_type not in self._CIPHER_TABLE:
         raise SSHException(
             'Unknown private key cipher "{}"'.format(encryption_type))
     # if no password was passed in,
     # raise an exception pointing out that we need one
     if password is None:
         raise PasswordRequiredException('Private key file is encrypted')
     cipher = self._CIPHER_TABLE[encryption_type]['cipher']
     keysize = self._CIPHER_TABLE[encryption_type]['keysize']
     mode = self._CIPHER_TABLE[encryption_type]['mode']
     salt = unhexlify(b(saltstr))
     key = util.generate_key_bytes(md5, salt, password, keysize)
     decryptor = Cipher(cipher(key), mode(salt),
                        backend=default_backend()).decryptor()
     return decryptor.update(data) + decryptor.finalize()
コード例 #32
0
ファイル: hostkeys.py プロジェクト: Defman21/KomodoEdit
    def hash_host(hostname, salt=None):
        """
        Return a "hashed" form of the hostname, as used by OpenSSH when storing
        hashed hostnames in the known_hosts file.

        :param str hostname: the hostname to hash
        :param str salt: optional salt to use when hashing (must be 20 bytes long)
        :return: the hashed hostname as a `str`
        """
        if salt is None:
            salt = os.urandom(sha1().digest_size)
        else:
            if salt.startswith('|1|'):
                salt = salt.split('|')[2]
            salt = decodebytes(b(salt))
        assert len(salt) == sha1().digest_size
        hmac = HMAC(salt, b(hostname), sha1).digest()
        hostkey = '|1|%s|%s' % (u(encodebytes(salt)), u(encodebytes(hmac)))
        return hostkey.replace('\n', '')
コード例 #33
0
    def hash_host(hostname, salt=None):
        """
        Return a "hashed" form of the hostname, as used by OpenSSH when storing
        hashed hostnames in the known_hosts file.

        :param str hostname: the hostname to hash
        :param str salt: optional salt to use when hashing (must be 20 bytes long)
        :return: the hashed hostname as a `str`
        """
        if salt is None:
            salt = os.urandom(sha1().digest_size)
        else:
            if salt.startswith('|1|'):
                salt = salt.split('|')[2]
            salt = decodebytes(b(salt))
        assert len(salt) == sha1().digest_size
        hmac = HMAC(salt, b(hostname), sha1).digest()
        hostkey = '|1|%s|%s' % (u(encodebytes(salt)), u(encodebytes(hmac)))
        return hostkey.replace('\n', '')
コード例 #34
0
    def _parse_openssh_pkey(cls, key_str):
        """Common parsing logic for PEM-like OpenSSH private key formats.

        Parse SSH2-format private string, looking for line containing the marker
        ``"BEGIN xxx PRIVATE KEY"`` for some ``xxx``, base64-decode the text we
        find, and return it along with some metadata. For ``FORMAT_ORIGINAL``
        keys, encryption headers are also parsed and returned as dict.

        :return: Four-tuple with the following fields:

            * pkformat: ``FORMAT_ORIGINAL`` or ``FORMAT_OPENSSH``.
            * type: string containing the type from BEGIN tag (e.g. ``RSA``).
            * headers: encryption headers if it's a FORMAT_ORIGINAL key,
              otherwise an empty ``dict``.
            * data: base64-decoded data from the key body.
        """
        match = cls._OPENSSH_KEY_RE.search(key_str)
        if not match:
            raise SSHException("not a valid private key file")

        typ, header_str, body = match.groups()

        headers = {}
        if typ == "OPENSSH":
            if header_str:
                raise SSHException(
                    "OPENSSH-format key should not contain headers")
            pkformat = cls.FORMAT_OPENSSH
        else:
            pkformat = cls.FORMAT_ORIGINAL
            if header_str:
                for line in header_str.splitlines():
                    key, value = line.split(": ", 1)
                    headers[key.lower()] = value.strip()

        try:
            data = decodebytes(b(body))
        except base64.binascii.Error as e:
            raise SSHException("base64 decoding error: " + str(e))

        return pkformat, typ, headers, data
コード例 #35
0
ファイル: demo_server.py プロジェクト: mozilla/ssh_mitm_poc
class Server(paramiko.ServerInterface):
    # 'data' is the output of base64.b64encode(key)
    # (using the "user_rsa_key" files)
    data = (
        b'AAAAB3NzaC1yc2EAAAADAQABAAACAQDQzL0E/aSxNtAhx6Jsn5Q9hkTiPnFWxo+gbf9YlPTzc9BxqH/ovatWkWXRhrI+bbMVwVVGJF/wvr0PAZ2HJhrTa6EteL/eyzdO5c4s+cW4jlmfmtb826ylKKVR056S5DfSiWqAcU7qg9m2FNnC6Uaerje3lWkB/MhpP6/+6/s2ytnfYu7EGIRz1FLGO+9V+OB3ep3mwUHTFrvji9zSWs5ssOpaxAi6KLCBgKvHsuOQ00KezRJORv7xTPmFnZOk4QISqGmWLPo0KThNCfPCHS7rTMehvywHOuSOVrGDik7xWTS6i6b5KOIJIn0JTMa+RXn+qcgBsMWZRxwJcLDN2fVK7n7bLQYWhSH/4lQpEcbnMVDFI76dUpXt3YMGZ+M8wZ9Tg4xmmABmws1bF8asfUwBvKvrhGJmBSBIQBAbzOT+NM3jEmgmkYUGJofFAimI9OsPp0CO0mc9vz2gw8/b1JAfVt//ZandX4bG0GBSWFMz0QUREOwV2fnJah7MfpG7D5IiiSE33W580Osw3vF9AAh3yjCN/ZIjpkA7SifGiEhL0bCXrCq4UPuOW1/gjed4QiY/OK0EJO8ZS5nKhpis74H3evZePQPX/p/Ju0h9QEFv80MvqI/J0QWuF4jBUYEuXZFPEJdE4t71F/eY2wsI9vwxRxmSzPtYCFOnpx19gV3wVw=='
    )
    good_pub_key = paramiko.RSAKey(data=decodebytes(data))

    def __init__(self, transport):
        self.event = threading.Event()
        self.transport = transport

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        print("client provided password {}".format(password))
        if (username == 'kang') and (password == 'testfoo'):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def check_auth_publickey(self, username, key):
        print('Auth attempt with key: ' + u(hexlify(key.get_fingerprint())))
        print('At auth time, session id was ', self.transport.session_id)
        if (username == 'kang') and (key == self.good_pub_key):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def get_allowed_auths(self, username):
        return 'password,publickey'

    def check_channel_shell_request(self, channel):
        self.event.set()
        return True

    def check_channel_pty_request(self, channel, term, width, height,
                                  pixelwidth, pixelheight, modes):
        return True
コード例 #36
0
ファイル: server.py プロジェクト: tc414103685/webterminal
class Server(paramiko.ServerInterface):
    # 'data' is the output of base64.b64encode(key)
    # (using the "user_rsa_key" files)
    data = (b"AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp"
            b"fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC"
            b"KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT"
            b"UWT10hcuO4Ks8=")
    good_pub_key = paramiko.RSAKey(data=decodebytes(data))
    channel = None
    serverid = None
    request_http_username = None
    channelid = None
    chanwidth = None
    chanheight = None

    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == "session":
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        conn = get_redis_instance()

        encrypt = PyCrypt('88aaaf7ffe3c6c0488aaaf7ffe3c6c04')
        if password == '' or password == u'':
            return paramiko.AUTH_FAILED
        try:
            key = encrypt.encrypt(content=username + encrypt.decrypt(password))
            key = encrypt.md5_crypt(key)
        except:
            conn.delete(username)
            return paramiko.AUTH_FAILED

        serverid = conn.get(key)
        if serverid is None:
            conn.delete(username)
            conn.delete(key)
            return paramiko.AUTH_FAILED
        else:
            try:
                if isinstance(serverid, bytes):
                    serverid = serverid.decode('utf8', 'ignore')
                serverid, request_username = serverid.rsplit('_')
                serverid = encrypt.decrypt(serverid)
                request_username = encrypt.decrypt(request_username)
                self.request_http_username = request_username
                try:
                    User.objects.get(username=request_username)
                except ObjectDoesNotExist:
                    print('request user name not exist')
                    conn.delete(username)
                    conn.delete(key)
                    return paramiko.AUTH_FAILED
            except:
                print('user {0} auth failed'.format(username))
                conn.delete(username)
                conn.delete(key)
                return paramiko.AUTH_FAILED

        try:
            ServerInfor.objects.get(id=serverid)
            self.serverid = int(serverid)
        except ObjectDoesNotExist:
            conn.delete(username)
            conn.delete(key)
            return paramiko.AUTH_FAILED

        if isinstance(conn.get(username), bytes) and isinstance(password, str):
            password = password.encode('utf8', 'ignore')

        try:
            if conn.get(username) is not None and password == conn.get(
                    username) and serverid != None:
                print('success connect to webterminal server')
                conn.delete(username)
                conn.delete(key)
                return paramiko.AUTH_SUCCESSFUL
        except:
            conn.delete(username)
            conn.delete(key)
            return paramiko.AUTH_FAILED
        conn.delete(username)
        conn.delete(key)
        return paramiko.AUTH_FAILED

    def check_auth_publickey(self, username, key):
        print("Auth attempt with key: " + u(hexlify(key.get_fingerprint())))
        # print (username, u(hexlify(key.get_fingerprint())
        # ), u(hexlify(self.good_pub_key.get_fingerprint())))
        if (username == "robey") and (key == self.good_pub_key):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def check_auth_gssapi_with_mic(self,
                                   username,
                                   gss_authenticated=paramiko.AUTH_FAILED,
                                   cc_file=None):
        """
        .. note::
            We are just checking in `AuthHandler` that the given user is a
            valid krb5 principal! We don't check if the krb5 principal is
            allowed to log in on the server, because there is no way to do that
            in python. So if you develop your own SSH server with paramiko for
            a certain platform like Linux, you should call ``krb5_kuserok()`` in
            your local kerberos library to make sure that the krb5_principal
            has an account on the server and is allowed to log in as a user.
        .. seealso::
            `krb5_kuserok() man page
            <http://www.unix.com/man-page/all/3/krb5_kuserok/>`_
        """
        if gss_authenticated == paramiko.AUTH_SUCCESSFUL:
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def check_auth_gssapi_keyex(self,
                                username,
                                gss_authenticated=paramiko.AUTH_FAILED,
                                cc_file=None):
        if gss_authenticated == paramiko.AUTH_SUCCESSFUL:
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def enable_auth_gssapi(self):
        return False

    def get_allowed_auths(self, username):
        return "gssapi-keyex,gssapi-with-mic,password,publickey"

    def check_channel_shell_request(self, channel):
        self.event.set()
        return True

    def check_channel_pty_request(self, channel, term, width, height,
                                  pixelwidth, pixelheight, modes):
        self.chanheight = height
        self.chanwidth = width
        return True

    def get_banner(self):
        return ('Webterminal ', 'version 1.0')

    def check_channel_window_change_request(self, channel, width, height,
                                            pixelwidth, pixelheight):
        print("Change window size to {0}*{1})".format(width, height))
        if self.channel is not None:
            self.channel.resize_pty(width=width, height=height)
        return True
コード例 #37
0
ファイル: fake_ssh_server.py プロジェクト: nrmay/mydata
 def __init__(self):
     self.command = None
     keyPair = OpenSSH.FindKeyPair("MyData")
     # Remove "ssh-rsa " and "MyData key":
     data = bytes(keyPair.GetPublicKey().split(" ")[1])
     self.mydata_pub_key = paramiko.RSAKey(data=decodebytes(data))
コード例 #38
0
ファイル: demo_server.py プロジェクト: ploxiln/paramiko-ng
class Server(paramiko.ServerInterface):
    # 'data' is the output of base64.b64encode(key)
    # (using the "user_rsa_key" files)
    data = (b'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp'
            b'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC'
            b'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT'
            b'UWT10hcuO4Ks8=')
    good_pub_key = paramiko.RSAKey(data=decodebytes(data))

    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        if (username == 'robey') and (password == 'foo'):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def check_auth_publickey(self, username, key):
        print("Auth attempt with key: " + key.get_fingerprint_sha256_b64())
        if (username == 'robey') and (key == self.good_pub_key):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def check_auth_gssapi_with_mic(self,
                                   username,
                                   gss_authenticated=paramiko.AUTH_FAILED,
                                   cc_file=None):
        """
        .. note::
            We are just checking in `AuthHandler` that the given user is a
            valid krb5 principal! We don't check if the krb5 principal is
            allowed to log in on the server, because there is no way to do that
            in python. So if you develop your own SSH server with paramiko for
            a certain platform like Linux, you should call ``krb5_kuserok()`` in
            your local kerberos library to make sure that the krb5_principal
            has an account on the server and is allowed to log in as a user.

        .. seealso::
            `krb5_kuserok() man page
            <http://www.unix.com/man-page/all/3/krb5_kuserok/>`_
        """
        if gss_authenticated == paramiko.AUTH_SUCCESSFUL:
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def check_auth_gssapi_keyex(self,
                                username,
                                gss_authenticated=paramiko.AUTH_FAILED,
                                cc_file=None):
        if gss_authenticated == paramiko.AUTH_SUCCESSFUL:
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def enable_auth_gssapi(self):
        return True

    def get_allowed_auths(self, username):
        return 'gssapi-keyex,gssapi-with-mic,password,publickey'

    def check_channel_shell_request(self, channel):
        self.event.set()
        return True

    def check_channel_pty_request(self, channel, term, width, height,
                                  pixelwidth, pixelheight, modes):
        return True
コード例 #39
0
    def _read_private_key_openssh(self, lines, password):
        """
        Read the new OpenSSH SSH2 private key format available
        since OpenSSH version 6.5
        Reference:
        https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key
        """
        try:
            data = decodebytes(b("".join(lines)))
        except base64.binascii.Error as e:
            raise SSHException("base64 decoding error: {}".format(e))

        # read data struct
        auth_magic = data[:15]
        if auth_magic != OPENSSH_AUTH_MAGIC:
            raise SSHException("unexpected OpenSSH key header encountered")

        cstruct = self._uint32_cstruct_unpack(data[15:], "sssur")
        cipher, kdfname, kdf_options, num_pubkeys, remainder = cstruct
        # For now, just support 1 key.
        if num_pubkeys > 1:
            raise SSHException(
                "unsupported: private keyfile has multiple keys")
        pubkey, privkey_blob = self._uint32_cstruct_unpack(remainder, "ss")

        if kdfname == b("bcrypt"):
            if cipher == b("aes256-cbc"):
                mode = modes.CBC
            elif cipher == b("aes256-ctr"):
                mode = modes.CTR
            else:
                raise SSHException(
                    "unknown cipher `{}` used in private key file".format(
                        cipher.decode("utf-8")))
            # Encrypted private key.
            # If no password was passed in, raise an exception pointing
            # out that we need one
            if password is None:
                raise PasswordRequiredException(
                    "private key file is encrypted")

            # Unpack salt and rounds from kdfoptions
            salt, rounds = self._uint32_cstruct_unpack(kdf_options, "su")

            # run bcrypt kdf to derive key and iv/nonce (32 + 16 bytes)
            key_iv = bcrypt.kdf(
                b(password),
                b(salt),
                48,
                rounds,
                # We can't control how many rounds are on disk, so no sense
                # warning about it.
                ignore_few_rounds=True,
            )
            key = key_iv[:32]
            iv = key_iv[32:]

            # decrypt private key blob
            decryptor = Cipher(algorithms.AES(key), mode(iv),
                               default_backend()).decryptor()
            decrypted_privkey = decryptor.update(privkey_blob)
            decrypted_privkey += decryptor.finalize()
        elif cipher == b("none") and kdfname == b("none"):
            # Unencrypted private key
            decrypted_privkey = privkey_blob
        else:
            raise SSHException(
                "unknown cipher or kdf used in private key file")

        # Unpack private key and verify checkints
        cstruct = self._uint32_cstruct_unpack(decrypted_privkey, "uusr")
        checkint1, checkint2, keytype, keydata = cstruct

        if checkint1 != checkint2:
            raise SSHException(
                "OpenSSH private key file checkints do not match")

        return _unpad_openssh(keydata)
コード例 #40
0
 def __init__(self):
     self.command = None
     keyPair = OpenSSH.FindKeyPair("MyDataTest")
     # Remove "ssh-rsa " and "MyDataTest key":
     data = bytes(keyPair.GetPublicKey().split(" ")[1])
     self.mydata_pub_key = paramiko.RSAKey(data=decodebytes(data))