twisted.conch.ssh.keys.Key.fromString

Here are the examples of the python api twisted.conch.ssh.keys.Key.fromString taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

79 Examples 7

Page 1 Selected Page 2

Example 1

Project: SubliminalCollaborator Source File: test_keys.py
Function: testpublicfromstring
    def _testPublicFromString(self, public, type, data):
        publicKey = keys.Key.fromString(public)
        self.assertTrue(publicKey.isPublic())
        self.assertEqual(publicKey.type(), type)
        for k, v in publicKey.data().items():
            self.assertEqual(data[k], v)

Example 2

Project: SubliminalCollaborator Source File: test_keys.py
    def test_sign(self):
        """
        Test that the Key object generates correct signatures.
        """
        key = keys.Key.fromString(keydata.privateRSA_openssh)
        self.assertEqual(key.sign(''), self.rsaSignature)
        key = keys.Key.fromString(keydata.privateDSA_openssh)
        self.assertEqual(key.sign(''), self.dsaSignature)

Example 3

Project: mythbox Source File: test_knownhosts.py
Function: test_from_string
    def test_fromString(self):
        """
        Constructing a plain text entry from an unhashed known_hosts entry will
        result in an L{IKnownHostEntry} provider with 'keyString', 'hostname',
        and 'keyType' attributes.  While outside the interface in question,
        these attributes are held in common by L{PlainEntry} and L{HashedEntry}
        implementations; other implementations should override this method in
        subclasses.
        """
        entry = self.entry
        self.assertEqual(entry.publicKey, Key.fromString(sampleKey))
        self.assertEqual(entry.keyType, "ssh-rsa")

Example 4

Project: mythbox Source File: test_knownhosts.py
    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)))

Example 5

Project: mythbox Source File: test_knownhosts.py
Function: test_haskeymismatch
    def test_hasKeyMismatch(self):
        """
        L{KnownHostsFile.hasHostKey} raises L{HostKeyChanged} if the host key
        is present, but different from the expected one.  The resulting
        exception should have an offendingEntry indicating the given entry.
        """
        hostsFile = self.loadSampleHostsFile()
        exception = self.assertRaises(
            HostKeyChanged, hostsFile.hasHostKey,
            "www.twistedmatrix.com", Key.fromString(otherSampleKey))
        self.assertEqual(exception.offendingEntry, hostsFile._entries[0])
        self.assertEqual(exception.lineno, 1)
        self.assertEqual(exception.path, hostsFile._savePath)

Example 6

Project: mythbox Source File: test_keys.py
    def test_toLSH(self):
        """
        Test that the Key object generates LSH keys correctly.
        """
        key = keys.Key.fromString(keydata.privateRSA_openssh)
        self.assertEquals(key.toString('lsh'), keydata.privateRSA_lsh)
        self.assertEquals(key.public().toString('lsh'),
                keydata.publicRSA_lsh)
        key = keys.Key.fromString(keydata.privateDSA_openssh)
        self.assertEquals(key.toString('lsh'), keydata.privateDSA_lsh)
        self.assertEquals(key.public().toString('lsh'),
                keydata.publicDSA_lsh)

Example 7

Project: SubliminalCollaborator Source File: test_keys.py
    def test_fromBlob(self):
        """
        Test that a public key is correctly generated from a public key blob.
        """
        rsaBlob = common.NS('ssh-rsa') + common.MP(2) + common.MP(3)
        rsaKey = keys.Key.fromString(rsaBlob)
        dsaBlob = (common.NS('ssh-dss') + common.MP(2) + common.MP(3) +
                common.MP(4) + common.MP(5))
        dsaKey = keys.Key.fromString(dsaBlob)
        badBlob = common.NS('ssh-bad')
        self.assertTrue(rsaKey.isPublic())
        self.assertEqual(rsaKey.data(), {'e':2L, 'n':3L})

Example 8

Project: mythbox Source File: test_default.py
    def setUp(self):
        self.rsaPublic = Key.fromString(keydata.publicRSA_openssh)
        self.tmpdir = FilePath(self.mktemp())
        self.tmpdir.makedirs()
        self.rsaFile = self.tmpdir.child('id_rsa')
        self.rsaFile.setContent(keydata.privateRSA_openssh)
        self.tmpdir.child('id_rsa.pub').setContent(keydata.publicRSA_openssh)

Example 9

Project: SubliminalCollaborator Source File: test_knownhosts.py
Function: set_up
    def setUp(self):
        """
        Patch 'open' in verifyHostKey.
        """
        self.fakeFile = FakeFile()
        self.patch(default, "_open", self.patchedOpen)
        self.hostsOption = self.mktemp()
        knownHostsFile = KnownHostsFile(FilePath(self.hostsOption))
        knownHostsFile.addHostKey("exists.example.com",
            Key.fromString(sampleKey))
        knownHostsFile.addHostKey("4.3.2.1", Key.fromString(sampleKey))
        knownHostsFile.save()
        self.fakeTransport = FakeObject()
        self.fakeTransport.factory = FakeObject()
        self.options = self.fakeTransport.factory.options = {
            'host': "exists.example.com",
            'known-hosts': self.hostsOption
            }

Example 10

Project: mythbox Source File: test_default.py
    def test_getPrivateKey(self):
        """
        L{SSHUserAuthClient.getPrivateKey} will load a private key from the
        last used file populated by L{SSHUserAuthClient.getPublicKey}, and
        return a L{Deferred} which fires with the corresponding private L{Key}.
        """
        rsaPrivate = Key.fromString(keydata.privateRSA_openssh)
        options = ConchOptions()
        options.identitys = [self.rsaFile.path]
        client = SSHUserAuthClient("user",  options, None)
        # Populate the list of used files
        client.getPublicKey()

        def _cbGetPrivateKey(key):
            self.assertEquals(key.isPublic(), False)
            self.assertEquals(key, rsaPrivate)

        return client.getPrivateKey().addCallback(_cbGetPrivateKey)

Example 11

Project: mythbox Source File: test_knownhosts.py
    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)

Example 12

Project: mythbox Source File: test_knownhosts.py
    def test_verifyValidKey(self):
        """
        Verifying a valid key should return a L{Deferred} which fires with
        True.
        """
        hostsFile = self.loadSampleHostsFile()
        hostsFile.addHostKey("1.2.3.4", Key.fromString(sampleKey))
        ui = FakeUI()
        d = hostsFile.verifyHostKey(ui, "www.twistedmatrix.com", "1.2.3.4",
                                    Key.fromString(sampleKey))
        l = []
        d.addCallback(l.append)
        self.assertEqual(l, [True])

Example 13

Project: mythbox Source File: test_keys.py
    def test_fromBlob(self):
        """
        Test that a public key is correctly generated from a public key blob.
        """
        rsaBlob = common.NS('ssh-rsa') + common.MP(2) + common.MP(3)
        rsaKey = keys.Key.fromString(rsaBlob)
        dsaBlob = (common.NS('ssh-dss') + common.MP(2) + common.MP(3) +
                common.MP(4) + common.MP(5))
        dsaKey = keys.Key.fromString(dsaBlob)
        badBlob = common.NS('ssh-bad')
        self.assertTrue(rsaKey.isPublic())
        self.assertEquals(rsaKey.data(), {'e':2L, 'n':3L})

Example 14

Project: SubliminalCollaborator Source File: test_default.py
    def test_getPublicKeyBadKeyError(self):
        """
        If L{keys.Key.fromFile} raises a L{keys.BadKeyError}, the
        L{SSHUserAuthClient.getPublicKey} tries again to get a public key by
        calling itself recursively.
        """
        options = ConchOptions()
        self.tmpdir.child('id_dsa.pub').setContent(keydata.publicDSA_openssh)
        dsaFile = self.tmpdir.child('id_dsa')
        dsaFile.setContent(keydata.privateDSA_openssh)
        options.identitys = [self.rsaFile.path, dsaFile.path]
        self.tmpdir.child('id_rsa.pub').setContent('not a key!')
        client = SSHUserAuthClient("user",  options, None)
        key = client.getPublicKey()
        self.assertEqual(key.isPublic(), True)
        self.assertEqual(key, Key.fromString(keydata.publicDSA_openssh))
        self.assertEqual(client.usedFiles, [self.rsaFile.path, dsaFile.path])

Example 15

Project: mythbox Source File: userauth.py
    def _cbGetPublicKey(self, publicKey):
        if isinstance(publicKey, str):
            warnings.warn("Returning a string from "
                          "SSHUserAuthClient.getPublicKey() is deprecated "
                          "since Twisted 9.0.  Return a keys.Key() instead.",
                          DeprecationWarning)
            publicKey = keys.Key.fromString(publicKey)
        if not isinstance(publicKey, keys.Key): # failure or None
            publicKey = None
        if publicKey is not None:
            self.lastPublicKey = publicKey
            self.triedPublicKeys.append(publicKey)
            log.msg('using key of type %s' % publicKey.type())
            self.askForAuth('publickey', '\x00' + NS(publicKey.sshType()) +
                            NS(publicKey.blob()))
            return True
        else:
            return False

Example 16

Project: SubliminalCollaborator Source File: test_keys.py
    def test_fromOpenSSH(self):
        """
        Test that keys are correctly generated from OpenSSH strings.
        """
        self._testPublicPrivateFromString(keydata.publicRSA_openssh,
                keydata.privateRSA_openssh, 'RSA', keydata.RSAData)
        self.assertEqual(keys.Key.fromString(
            keydata.privateRSA_openssh_encrypted,
            passphrase='encrypted'),
            keys.Key.fromString(keydata.privateRSA_openssh))
        self.assertEqual(keys.Key.fromString(
            keydata.privateRSA_openssh_alternate),
            keys.Key.fromString(keydata.privateRSA_openssh))
        self._testPublicPrivateFromString(keydata.publicDSA_openssh,
                keydata.privateDSA_openssh, 'DSA', keydata.DSAData)

Example 17

Project: mythbox Source File: test_keys.py
    def test_sign(self):
        """
        Test that the Key object generates correct signatures.
        """
        key = keys.Key.fromString(keydata.privateRSA_openssh)
        self.assertEquals(key.sign(''), self.rsaSignature)
        key = keys.Key.fromString(keydata.privateDSA_openssh)
        self.assertEquals(key.sign(''), self.dsaSignature)

Example 18

Project: SubliminalCollaborator Source File: test_keys.py
    def test_toLSH(self):
        """
        Test that the Key object generates LSH keys correctly.
        """
        key = keys.Key.fromString(keydata.privateRSA_openssh)
        self.assertEqual(key.toString('lsh'), keydata.privateRSA_lsh)
        self.assertEqual(key.public().toString('lsh'),
                keydata.publicRSA_lsh)
        key = keys.Key.fromString(keydata.privateDSA_openssh)
        self.assertEqual(key.toString('lsh'), keydata.privateDSA_lsh)
        self.assertEqual(key.public().toString('lsh'),
                keydata.publicDSA_lsh)

Example 19

Project: opencanary Source File: ssh.py
    def getService(self):
        factory = HoneyPotSSHFactory(version=self.version, logger=self.logger)
        factory.canaryservice = self
        factory.portal = portal.Portal(HoneyPotRealm())

        rsa_pubKeyString, rsa_privKeyString = getRSAKeys()
        dsa_pubKeyString, dsa_privKeyString = getDSAKeys()
        factory.portal.registerChecker(HoneypotPasswordChecker(logger=factory.logger))
        factory.portal.registerChecker(CanaryPublicKeyChecker(logger=factory.logger))
        factory.publicKeys = {'ssh-rsa': keys.Key.fromString(data=rsa_pubKeyString),
                              'ssh-dss': keys.Key.fromString(data=dsa_pubKeyString)}
        factory.privateKeys = {'ssh-rsa': keys.Key.fromString(data=rsa_privKeyString),
                               'ssh-dss': keys.Key.fromString(data=dsa_privKeyString)}
        return internet.TCPServer(self.port, factory, interface=self.listen_addr)

Example 20

Project: SubliminalCollaborator Source File: test_knownhosts.py
Function: test_haskeymismatch
    def test_hasKeyMismatch(self):
        """
        L{KnownHostsFile.hasHostKey} raises L{HostKeyChanged} if the host key
        is present, but different from the expected one.  The resulting
        exception should have an C{offendingEntry} indicating the given entry.
        """
        hostsFile = self.loadSampleHostsFile()
        exception = self.assertRaises(
            HostKeyChanged, hostsFile.hasHostKey,
            "www.twistedmatrix.com", Key.fromString(otherSampleKey))
        self.assertEqual(exception.offendingEntry, hostsFile._entries[0])
        self.assertEqual(exception.lineno, 1)
        self.assertEqual(exception.path, hostsFile._savePath)

Example 21

Project: mythbox Source File: test_knownhosts.py
    def test_hasPresentKey(self):
        """
        L{KnownHostsFile.hasHostKey} returns C{True} when a key for the given
        hostname is present and matches the expected key.
        """
        hostsFile = self.loadSampleHostsFile()
        self.assertEqual(True, hostsFile.hasHostKey(
                "www.twistedmatrix.com", Key.fromString(sampleKey)))

Example 22

Project: mythbox Source File: test_knownhosts.py
    def test_hasNonPresentKey(self):
        """
        L{KnownHostsFile.hasHostKey} returns C{False} when a key for the given
        hostname is not present.
        """
        hostsFile = self.loadSampleHostsFile()
        self.assertEqual(False, hostsFile.hasHostKey(
                "non-existent.example.com", Key.fromString(sampleKey)))

Example 23

Project: Piped Source File: providers.py
Function: init
    def __init__(self, portal, private_key=None, public_key=None, **kw):
        manhole_ssh.ConchFactory.__init__(self, portal)
        if private_key:
            self.privateKeys = {
                'ssh-rsa' : keys.Key.fromString(private_key)
            }

        if public_key:
            self.publicKeys = {
                'ssh-rsa' : keys.Key.fromString(public_key)
            }

Example 24

Project: mythbox Source File: test_knownhosts.py
    def test_randomSalts(self):
        """
        L{KnownHostsFile.addHostKey} generates a random salt for each new key,
        so subsequent salts will be different.
        """
        hostsFile = self.loadSampleHostsFile()
        aKey = Key.fromString(thirdSampleKey)
        self.assertNotEqual(
            hostsFile.addHostKey("somewhere.example.com", aKey)._hostSalt,
            hostsFile.addHostKey("somewhere-else.example.com", aKey)._hostSalt)

Example 25

Project: mythbox Source File: test_keys.py
Function: testpublicfromstring
    def _testPublicFromString(self, public, type, data):
        publicKey = keys.Key.fromString(public)
        self.assertTrue(publicKey.isPublic())
        self.assertEquals(publicKey.type(), type)
        for k, v in publicKey.data().items():
            self.assertEquals(data[k], v)

Example 26

Project: mythbox Source File: test_knownhosts.py
    def test_verifyHostIPMismatch(self):
        """
        Verifying a key where the host is present (and correct), but the IP is
        present and different, should result the deferred firing in a
        HostKeyChanged failure.
        """
        hostsFile = self.loadSampleHostsFile()
        wrongKey = Key.fromString(thirdSampleKey)
        ui = FakeUI()
        d = hostsFile.verifyHostKey(
            ui, "www.twistedmatrix.com", "4.3.2.1", wrongKey)
        return self.assertFailure(d, HostKeyChanged)

Example 27

Project: mythbox Source File: test_knownhosts.py
Function: test_verify_invalid_key
    def test_verifyInvalidKey(self):
        """
        Verfying an invalid key should return a L{Deferred} which fires with a
        L{HostKeyChanged} failure.
        """
        hostsFile = self.loadSampleHostsFile()
        wrongKey = Key.fromString(thirdSampleKey)
        ui = FakeUI()
        hostsFile.addHostKey("1.2.3.4", Key.fromString(sampleKey))
        d = hostsFile.verifyHostKey(
            ui, "www.twistedmatrix.com", "1.2.3.4", wrongKey)
        return self.assertFailure(d, HostKeyChanged)

Example 28

Project: mythbox Source File: test_keys.py
    def test_fromOpenSSH(self):
        """
        Test that keys are correctly generated from OpenSSH strings.
        """
        self._testPublicPrivateFromString(keydata.publicRSA_openssh,
                keydata.privateRSA_openssh, 'RSA', keydata.RSAData)
        self.assertEquals(keys.Key.fromString(
            keydata.privateRSA_openssh_encrypted,
            passphrase='encrypted'),
            keys.Key.fromString(keydata.privateRSA_openssh))
        self.assertEquals(keys.Key.fromString(
            keydata.privateRSA_openssh_alternate),
            keys.Key.fromString(keydata.privateRSA_openssh))
        self._testPublicPrivateFromString(keydata.publicDSA_openssh,
                keydata.privateDSA_openssh, 'DSA', keydata.DSAData)

Example 29

Project: mythbox Source File: test_knownhosts.py
    def setUp(self):
        """
        Patch 'open' in verifyHostKey.
        """
        self.fakeFile = FakeFile()
        self.patch(default, "_open", self.patchedOpen)
        self.hostsOption = self.mktemp()
        knownHostsFile = KnownHostsFile(FilePath(self.hostsOption))
        knownHostsFile.addHostKey("exists.example.com", Key.fromString(sampleKey))
        knownHostsFile.addHostKey("4.3.2.1", Key.fromString(sampleKey))
        knownHostsFile.save()
        self.fakeTransport = FakeObject()
        self.fakeTransport.factory = FakeObject()
        self.options = self.fakeTransport.factory.options = {
            'host': "exists.example.com",
            'known-hosts': self.hostsOption
            }

Example 30

Project: mythbox Source File: agent.py
    def agentc_REMOVE_IDENTITY(self, data):
        """
        Remove a specific key from the agent's collection of identities.
        """
        blob, _ = getNS(data)
        k = keys.Key.fromString(blob, type='blob')
        del self.factory.keys[k.blob()]
        self.sendResponse(AGENT_SUCCESS, '')

Example 31

Project: mythbox Source File: test_userauth.py
    def getPublicKey(self):
        """
        If this is the first time we've been called, return a blob for
        the DSA key.  Otherwise, return a blob
        for the RSA key.
        """
        if self.lastPublicKey:
            return keys.Key.fromString(keydata.publicRSA_openssh)
        else:
            return defer.succeed(keys.Key.fromString(keydata.publicDSA_openssh))

Example 32

Project: mythbox Source File: test_keys.py
    def test_toOpenSSH(self):
        """
        Test that the Key object generates OpenSSH keys correctly.
        """
        key = keys.Key.fromString(keydata.privateRSA_lsh)
        self.assertEquals(key.toString('openssh'), keydata.privateRSA_openssh)
        self.assertEquals(key.toString('openssh', 'encrypted'),
                keydata.privateRSA_openssh_encrypted)
        self.assertEquals(key.public().toString('openssh'),
                keydata.publicRSA_openssh[:-8]) # no comment
        self.assertEquals(key.public().toString('openssh', 'comment'),
                keydata.publicRSA_openssh)
        key = keys.Key.fromString(keydata.privateDSA_lsh)
        self.assertEquals(key.toString('openssh'), keydata.privateDSA_openssh)
        self.assertEquals(key.public().toString('openssh', 'comment'),
                keydata.publicDSA_openssh)
        self.assertEquals(key.public().toString('openssh'),
                keydata.publicDSA_openssh[:-8]) # no comment

Example 33

Project: SubliminalCollaborator Source File: test_default.py
    def test_getPrivateKey(self):
        """
        L{SSHUserAuthClient.getPrivateKey} will load a private key from the
        last used file populated by L{SSHUserAuthClient.getPublicKey}, and
        return a L{Deferred} which fires with the corresponding private L{Key}.
        """
        rsaPrivate = Key.fromString(keydata.privateRSA_openssh)
        options = ConchOptions()
        options.identitys = [self.rsaFile.path]
        client = SSHUserAuthClient("user",  options, None)
        # Populate the list of used files
        client.getPublicKey()

        def _cbGetPrivateKey(key):
            self.assertEqual(key.isPublic(), False)
            self.assertEqual(key, rsaPrivate)

        return client.getPrivateKey().addCallback(_cbGetPrivateKey)

Example 34

Project: mythbox Source File: test_default.py
    def test_getPublicKeyBadKeyError(self):
        """
        If L{keys.Key.fromFile} raises a L{keys.BadKeyError}, the
        L{SSHUserAuthClient.getPublicKey} tries again to get a public key by
        calling itself recursively.
        """
        options = ConchOptions()
        self.tmpdir.child('id_dsa.pub').setContent(keydata.publicDSA_openssh)
        dsaFile = self.tmpdir.child('id_dsa')
        dsaFile.setContent(keydata.privateDSA_openssh)
        options.identitys = [self.rsaFile.path, dsaFile.path]
        self.tmpdir.child('id_rsa.pub').setContent('not a key!')
        client = SSHUserAuthClient("user",  options, None)
        key = client.getPublicKey()
        self.assertEquals(key.isPublic(), True)
        self.assertEquals(key, Key.fromString(keydata.publicDSA_openssh))
        self.assertEquals(client.usedFiles, [self.rsaFile.path, dsaFile.path])

Example 35

Project: SubliminalCollaborator Source File: test_keys.py
Function: testprivatefromstring
    def _testPrivateFromString(self, private, type, data):
        privateKey = keys.Key.fromString(private)
        self.assertFalse(privateKey.isPublic())
        self.assertEqual(privateKey.type(), type)
        for k, v in data.items():
            self.assertEqual(privateKey.data()[k], v)

Example 36

Project: mythbox Source File: test_keys.py
    def test_toAgentv3(self):
        """
        Test that the Key object generates Agent v3 keys correctly.
        """
        key = keys.Key.fromString(keydata.privateRSA_openssh)
        self.assertEquals(key.toString('agentv3'), keydata.privateRSA_agentv3)
        key = keys.Key.fromString(keydata.privateDSA_openssh)
        self.assertEquals(key.toString('agentv3'), keydata.privateDSA_agentv3)

Example 37

Project: SubliminalCollaborator Source File: test_keys.py
    def test_fromNewerOpenSSH(self):
        """
        Newer versions of OpenSSH generate encrypted keys which have a longer
        IV than the older versions.  These newer keys are also loaded.
        """
        key = keys.Key.fromString(keydata.privateRSA_openssh_encrypted_aes,
                                  passphrase='testxp')
        self.assertEqual(key.type(), 'RSA')
        key2 = keys.Key.fromString(
            keydata.privateRSA_openssh_encrypted_aes + '\n',
            passphrase='testxp')
        self.assertEqual(key, key2)

Example 38

Project: mythbox Source File: test_agent.py
    def setUp(self):
        # wire up our client <-> server
        self.client, self.server, self.pump = iosim.connectedServerAndClient(
            agent.SSHAgentServer, agent.SSHAgentClient)

        # the server's end of the protocol is stateful and we store it on the
        # factory, for which we only need a mock
        self.server.factory = StubFactory()

        # pub/priv keys of each kind
        self.rsaPrivate = keys.Key.fromString(keydata.privateRSA_openssh)
        self.dsaPrivate = keys.Key.fromString(keydata.privateDSA_openssh)

        self.rsaPublic = keys.Key.fromString(keydata.publicRSA_openssh)
        self.dsaPublic = keys.Key.fromString(keydata.publicDSA_openssh)

Example 39

Project: SubliminalCollaborator Source File: test_keys.py
    def test_toOpenSSH(self):
        """
        Test that the Key object generates OpenSSH keys correctly.
        """
        key = keys.Key.fromString(keydata.privateRSA_lsh)
        self.assertEqual(key.toString('openssh'), keydata.privateRSA_openssh)
        self.assertEqual(key.toString('openssh', 'encrypted'),
                keydata.privateRSA_openssh_encrypted)
        self.assertEqual(key.public().toString('openssh'),
                keydata.publicRSA_openssh[:-8]) # no comment
        self.assertEqual(key.public().toString('openssh', 'comment'),
                keydata.publicRSA_openssh)
        key = keys.Key.fromString(keydata.privateDSA_lsh)
        self.assertEqual(key.toString('openssh'), keydata.privateDSA_openssh)
        self.assertEqual(key.public().toString('openssh', 'comment'),
                keydata.publicDSA_openssh)
        self.assertEqual(key.public().toString('openssh'),
                keydata.publicDSA_openssh[:-8]) # no comment

Example 40

Project: mythbox Source File: test_keys.py
    def test_verify(self):
        """
        Test that the Key object correctly verifies signatures.
        """
        key = keys.Key.fromString(keydata.publicRSA_openssh)
        self.assertTrue(key.verify(self.rsaSignature, ''))
        self.assertFalse(key.verify(self.rsaSignature, 'a'))
        self.assertFalse(key.verify(self.dsaSignature, ''))
        key = keys.Key.fromString(keydata.publicDSA_openssh)
        self.assertTrue(key.verify(self.dsaSignature, ''))
        self.assertFalse(key.verify(self.dsaSignature, 'a'))
        self.assertFalse(key.verify(self.rsaSignature, ''))

Example 41

Project: SubliminalCollaborator Source File: test_keys.py
    def test_toAgentv3(self):
        """
        Test that the Key object generates Agent v3 keys correctly.
        """
        key = keys.Key.fromString(keydata.privateRSA_openssh)
        self.assertEqual(key.toString('agentv3'), keydata.privateRSA_agentv3)
        key = keys.Key.fromString(keydata.privateDSA_openssh)
        self.assertEqual(key.toString('agentv3'), keydata.privateDSA_agentv3)

Example 42

Project: mythbox Source File: test_knownhosts.py
Function: test_matcheskey
    def test_matchesKey(self):
        """
        L{IKnownHostEntry.matchesKey} checks to see if an entry matches a given
        SSH key.
        """
        twistedmatrixDotCom = Key.fromString(sampleKey)
        divmodDotCom = Key.fromString(otherSampleKey)
        self.assertEqual(
            True,
            self.entry.matchesKey(twistedmatrixDotCom))
        self.assertEqual(
            False,
            self.entry.matchesKey(divmodDotCom))

Example 43

Project: SubliminalCollaborator Source File: test_keys.py
    def test_verifyDSANoPrefix(self):
        """
        Some commercial SSH servers send DSA keys as 2 20-byte numbers;
        they are still verified as valid keys.
        """
        key = keys.Key.fromString(keydata.publicDSA_openssh)
        self.assertTrue(key.verify(self.dsaSignature[-40:], ''))

Example 44

Project: ZenPacks.zenoss.OpenStackInfrastructure Source File: __init__.py
Function: get_public_key
    def getPublicKey(self):
        identities = self.options.get('identities')
        if not identities:
            return

        identity = os.path.expanduser(identities[0])
        if not os.path.exists(identity):
            return

        password = self.options.get('password', '')

        log.debug('Reading pubkey %s' % identity)
        try:
            data = ''.join(open(identity).readlines()).strip()
            self.key = Key.fromString(data, passphrase=password)
            return self.key
        except Exception:
            return

Example 45

Project: mythbox Source File: agent.py
Function: get_public_key
    def getPublicKey(self):
        """
        Return a L{Key} from the first blob in C{self.blobs}, if any, or
        return C{None}.
        """
        if self.blobs:
            return keys.Key.fromString(self.blobs.pop(0))
        return None

Example 46

Project: mythbox Source File: test_keys.py
Function: testprivatefromstring
    def _testPrivateFromString(self, private, type, data):
        privateKey = keys.Key.fromString(private)
        self.assertFalse(privateKey.isPublic())
        self.assertEquals(privateKey.type(), type)
        for k, v in data.items():
            self.assertEquals(privateKey.data()[k], v)

Example 47

Project: mythbox Source File: test_knownhosts.py
    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)))

Example 48

Project: tahoe-lafs Source File: auth.py
    def _checkKey(self, creds):
        """
        Determine whether some key-based credentials correctly authenticates a
        user.

        Returns a Deferred that fires with the username if so or with an
        UnauthorizedLogin failure otherwise.
        """

        # Is the public key indicated by the given credentials allowed to
        # authenticate the username in those credentials?
        if creds.blob == self.pubkeys.get(creds.username):
            if creds.signature is None:
                return defer.fail(conch_error.ValidPublicKey())

            # Is the signature in the given credentials the correct
            # signature for the data in those credentials?
            key = keys.Key.fromString(creds.blob)
            if key.verify(creds.signature, creds.sigData):
                return defer.succeed(self._avatarId(creds.username))

        return defer.fail(error.UnauthorizedLogin())

Example 49

Project: ZenPacks.zenoss.OpenStackInfrastructure Source File: test_auth.py
Function: init
    def __init__(self, user, password):
        log.debug('adding user %s to ssh server' % user)
        self.passwdDB.addUser(user, password)
        self.privateKeys = {'ssh-rsa': Key.fromString(data=privkey)}
        self.publicKeys = {'ssh-rsa': Key.fromString(data=pubkey)}

Example 50

Project: ZenPacks.zenoss.OpenStackInfrastructure Source File: test_common.py
    def requestAvatarId(self, credentials):
        userKeyString = self.authorizedKeys.get(credentials.username)
        if not userKeyString:
            return failure.Failure(error.ConchError("No such user"))

        # Remove the 'ssh-rsa' type before decoding.
        if credentials.blob != base64.decodestring(
                userKeyString.split(" ")[1]):
            raise failure.failure(
                error.ConchError("I don't recognize that key"))

        if not credentials.signature:
            return failure.Failure(error.ValidPublicKey())

        userKey = keys.Key.fromString(data=userKeyString)
        if userKey.verify(credentials.signature, credentials.sigData):
            return credentials.username
        else:
            log.debug("signature check failed")
            return failure.Failure(
                error.ConchError("Incorrect signature"))
See More Examples - Go to Next Page
Page 1 Selected Page 2