Ejemplo n.º 1
0
    def test_savingsPreservesExisting(self):
        """
        L{KnownHostsFile.save} will not overwrite existing entries in its save
        path, even if they were only added after the L{KnownHostsFile} instance
        was initialized.
        """
        # Start off with one host/key pair in the file
        path = self.pathWithContent(sampleHashedLine)
        knownHosts = KnownHostsFile.fromPath(path)

        # After initializing the KnownHostsFile instance, add a second host/key
        # pair to the file directly - without the instance's help or knowledge.
        with path.open("a") as hostsFileObj:
            hostsFileObj.write(otherSamplePlaintextLine)

        # Add a third host/key pair using the KnownHostsFile instance
        key = Key.fromString(thirdSampleKey)
        knownHosts.addHostKey("brandnew.example.com", key)
        knownHosts.save()

        # Check that all three host/key pairs are present.
        knownHosts = KnownHostsFile.fromPath(path)
        self.assertEqual([True, True, True], [
            knownHosts.hasHostKey("www.twistedmatrix.com",
                                  Key.fromString(sampleKey)),
            knownHosts.hasHostKey("divmod.com",
                                  Key.fromString(otherSampleKey)),
            knownHosts.hasHostKey("brandnew.example.com", key)
        ])
Ejemplo n.º 2
0
    def test_savingsPreservesExisting(self):
        """
        L{KnownHostsFile.save} will not overwrite existing entries in its save
        path, even if they were only added after the L{KnownHostsFile} instance
        was initialized.
        """
        # Start off with one host/key pair in the file
        path = self.pathWithContent(sampleHashedLine)
        knownHosts = KnownHostsFile.fromPath(path)

        # After initializing the KnownHostsFile instance, add a second host/key
        # pair to the file directly - without the instance's help or knowledge.
        with path.open("a") as hostsFileObj:
            hostsFileObj.write(otherSamplePlaintextLine)

        # Add a third host/key pair using the KnownHostsFile instance
        key = Key.fromString(thirdSampleKey)
        knownHosts.addHostKey("brandnew.example.com", key)
        knownHosts.save()

        # Check that all three host/key pairs are present.
        knownHosts = KnownHostsFile.fromPath(path)
        self.assertEqual([True, True, True], [
                knownHosts.hasHostKey(
                    "www.twistedmatrix.com", Key.fromString(sampleKey)),
                knownHosts.hasHostKey(
                    "divmod.com", Key.fromString(otherSampleKey)),
                knownHosts.hasHostKey("brandnew.example.com", key)])
Ejemplo n.º 3
0
    def fromConfig(cls, reactor):
        keys = []
        if "identity" in _CONFIG:
            keyPath = os.path.expanduser(_CONFIG["identity"])
            if os.path.exists(keyPath):
                keys.append(readKey(keyPath))

        knownHostsPath = FilePath(os.path.expanduser(_CONFIG["knownhosts"]))
        if knownHostsPath.exists():
            knownHosts = KnownHostsFile.fromPath(knownHostsPath)
        else:
            knownHosts = None

        if "no-agent" in _CONFIG or "SSH_AUTH_SOCK" not in os.environ:
            agentEndpoint = None
        else:
            agentEndpoint = UNIXClientEndpoint(
                reactor, os.environ["SSH_AUTH_SOCK"])

        if "password" in _CONFIG:
            password = _CONFIG["password"]
        else:
            password = None

        return cls(
            reactor, _CONFIG["host"], _CONFIG["port"],
            _CONFIG["username"], password, keys,
            knownHosts, agentEndpoint)
    def fromCommandLine(cls, reactor, argv):
        config = EchoOptions()
        config.parseOptions(argv)

        keys = []
        if config["identity"]:
            keyPath = os.path.expanduser(config["identity"])
            if os.path.exists(keyPath):
                keys.append(readKey(keyPath))

        knownHostsPath = FilePath(os.path.expanduser(config["knownhosts"]))
        if knownHostsPath.exists():
            knownHosts = KnownHostsFile.fromPath(knownHostsPath)
        else:
            knownHosts = None

        if config["no-agent"] or "SSH_AUTH_SOCK" not in os.environ:
            agentEndpoint = None
        else:
            agentEndpoint = UNIXClientEndpoint(
                reactor, os.environ["SSH_AUTH_SOCK"])

        return cls(
            reactor, config["host"], config["port"],
            config["username"], config["password"], keys,
            knownHosts, agentEndpoint)
Ejemplo n.º 5
0
    def __init__(self, *args, **kw):
        channel.CowrieSSHChannel.__init__(self, *args, **kw)

        keyPath = CONFIG.get('proxy', 'private_key')
        self.keys.append(keys.Key.fromFile(keyPath))

        try:
            keyPath = CONFIG.get('proxy', 'private_key')
            self.keys.append(keys.Key.fromFile(keyPath))
        except NoOptionError:
            self.keys = None

        knownHostsPath = CONFIG.get('proxy', 'known_hosts')
        self.knownHosts = KnownHostsFile.fromPath(knownHostsPath)

        self.host = CONFIG.get('proxy', 'host')
        self.port = CONFIG.getint('proxy', 'port')
        self.user = CONFIG.get('proxy', 'user')
        try:
            self.password = CONFIG.get('proxy', 'password')
        except NoOptionError:
            self.password = None

        log.msg("knownHosts = {0}".format(repr(self.knownHosts)))
        log.msg("host = {0}".format(self.host))
        log.msg("port = {0}".format(self.port))
        log.msg("user = {0}".format(self.user))

        self.client = ProxyClient(self)
Ejemplo n.º 6
0
def get_known_hosts():
    knownHostsPath = FilePath(os.path.expanduser("~/.ssh/known_hosts"))
    if knownHostsPath.exists():
        knownHosts = KnownHostsFile.fromPath(knownHostsPath)
    else:
        knownHosts = None
    return knownHosts
Ejemplo n.º 7
0
    def __init__(self, *args, **kw):
        channel.CowrieSSHChannel.__init__(self, *args, **kw)
        #self.__dict__['*****@*****.**'] = self.request_agent

        try:
            keyPath = CONFIG.get('proxy', 'private_key')
            self.keys.append(keys.Key.fromFile(keyPath))
        except:
            self.keys = None

        knownHostsPath = CONFIG.get('proxy', 'known_hosts')
        self.knownHosts = KnownHostsFile.fromPath(knownHostsPath)
        log.msg("knownHosts = " + repr(self.knownHosts))

        self.host = CONFIG.get('proxy', 'host')
        self.port = CONFIG.getint('proxy', 'port')
        self.user = CONFIG.get('proxy', 'user')
        try:
            self.password = CONFIG.get('proxy', 'password')
        except:
            self.password = None

        log.msg("host = " + self.host)
        log.msg("port = " + str(self.port))
        log.msg("user = " + self.user)

        self.client = ProxyClient(self)
Ejemplo n.º 8
0
 def _knownHosts(cls):
     """
     @return: A L{KnownHostsFile} instance pointed at the user's personal
         I{known hosts} file.
     @type: L{KnownHostsFile}
     """
     return KnownHostsFile.fromPath(FilePath(expanduser(cls._KNOWN_HOSTS)))
Ejemplo n.º 9
0
    def fromConfig(cls, reactor):
        keys = []
        if "identity" in _CONFIG:
            keyPath = os.path.expanduser(_CONFIG["identity"])
            if os.path.exists(keyPath):
                keys.append(readKey(keyPath))

        knownHostsPath = FilePath(os.path.expanduser(_CONFIG["knownhosts"]))
        if knownHostsPath.exists():
            knownHosts = KnownHostsFile.fromPath(knownHostsPath)
        else:
            knownHosts = None

        if "no-agent" in _CONFIG or "SSH_AUTH_SOCK" not in os.environ:
            agentEndpoint = None
        else:
            agentEndpoint = UNIXClientEndpoint(reactor,
                                               os.environ["SSH_AUTH_SOCK"])

        if "password" in _CONFIG:
            password = _CONFIG["password"]
        else:
            password = None

        return cls(reactor, _CONFIG["host"], _CONFIG["port"],
                   _CONFIG["username"], password, keys, knownHosts,
                   agentEndpoint)
Ejemplo n.º 10
0
def get_connection_helper(reactor, address, username, port):
    """
    Get a :class:`twisted.conch.endpoints._ISSHConnectionCreator` to connect to
    the given remote.

    :param reactor: Reactor to connect with.
    :param bytes address: The address of the remote host to connect to.
    :param bytes username: The user to connect as.
    :param int port: The port of the ssh server to connect to.

    :return _ISSHConnectionCreator:
    """
    try:
        agentEndpoint = UNIXClientEndpoint(reactor,
                                           os.environ["SSH_AUTH_SOCK"])
    except KeyError:
        agentEndpoint = None

    return _NewConnectionHelper(reactor,
                                address,
                                port,
                                None,
                                username,
                                keys=None,
                                password=None,
                                agentEndpoint=agentEndpoint,
                                knownHosts=KnownHostsFile.fromPath(
                                    FilePath("/dev/null")),
                                ui=ConsoleUI(lambda: _ReadFile(b"yes")))
Ejemplo n.º 11
0
 def get_known_hosts(self):
     knownHostsPath = FilePath(self.known_hosts)
     if knownHostsPath.exists():
         knownHosts = KnownHostsFile.fromPath(knownHostsPath)
     else:
         knownHosts = None
     return knownHosts
Ejemplo n.º 12
0
    def __init__(self, *args, **kw):
        channel.CowrieSSHChannel.__init__(self, *args, **kw)

        keyPath = CONFIG.get('proxy', 'private_key')
        self.keys.append(keys.Key.fromFile(keyPath))

        try:
            keyPath = CONFIG.get('proxy', 'private_key')
            self.keys.append(keys.Key.fromFile(keyPath))
        except NoOptionError:
            self.keys = None

        knownHostsPath = CONFIG.get('proxy', 'known_hosts')
        self.knownHosts = KnownHostsFile.fromPath(knownHostsPath)

        self.host = CONFIG.get('proxy', 'host')
        self.port = CONFIG.getint('proxy', 'port')
        self.user = CONFIG.get('proxy', 'user')
        try:
            self.password = CONFIG.get('proxy', 'password')
        except NoOptionError:
            self.password = None

        log.msg("knownHosts = {0}".format(repr(self.knownHosts)))
        log.msg("host = {0}".format(self.host))
        log.msg("port = {0}".format(self.port))
        log.msg("user = {0}".format(self.user))

        self.client = ProxyClient(self)
Ejemplo n.º 13
0
    def fromCommandLine(cls, reactor, argv):
        config = EchoOptions()
        config.parseOptions(argv)

        keys = []
        if config["identity"]:
            keyPath = os.path.expanduser(config["identity"])
            if os.path.exists(keyPath):
                keys.append(readKey(keyPath))

        knownHostsPath = FilePath(os.path.expanduser(config["knownhosts"]))
        if knownHostsPath.exists():
            knownHosts = KnownHostsFile.fromPath(knownHostsPath)
        else:
            knownHosts = None

        if config["no-agent"] or "SSH_AUTH_SOCK" not in os.environ:
            agentEndpoint = None
        else:
            agentEndpoint = UNIXClientEndpoint(reactor,
                                               os.environ["SSH_AUTH_SOCK"])

        return cls(
            reactor,
            config["host"],
            config["port"],
            config["username"],
            config["password"],
            keys,
            knownHosts,
            agentEndpoint,
        )
Ejemplo n.º 14
0
    def testSSH101(self):
        def finished():
            pass

        keypaths = [
            # '/data/dev/beholder/sys/ssh-keys/client_rsa.pub',
            '/data/dev/beholder/sys/ssh-keys/client_rsa'
        ]
        keys = []
        for keyPath in keypaths:
            if os.path.exists(keyPath):
                keys.append(readKey(keyPath))
        knownHostsPath = '/home/jan/.ssh/known_hosts'
        knownHosts = KnownHostsFile.fromPath(FilePath(knownHostsPath))
        # for entry in knownHosts.iterentries():
        #     if entry.matchesHost(b"[localhost]:2222"):
        #         print("yess!!!!!!!!!!!!!!!!!!!!!")
        #         print(entry)
        agentEndpoint = UNIXClientEndpoint(reactor,
                                           os.environ["SSH_AUTH_SOCK"])
        client = SSHCmdClient(b"localhost",
                              2222,
                              b"user",
                              keys=keys,
                              knownhosts=knownHosts,
                              agent=None)
        self.assertIsNotNone(client)
        endpoint = client.newConnection("ls")
        self.assertIsNotNone(endpoint)
        factory = Factory()
        factory.protocol = TestProtocol
        d = endpoint.connect(factory)
        d.addCallback(finished)
        return d
Ejemplo n.º 15
0
def get_connection_helper(reactor, address, username, port):
    """
    Get a :class:`twisted.conch.endpoints._ISSHConnectionCreator` to connect to
    the given remote.

    :param reactor: Reactor to connect with.
    :param bytes address: The address of the remote host to connect to.
    :param bytes username: The user to connect as.
    :param int port: The port of the ssh server to connect to.

    :return _ISSHConnectionCreator:
    """
    try:
        agentEndpoint = UNIXClientEndpoint(
            reactor, os.environ["SSH_AUTH_SOCK"])
    except KeyError:
        agentEndpoint = None

    return _NewConnectionHelper(
        reactor, address, port, None, username,
        keys=None,
        password=None,
        agentEndpoint=agentEndpoint,
        knownHosts=KnownHostsFile.fromPath(FilePath("/dev/null")),
        ui=ConsoleUI(lambda: _ReadFile(b"yes")))
Ejemplo n.º 16
0
 def __init__(self, factory):
     self.factory = factory
     self._state = b'STARTING'
     self.knownHosts = KnownHostsFile.fromPath(
         FilePath(os.path.expanduser('~/.ssh/known_hosts')))
     self._hostKeyFailure = None
     self._user_auth = None
     self._connection_lost_reason = None
Ejemplo n.º 17
0
 def verifyHostKey(transport, host, pubKey, fingerprint):
     log.msg("verifying host key")
     actualHost = transport.factory.options["host"]
     actualKey = keys.Key.fromString(pubKey)
     kh = KnownHostsFile.fromPath(
         FilePath(transport.factory.options["known-hosts"] or os.path.expanduser("~/.ssh/known_hosts"))
     )
     return kh.verifyHostKey(console, actualHost, host, actualKey).addErrback(log.err)
Ejemplo n.º 18
0
 def verifyHostKey(transport, host, pubKey, fingerprint):
     log.msg('verifying host key')
     actualHost = transport.factory.options['host']
     actualKey = keys.Key.fromString(pubKey)
     kh = KnownHostsFile.fromPath(
         FilePath(transport.factory.options['known-hosts']
                  or os.path.expanduser('~/.ssh/known_hosts')))
     return kh.verifyHostKey(console, actualHost, host,
                             actualKey).addErrback(log.err)
Ejemplo n.º 19
0
 def __init__(self, factory):
     self.factory = factory
     self._state = b'STARTING'
     self.knownHosts = KnownHostsFile.fromPath(
         FilePath(os.path.expanduser('~/.ssh/known_hosts'))
     )
     self._hostKeyFailure = None
     self._user_auth = None
     self._connection_lost_reason = None
Ejemplo n.º 20
0
 def loadSampleHostsFile(self, content=(
         sampleHashedLine + otherSamplePlaintextLine +
         "\n# That was a blank line.\n"
         "This is just unparseable.\n"
         "|1|This also unparseable.\n")):
     """
     Return a sample hosts file, with keys for www.twistedmatrix.com and
     divmod.com present.
     """
     return KnownHostsFile.fromPath(self.pathWithContent(content))
Ejemplo n.º 21
0
 def connectionMade(self):
     script_dir = os.getcwd()
     rel_path = "hostkeys"
     abs_file_path = os.path.join(script_dir, rel_path)
     knownHosts = KnownHostsFile.fromPath(abs_file_path)
     self.point = SSHCommandClientEndpoint.newConnection(reactor, 'cmd', 'user', '127.0.0.1', port=5122,
                                                         password='******', knownHosts=PermissiveKnownHosts())
     self.sshSide = FzSSHClient()
     self.sshSide.tcpSide = self
     connectProtocol(self.point, self.sshSide)
Ejemplo n.º 22
0
 def test_loadNonExistent(self):
     """
     Loading a L{KnownHostsFile} from a path that does not exist should
     result in an empty L{KnownHostsFile} that will save back to that path.
     """
     pn = self.mktemp()
     knownHostsFile = KnownHostsFile.fromPath(FilePath(pn))
     self.assertEqual([], list(knownHostsFile._entries))
     self.assertEqual(False, FilePath(pn).exists())
     knownHostsFile.save()
     self.assertEqual(True, FilePath(pn).exists())
Ejemplo n.º 23
0
 def test_loadNonExistent(self):
     """
     Loading a L{KnownHostsFile} from a path that does not exist should
     result in an empty L{KnownHostsFile} that will save back to that path.
     """
     pn = self.mktemp()
     knownHostsFile = KnownHostsFile.fromPath(FilePath(pn))
     self.assertEqual([], list(knownHostsFile._entries))
     self.assertEqual(False, FilePath(pn).exists())
     knownHostsFile.save()
     self.assertEqual(True, FilePath(pn).exists())
Ejemplo n.º 24
0
 def test_loadNonExistentParent(self):
     """
     Loading a L{KnownHostsFile} from a path whose parent directory does not
     exist should result in an empty L{KnownHostsFile} that will save back
     to that path, creating its parent directory(ies) in the process.
     """
     thePath = FilePath(self.mktemp())
     knownHostsPath = thePath.child("foo").child("known_hosts")
     knownHostsFile = KnownHostsFile.fromPath(knownHostsPath)
     knownHostsFile.save()
     knownHostsPath.restat(False)
     self.assertEqual(True, knownHostsPath.exists())
Ejemplo n.º 25
0
 def test_loadNonExistentParent(self):
     """
     Loading a L{KnownHostsFile} from a path whose parent directory does not
     exist should result in an empty L{KnownHostsFile} that will save back
     to that path, creating its parent directory(ies) in the process.
     """
     thePath = FilePath(self.mktemp())
     knownHostsPath = thePath.child("foo").child("known_hosts")
     knownHostsFile = KnownHostsFile.fromPath(knownHostsPath)
     knownHostsFile.save()
     knownHostsPath.restat(False)
     self.assertEqual(True, knownHostsPath.exists())
Ejemplo n.º 26
0
    def test_savingAvoidsDuplication(self):
        """
        L{KnownHostsFile.save} only writes new entries to the save path, not
        entries which were added and already written by a previous call to
        C{save}.
        """
        path = FilePath(self.mktemp())
        knownHosts = KnownHostsFile(path)
        entry = knownHosts.addHostKey(
            "some.example.com", Key.fromString(sampleKey))
        knownHosts.save()
        knownHosts.save()

        knownHosts = KnownHostsFile.fromPath(path)
        self.assertEqual([entry], list(knownHosts.iterentries()))
Ejemplo n.º 27
0
    def test_savingAvoidsDuplication(self):
        """
        L{KnownHostsFile.save} only writes new entries to the save path, not
        entries which were added and already written by a previous call to
        C{save}.
        """
        path = FilePath(self.mktemp())
        knownHosts = KnownHostsFile(path)
        entry = knownHosts.addHostKey("some.example.com",
                                      Key.fromString(sampleKey))
        knownHosts.save()
        knownHosts.save()

        knownHosts = KnownHostsFile.fromPath(path)
        self.assertEqual([entry], list(knownHosts.iterentries()))
Ejemplo n.º 28
0
def verifyHostKey(transport, host, pubKey, fingerprint):
    """
    Verify a host's key.

    This function is a gross vestige of some bad factoring in the client
    internals.  The actual implementation, and a better signature of this logic
    is in L{KnownHostsFile.verifyHostKey}.  This function is not deprecated yet
    because the callers have not yet been rehabilitated, but they should
    eventually be changed to call that method instead.

    However, this function does perform two functions not implemented by
    L{KnownHostsFile.verifyHostKey}.  It determines the path to the user's
    known_hosts file based on the options (which should really be the options
    object's job), and it provides an opener to L{ConsoleUI} which opens
    '/dev/tty' so that the user will be prompted on the tty of the process even
    if the input and output of the process has been redirected.  This latter
    part is, somewhat obviously, not portable, but I don't know of a portable
    equivalent that could be used.

    @param host: Due to a bug in L{SSHClientTransport.verifyHostKey}, this is
    always the dotted-quad IP address of the host being connected to.
    @type host: L{str}

    @param transport: the client transport which is attempting to connect to
    the given host.
    @type transport: L{SSHClientTransport}

    @param fingerprint: the fingerprint of the given public key, in
    xx:xx:xx:... format.  This is ignored in favor of getting the fingerprint
    from the key itself.
    @type fingerprint: L{str}

    @param pubKey: The public key of the server being connected to.
    @type pubKey: L{str}

    @return: a L{Deferred} which fires with C{1} if the key was successfully
    verified, or fails if the key could not be successfully verified.  Failure
    types may include L{HostKeyChanged}, L{UserRejectedKey}, L{IOError} or
    L{KeyboardInterrupt}.
    """
    actualHost = transport.factory.options['host']
    actualKey = keys.Key.fromString(pubKey)
    kh = KnownHostsFile.fromPath(FilePath(
            transport.factory.options['known-hosts']
            or os.path.expanduser(_KNOWN_HOSTS)
            ))
    ui = ConsoleUI(lambda : _open("/dev/tty", "r+b"))
    return kh.verifyHostKey(ui, actualHost, host, actualKey)
Ejemplo n.º 29
0
def verifyHostKey(transport, host, pubKey, fingerprint):
    """
    Verify a host's key.

    This function is a gross vestige of some bad factoring in the client
    internals.  The actual implementation, and a better signature of this logic
    is in L{KnownHostsFile.verifyHostKey}.  This function is not deprecated yet
    because the callers have not yet been rehabilitated, but they should
    eventually be changed to call that method instead.

    However, this function does perform two functions not implemented by
    L{KnownHostsFile.verifyHostKey}.  It determines the path to the user's
    known_hosts file based on the options (which should really be the options
    object's job), and it provides an opener to L{ConsoleUI} which opens
    '/dev/tty' so that the user will be prompted on the tty of the process even
    if the input and output of the process has been redirected.  This latter
    part is, somewhat obviously, not portable, but I don't know of a portable
    equivalent that could be used.

    @param host: Due to a bug in L{SSHClientTransport.verifyHostKey}, this is
    always the dotted-quad IP address of the host being connected to.
    @type host: L{str}

    @param transport: the client transport which is attempting to connect to
    the given host.
    @type transport: L{SSHClientTransport}

    @param fingerprint: the fingerprint of the given public key, in
    xx:xx:xx:... format.  This is ignored in favor of getting the fingerprint
    from the key itself.
    @type fingerprint: L{str}

    @param pubKey: The public key of the server being connected to.
    @type pubKey: L{str}

    @return: a L{Deferred} which fires with C{1} if the key was successfully
    verified, or fails if the key could not be successfully verified.  Failure
    types may include L{HostKeyChanged}, L{UserRejectedKey}, L{IOError} or
    L{KeyboardInterrupt}.
    """
    actualHost = transport.factory.options['host']
    actualKey = keys.Key.fromString(pubKey)
    kh = KnownHostsFile.fromPath(FilePath(
            transport.factory.options['known-hosts']
            or os.path.expanduser(_KNOWN_HOSTS)
            ))
    ui = ConsoleUI(lambda : _open("/dev/tty", "r+b", buffering=0))
    return kh.verifyHostKey(ui, actualHost, host, actualKey)
Ejemplo n.º 30
0
 def connectionMade(self):
     script_dir = os.getcwd()
     rel_path = "hostkeys"
     abs_file_path = os.path.join(script_dir, rel_path)
     knownHosts = KnownHostsFile.fromPath(abs_file_path)
     self.point = SSHCommandClientEndpoint.newConnection(
         reactor,
         'cmd',
         'user',
         '127.0.0.1',
         port=5122,
         password='******',
         knownHosts=PermissiveKnownHosts())
     self.sshSide = FzSSHClient()
     self.sshSide.tcpSide = self
     connectProtocol(self.point, self.sshSide)
Ejemplo n.º 31
0
 def test_verifyNonPresentKey_Yes(self):
     """
     Verifying a key where neither the hostname nor the IP are present
     should result in the UI being prompted with a message explaining as
     much.  If the UI says yes, the Deferred should fire with True.
     """
     ui, l, knownHostsFile = self.verifyNonPresentKey()
     ui.promptDeferred.callback(True)
     self.assertEqual([True], l)
     reloaded = KnownHostsFile.fromPath(knownHostsFile.savePath)
     self.assertEqual(
         True,
         reloaded.hasHostKey("4.3.2.1", Key.fromString(thirdSampleKey)))
     self.assertEqual(
         True,
         reloaded.hasHostKey("sample-host.example.com",
                             Key.fromString(thirdSampleKey)))
Ejemplo n.º 32
0
 def test_verifyNonPresentKey_Yes(self):
     """
     Verifying a key where neither the hostname nor the IP are present
     should result in the UI being prompted with a message explaining as
     much.  If the UI says yes, the Deferred should fire with True.
     """
     ui, l, knownHostsFile = self.verifyNonPresentKey()
     ui.promptDeferred.callback(True)
     self.assertEqual([True], l)
     reloaded = KnownHostsFile.fromPath(knownHostsFile._savePath)
     self.assertEqual(
         True, reloaded.hasHostKey("4.3.2.1",
                                   Key.fromString(thirdSampleKey)))
     self.assertEqual(
         True,
         reloaded.hasHostKey("sample-host.example.com",
                             Key.fromString(thirdSampleKey)))
Ejemplo n.º 33
0
 def test_verifyHostButNotIP(self):
     """
     L{default.verifyHostKey} should return a L{Deferred} which fires with
     C{1} when passed a host which matches with an IP is not present in its
     known_hosts file, and should also warn the user that it has added the
     IP address.
     """
     l = []
     default.verifyHostKey(self.fakeTransport, "8.7.6.5", sampleKey,
                           "Fingerprint not required.").addCallback(l.append)
     self.assertEqual(
         ["Warning: Permanently added the RSA host key for IP address "
         "'8.7.6.5' to the list of known hosts."],
         self.fakeFile.outchunks)
     self.assertEqual([1], l)
     knownHostsFile = KnownHostsFile.fromPath(FilePath(self.hostsOption))
     self.assertEqual(True, knownHostsFile.hasHostKey("8.7.6.5",
                                          Key.fromString(sampleKey)))
Ejemplo n.º 34
0
 def test_verifyKeyForHostAndIP(self):
     """
     Verifying a key where the hostname is present but the IP is not should
     result in the key being added for the IP and the user being warned
     about the change.
     """
     ui = FakeUI()
     hostsFile = self.loadSampleHostsFile()
     expectedKey = Key.fromString(sampleKey)
     hostsFile.verifyHostKey(
         ui, "www.twistedmatrix.com", "5.4.3.2", expectedKey)
     self.assertEqual(
         True, KnownHostsFile.fromPath(hostsFile.savePath).hasHostKey(
             "5.4.3.2", expectedKey))
     self.assertEqual(
         ["Warning: Permanently added the RSA host key for IP address "
          "'5.4.3.2' to the list of known hosts."],
         ui.userWarnings)
Ejemplo n.º 35
0
    def __init__(self, hostname, username, port, password=None,
                 knownhosts=None):

        self.hostname = hostname.encode()
        self.username = username.encode()
        self.port = int(port)
        self.password = None
        if password:
            self.password = password.encode()
        self.connection = None

        if not knownhosts:
            knownhosts = '/var/lib/tensor/known_hosts'

        self.knownHosts = KnownHostsFile.fromPath(FilePath(knownhosts.encode()))
        self.knownHosts.verifyHostKey = self.verifyHostKey

        self.keys = []
Ejemplo n.º 36
0
def getHostKeyAlgorithms(host, options):
    """
    Look in known_hosts for a key corresponding to C{host}.
    This can be used to change the order of supported key types
    in the KEXINIT packet.

    @type host: L{str}
    @param host: the host to check in known_hosts
    @type options: L{twisted.conch.client.options.ConchOptions}
    @param options: options passed to client
    @return: L{list} of L{str} representing key types or L{None}.
    """
    knownHosts = KnownHostsFile.fromPath(
        FilePath(options['known-hosts'] or os.path.expanduser(_KNOWN_HOSTS)))
    keyTypes = []
    for entry in knownHosts.iterentries():
        if entry.matchesHost(host):
            if entry.keyType not in keyTypes:
                keyTypes.append(entry.keyType)
    return keyTypes or None
Ejemplo n.º 37
0
    def test_savingAddsEntry(self):
        """
        L{KnownHostsFile.save} will write out a new file with any entries
        that have been added.
        """
        path = self.pathWithContent(sampleHashedLine +
                                    otherSamplePlaintextLine)
        knownHostsFile = KnownHostsFile.fromPath(path)
        newEntry = knownHostsFile.addHostKey("some.example.com",
                                             Key.fromString(thirdSampleKey))
        expectedContent = (sampleHashedLine + otherSamplePlaintextLine +
                           HashedEntry.MAGIC +
                           b2a_base64(newEntry._hostSalt).strip() + "|" +
                           b2a_base64(newEntry._hostHash).strip() +
                           " ssh-rsa " + thirdSampleEncodedKey + "\n")

        # Sanity check, let's make sure the base64 API being used for the test
        # isn't inserting spurious newlines.
        self.assertEqual(3, expectedContent.count("\n"))
        knownHostsFile.save()
        self.assertEqual(expectedContent, path.getContent())
Ejemplo n.º 38
0
    def test_savingAddsEntry(self):
        """
        L{KnownHostsFile.save()} will write out a new file with any entries
        that have been added.
        """
        path = self.pathWithContent(sampleHashedLine +
                                    otherSamplePlaintextLine)
        knownHostsFile = KnownHostsFile.fromPath(path)
        newEntry = knownHostsFile.addHostKey("some.example.com", Key.fromString(thirdSampleKey))
        expectedContent = (
            sampleHashedLine +
            otherSamplePlaintextLine + HashedEntry.MAGIC +
            b2a_base64(newEntry._hostSalt).strip() + "|" +
            b2a_base64(newEntry._hostHash).strip() + " ssh-rsa " +
            thirdSampleEncodedKey + "\n")

        # Sanity check, let's make sure the base64 API being used for the test
        # isn't inserting spurious newlines.
        self.assertEqual(3, expectedContent.count("\n"))
        knownHostsFile.save()
        self.assertEqual(expectedContent, path.getContent())
Ejemplo n.º 39
0
def getHostKeyAlgorithms(host, options):
    """
    Look in known_hosts for a key corresponding to C{host}.
    This can be used to change the order of supported key types
    in the KEXINIT packet.

    @type host: L{str}
    @param host: the host to check in known_hosts
    @type options: L{twisted.conch.client.options.ConchOptions}
    @param options: options passed to client
    @return: L{list} of L{str} representing key types or L{None}.
    """
    knownHosts = KnownHostsFile.fromPath(FilePath(
        options['known-hosts']
        or os.path.expanduser(_KNOWN_HOSTS)
        ))
    keyTypes = []
    for entry in knownHosts.iterentries():
        if entry.matchesHost(host):
            if entry.keyType not in keyTypes:
                keyTypes.append(entry.keyType)
    return keyTypes or None
Ejemplo n.º 40
0
    def __init__(self, remote_config, cmd):
        """Create a new remote Astrisk CLI Protocol instance

        Keyword Arguments:
        remote_config The parameters configuring this remote CLI command
        cmd           The CLI command to run
        """
        if REMOTE_ERROR:
            raise REMOTE_ERROR

        self.exitcode = -1
        self.output = ""
        self.err = ""

        self.config = remote_config
        self.cmd = cmd
        self.keys = []

        identity = self.config.get('identity')
        if identity:
            key_path = os.path.expanduser(identity)
            if os.path.exists(key_path):
                passphrase = self.config.get('passphrase')
                self.keys.append(Key.fromFile(key_path, passphrase=passphrase))

        known_hosts_file = self.config.get('known_hosts', '~/.ssh/known_hosts')
        known_hosts_path = FilePath(os.path.expanduser(known_hosts_file))
        if known_hosts_path.exists():
            self.known_hosts = KnownHostsFile.fromPath(known_hosts_path)
        else:
            self.known_hosts = None

        no_agent = self.config.get('no-agent')
        if no_agent or 'SSH_AUTH_SOCK' not in os.environ:
            self.agent_endpoint = None
        else:
            self.agent_endpoint = UNIXClientEndpoint(reactor,
                                                     os.environ['SSH_AUTH_SOCK'])
Ejemplo n.º 41
0
    def __init__(self, remote_config, cmd):
        """Create a new remote Astrisk CLI Protocol instance

        Keyword Arguments:
        remote_config The parameters configuring this remote CLI command
        cmd           The CLI command to run
        """
        if REMOTE_ERROR:
            raise REMOTE_ERROR

        self.exitcode = -1
        self.output = ""
        self.err = ""

        self.config = remote_config
        self.cmd = cmd
        self.keys = []

        identity = self.config.get('identity')
        if identity:
            key_path = os.path.expanduser(identity)
            if os.path.exists(key_path):
                passphrase = self.config.get('passphrase')
                self.keys.append(Key.fromFile(key_path, passphrase=passphrase))

        known_hosts_file = self.config.get('known_hosts', '~/.ssh/known_hosts')
        known_hosts_path = FilePath(os.path.expanduser(known_hosts_file))
        if known_hosts_path.exists():
            self.known_hosts = KnownHostsFile.fromPath(known_hosts_path)
        else:
            self.known_hosts = None

        no_agent = self.config.get('no-agent')
        if no_agent or 'SSH_AUTH_SOCK' not in os.environ:
            self.agent_endpoint = None
        else:
            self.agent_endpoint = UNIXClientEndpoint(reactor,
                                                     os.environ['SSH_AUTH_SOCK'])
Ejemplo n.º 42
0
    def __init__(self,
                 hostname,
                 username,
                 port,
                 password=None,
                 knownhosts=None):

        self.hostname = hostname.encode()
        self.username = username.encode()
        self.port = int(port)
        self.password = None
        self.endpoint = None
        if password:
            self.password = password.encode()
        self.connection = None

        if not knownhosts:
            knownhosts = '/var/lib/duct/known_hosts'

        self.knownHosts = KnownHostsFile.fromPath(FilePath(
            knownhosts.encode()))
        self.knownHosts.verifyHostKey = self.verifyHostKey

        self.keys = []
Ejemplo n.º 43
0
def getKnownHosts(knownhosts, **kwargs):
    known_hosts_path = FilePath(os.path.expanduser(knownhosts))
    if known_hosts_path.exists():
        return KnownHostsFile.fromPath(known_hosts_path)