Esempio n. 1
0
 def _setNewPass(self, np):
     if self._oldPass:
         op = self._oldPass
         self._oldPass = None
         self.askForAuth('password', '\xff' + NS(op) + NS(np))
     else:
         self._newPass = np
Esempio n. 2
0
 def _packAttributes(self, attrs):
     flags = 0
     data = ''
     if 'size' in attrs:
         data += struct.pack('!Q', attrs['size'])
         flags |= FILEXFER_ATTR_SIZE
     if 'uid' in attrs and 'gid' in attrs:
         data += struct.pack('!2L', attrs['uid'], attrs['gid'])
         flags |= FILEXFER_ATTR_OWNERGROUP
     if 'permissions' in attrs:
         data += struct.pack('!L', attrs['permissions'])
         flags |= FILEXFER_ATTR_PERMISSIONS
     if 'atime' in attrs and 'mtime' in attrs:
         data += struct.pack('!2L', attrs['atime'], attrs['mtime'])
         flags |= FILEXFER_ATTR_ACMODTIME
     extended = []
     for k in attrs:
         if k.startswith('ext_'):
             ext_type = NS(k[4:])
             ext_data = NS(attrs[k])
             extended.append(ext_type + ext_data)
     if extended:
         data += struct.pack('!L', len(extended))
         data += ''.join(extended)
         flags |= FILEXFER_ATTR_EXTENDED
     return struct.pack('!L', flags) + data
Esempio n. 3
0
 def _cbSendDirectory(self, result, requestId):
     data = ''
     for (filename, longname, attrs) in result:
         data += NS(filename)
         data += NS(longname)
         data += self._packAttributes(attrs)
     self.sendPacket(FXP_NAME,
                     requestId + struct.pack('!L', len(result)) + data)
Esempio n. 4
0
 def _sendStatus(self, requestId, code, message, lang=''):
     """
     Helper method to send a FXP_STATUS message.
     """
     data = requestId + struct.pack('!L', code)
     data += NS(message)
     data += NS(lang)
     self.sendPacket(FXP_STATUS, data)
Esempio n. 5
0
    def renameFile(self, oldpath, newpath):
        """
        Rename the given file.

        This method returns a Deferred that is called back when it succeeds.

        @param oldpath: the current location of the file.
        @param newpath: the new file name.
        """
        return self._sendRequest(FXP_RENAME, NS(oldpath) + NS(newpath))
Esempio n. 6
0
    def makeLink(self, linkPath, targetPath):
        """
        Create a symbolic link.

        This method returns when the link is made, or a Deferred that
        returns the same.

        @param linkPath: the pathname of the symlink as a string
        @param targetPath: the path of the target of the link as a string.
        """
        return self._sendRequest(FXP_SYMLINK, NS(linkPath) + NS(targetPath))
Esempio n. 7
0
 def auth_publickey(self):
     publicKey = self.getPublicKey()
     if publicKey:
         self.lastPublicKey = publicKey
         self.triedPublicKeys.append(publicKey)
         keyType = getNS(publicKey)[0]
         log.msg('using key of type %s' % keyType)
         self.askForAuth('publickey', '\x00' + NS(keyType) + \
                         NS(publicKey))
         return 1
     else:
         return 0
Esempio n. 8
0
 def sendKexInit(self):
     self.ourKexInitPayload = chr(MSG_KEXINIT)+entropy.get_bytes(16)+ \
                    NS(','.join(self.supportedKeyExchanges))+ \
                    NS(','.join(self.supportedPublicKeys))+ \
                    NS(','.join(self.supportedCiphers))+ \
                    NS(','.join(self.supportedCiphers))+ \
                    NS(','.join(self.supportedMACs))+ \
                    NS(','.join(self.supportedMACs))+ \
                    NS(','.join(self.supportedCompressions))+ \
                    NS(','.join(self.supportedCompressions))+ \
                    NS(','.join(self.supportedLanguages))+ \
                    NS(','.join(self.supportedLanguages))+ \
                    '\000'+'\000\000\000\000'
     self.sendPacket(MSG_KEXINIT, self.ourKexInitPayload[1:])
Esempio n. 9
0
 def packet_INIT(self, data):
     version, = struct.unpack('!L', data[:4])
     self.version = min(list(self.versions) + [version])
     data = data[4:]
     ext = {}
     while data:
         ext_name, data = getNS(data)
         ext_data, data = getNS(data)
         ext[ext_name] = ext_data
     our_ext = self.client.gotVersion(version, ext)
     our_ext_data = ""
     for (k, v) in our_ext.items():
         our_ext_data += NS(k) + NS(v)
     self.sendPacket(FXP_VERSION, struct.pack('!L', self.version) + \
                                  our_ext_data)
Esempio n. 10
0
    def openDirectory(self, path):
        """
        Open a directory for scanning.

        This method returns a Deferred that is called back with an iterable
        object that has a close() method.

        The close() method is called when the client is finished reading
        from the directory.  At this point, the iterable will no longer
        be used.

        The iterable returns triples of the form (filename, longname, attrs)
        or a Deferred that returns the same.  The sequence must support
        __getitem__, but otherwise may be any 'sequence-like' object.

        filename is the name of the file relative to the directory.
        logname is an expanded format of the filename.  The recommended format
        is:
        -rwxr-xr-x   1 mjos     staff      348911 Mar 25 14:29 t-filexfer
        1234567890 123 12345678 12345678 12345678 123456789012

        The first line is sample output, the second is the length of the field.
        The fields are: permissions, link count, user owner, group owner,
        size in bytes, modification time.

        attrs is a dictionary in the format of the attrs argument to openFile.

        @param path: the directory to open.
        """
        d = self._sendRequest(FXP_OPENDIR, NS(path))
        self.wasAFile[d] = (0, path)
        return d
Esempio n. 11
0
    def openFile(self, filename, flags, attrs):
        """
        Open a file.

        This method returns a L{Deferred} that is called back with an object
        that provides the L{ISFTPFile} interface.

        @param filename: a string representing the file to open.

        @param flags: a integer of the flags to open the file with, ORed together.
        The flags and their values are listed at the bottom of this file.

        @param attrs: a list of attributes to open the file with.  It is a
        dictionary, consisting of 0 or more keys.  The possible keys are::

            size: the size of the file in bytes
            uid: the user ID of the file as an integer
            gid: the group ID of the file as an integer
            permissions: the permissions of the file with as an integer.
            the bit representation of this field is defined by POSIX.
            atime: the access time of the file as seconds since the epoch.
            mtime: the modification time of the file as seconds since the epoch.
            ext_*: extended attributes.  The server is not required to
            understand this, but it may.

        NOTE: there is no way to indicate text or binary files.  it is up
        to the SFTP client to deal with this.
        """
        data = NS(filename) + struct.pack('!L',
                                          flags) + self._packAttributes(attrs)
        d = self._sendRequest(FXP_OPEN, data)
        self.wasAFile[d] = (1, filename)  # HACK
        return d
Esempio n. 12
0
 def _continueGEX_GROUP(self, ignored, pubKey, f, signature):
     serverKey = keys.getPublicKeyObject(pubKey)
     sharedSecret = _MPpow(f, self.x, DH_PRIME)
     h = sha.new()
     h.update(NS(self.ourVersionString))
     h.update(NS(self.otherVersionString))
     h.update(NS(self.ourKexInitPayload))
     h.update(NS(self.serverKexInitPayload))
     h.update(NS(pubKey))
     h.update(MP(self.DHpubKey))
     h.update(MP(f))
     h.update(sharedSecret)
     exchangeHash = h.digest()
     if not keys.verifySignature(serverKey, signature, exchangeHash):
         self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED, 'bad signature')
         return
     self._keySetup(sharedSecret, exchangeHash)
Esempio n. 13
0
    def requestService(self, instance):
        """
        Request that a service be run over this transport.

        @type instance: subclass of C{twisted.conch.ssh.service.SSHService}
        """
        self.sendPacket(MSG_SERVICE_REQUEST, NS(instance.name))
        self.instance = instance
Esempio n. 14
0
 def ssh_KEX_DH_GEX_REQUEST_OLD(self, packet):
     if self.ignoreNextPacket:
         self.ignoreNextPacket = 0
         return
     if self.kexAlg == 'diffie-hellman-group1-sha1':  # this is really KEXDH_INIT
         clientDHPubKey, foo = getMP(packet)
         y = Util.number.getRandomNumber(16, entropy.get_bytes)
         f = pow(DH_GENERATOR, y, DH_PRIME)
         sharedSecret = _MPpow(clientDHPubKey, y, DH_PRIME)
         h = sha.new()
         h.update(NS(self.otherVersionString))
         h.update(NS(self.ourVersionString))
         h.update(NS(self.clientKexInitPayload))
         h.update(NS(self.ourKexInitPayload))
         h.update(NS(self.factory.publicKeys[self.keyAlg]))
         h.update(MP(clientDHPubKey))
         h.update(MP(f))
         h.update(sharedSecret)
         exchangeHash = h.digest()
         self.sendPacket(MSG_KEXDH_REPLY, NS(self.factory.publicKeys[self.keyAlg])+ \
                        MP(f)+NS(keys.signData(self.factory.privateKeys[self.keyAlg], exchangeHash)))
         self._keySetup(sharedSecret, exchangeHash)
     elif self.kexAlg == 'diffie-hellman-group-exchange-sha1':
         self.kexAlg = 'diffie-hellman-group-exchange-sha1-old'
         self.ideal = struct.unpack('>L', packet)[0]
         self.g, self.p = self.factory.getDHPrime(self.ideal)
         self.sendPacket(MSG_KEX_DH_GEX_GROUP, MP(self.p) + MP(self.g))
     else:
         raise error.ConchError('bad kexalg: %s' % self.kexAlg)
Esempio n. 15
0
 def ssh_SERVICE_REQUEST(self, packet):
     service, rest = getNS(packet)
     cls = self.factory.getService(self, service)
     if not cls:
         self.sendDisconnect(DISCONNECT_SERVICE_NOT_AVAILABLE, "don't have service %s"%service)
         return
     else:
         self.sendPacket(MSG_SERVICE_ACCEPT, NS(service))
         self.setService(cls())
Esempio n. 16
0
    def removeFile(self, filename):
        """
        Remove the given file.

        This method returns a Deferred that is called back when it succeeds.

        @param filename: the name of the file as a string.
        """
        return self._sendRequest(FXP_REMOVE, NS(filename))
Esempio n. 17
0
    def extendedRequest(self, request, data):
        """
        Make an extended request of the server.
        request is the name of the extended request to make.
        data is any other data that goes along with the request.

        The method returns a Deferred that is called back with
        the result of the extended request.
        """
        return self._sendRequest(FXP_EXTENDED, NS(request) + data)
Esempio n. 18
0
    def readLink(self, path):
        """
        Find the root of a set of symbolic links.

        This method returns the target of the link, or a Deferred that
        returns the same.

        @param path: the path of the symlink to read.
        """
        d = self._sendRequest(FXP_READLINK, NS(path))
        return d.addCallback(self._cbRealPath)
Esempio n. 19
0
    def realPath(self, path):
        """
        Convert any path to an absolute path.

        This method returns the absolute path as a string, or a Deferred
        that returns the same.

        @param path: the path to convert as a string.
        """
        d = self._sendRequest(FXP_REALPATH, NS(path))
        return d.addCallback(self._cbRealPath)
Esempio n. 20
0
    def removeDirectory(self, path):
        """
        Remove a directory (non-recursively)

        It is an error to remove a directory that has files or directories in
        it.

        This method returns a Deferred that is called back when it is removed.

        @param path: the directory to remove.
        """
        return self._sendRequest(FXP_RMDIR, NS(path))
Esempio n. 21
0
    def makeDirectory(self, path, attrs):
        """
        Make a directory.

        path is the name of the directory to create as a string.
        attrs is a dictionary of attributes to create the directory with.
        It's meaning is the same as the attrs in the openFile method.

        This method returns a Deferred that is called back when it is 
        created.
        """
        return self._sendRequest(FXP_MKDIR, NS(path)+self._packAttributes(attrs))
Esempio n. 22
0
 def _pamConv(self, items):
     resp = []
     for message, kind in items:
         if kind == 1:  # password
             resp.append((message, 0))
         elif kind == 2:  # text
             resp.append((message, 1))
         elif kind in (3, 4):
             return defer.fail(
                 error.ConchError('cannot handle PAM 3 or 4 messages'))
         else:
             return defer.fail(
                 error.ConchError('bad PAM auth kind %i' % kind))
     packet = NS('') + NS('') + NS('')
     packet += struct.pack('>L', len(resp))
     for prompt, echo in resp:
         packet += NS(prompt)
         packet += chr(echo)
     self.transport.sendPacket(MSG_USERAUTH_INFO_REQUEST, packet)
     self._pamDeferred = defer.Deferred()
     return self._pamDeferred
Esempio n. 23
0
 def ssh_USERAUTH_PK_OK(self, packet):
     if self.lastAuth == 'publickey':
         # this is ok
         publicKey = self.lastPublicKey
         keyType = getNS(publicKey)[0]
         b = NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) + \
         NS(self.user) + NS(self.instance.name) + NS('publickey') + '\xff' +\
         NS(keyType) + NS(publicKey)
         d = self.signData(publicKey, b)
         if not d:
             self.askForAuth('none', '')
             # this will fail, we'll move on
             return
         d.addCallback(self._cbSignedData)
         d.addErrback(self._ebAuth)
     elif self.lastAuth == 'password':
         prompt, language, rest = getNS(packet, 2)
         self._oldPass = self._newPass = None
         self.getPassword('Old Password: '******'keyboard-interactive':
         name, instruction, lang, data = getNS(packet, 3)
         numPrompts = struct.unpack('!L', data[:4])[0]
         data = data[4:]
         prompts = []
         for i in range(numPrompts):
             prompt, data = getNS(data)
             echo = bool(ord(data[0]))
             data = data[1:]
             prompts.append((prompt, echo))
         d = self.getGenericAnswers(name, instruction, prompts)
         d.addCallback(self._cbGenericAnswers)
         d.addErrback(self._ebAuth)
Esempio n. 24
0
    def setAttrs(self, path, attrs):
        """
        Set the attributes for the path.

        This method returns when the attributes are set or a Deferred that is
        called back when they are.

        @param path: the path to set attributes for as a string.
        @param attrs: a dictionary in the same format as the attrs argument to
        openFile.
        """
        data = NS(path) + self._packAttributes(attrs)
        return self._sendRequest(FXP_SETSTAT, data)
Esempio n. 25
0
    def getAttrs(self, path, followLinks=0):
        """
        Return the attributes for the given path.

        This method returns a dictionary in the same format as the attrs
        argument to openFile or a Deferred that is called back with same.

        @param path: the path to return attributes for as a string.
        @param followLinks: a boolean.  if it is True, follow symbolic links
        and return attributes for the real path at the base.  if it is False,
        return attributes for the specified path.
        """
        if followLinks: m = FXP_STAT
        else: m = FXP_LSTAT
        return self._sendRequest(m, NS(path))
Esempio n. 26
0
    def ssh_KEX_DH_GEX_INIT(self, packet):
        clientDHPubKey, foo = getMP(packet)

        # if y < 1024, openssh will reject us: "bad server public DH value".
        # y<1024 means f will be short, and of the form 2^y, so an observer
        # could trivially derive our secret y from f. Openssh detects this
        # and complains, so avoid creating such values by requiring y to be
        # larger than ln2(self.p)

        # TODO: we should also look at the value they send to us and reject
        # insecure values of f (if g==2 and f has a single '1' bit while the
        # rest are '0's, then they must have used a small y also).

        # TODO: This could be computed when self.p is set up
        #  or do as openssh does and scan f for a single '1' bit instead

        minimum = long(math.floor(math.log(self.p) / math.log(2)) + 1)
        tries = 0
        pSize = Util.number.size(self.p)
        y = Util.number.getRandomNumber(pSize, entropy.get_bytes)
        while tries < 10 and y < minimum:
            tries += 1
            y = Util.number.getRandomNumber(pSize, entropy.get_bytes)
        assert (y >= minimum)  # TODO: test_conch just hangs if this is hit
        # the chance of it being hit are really really low

        f = pow(self.g, y, self.p)
        sharedSecret = _MPpow(clientDHPubKey, y, self.p)
        h = sha.new()
        h.update(NS(self.otherVersionString))
        h.update(NS(self.ourVersionString))
        h.update(NS(self.clientKexInitPayload))
        h.update(NS(self.ourKexInitPayload))
        h.update(NS(self.factory.publicKeys[self.keyAlg]))
        if self.kexAlg == 'diffie-hellman-group-exchange-sha1':
            h.update(struct.pack('>3L', self.min, self.ideal, self.max))
        else:
            h.update(struct.pack('>L', self.ideal))
        h.update(MP(self.p))
        h.update(MP(self.g))
        h.update(MP(clientDHPubKey))
        h.update(MP(f))
        h.update(sharedSecret)
        exchangeHash = h.digest()
        self.sendPacket(MSG_KEX_DH_GEX_REPLY, NS(self.factory.publicKeys[self.keyAlg])+ \
                       MP(f)+NS(keys.signData(self.factory.privateKeys[self.keyAlg], exchangeHash)))
        self._keySetup(sharedSecret, exchangeHash)
Esempio n. 27
0
 def _ebBadAuth(self, reason):
     if reason.type == error.IgnoreAuthentication:
         return
     if self.method != 'none':
         log.msg('%s failed auth %s' % (self.user, self.method))
         log.msg('reason:')
         if reason.type == error.ConchError:
             log.msg(str(reason))
         else:
             log.msg(reason.getTraceback())
         self.loginAttempts += 1
         if self.loginAttempts > self.attemptsBeforeDisconnect:
             self.transport.sendDisconnect(
                 transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
                 'too many bad auths')
     self.transport.sendPacket(
         MSG_USERAUTH_FAILURE,
         NS(','.join(self.supportedAuthentications)) + '\x00')
Esempio n. 28
0
 def auth_publickey(self, packet):
     hasSig = ord(packet[0])
     algName, blob, rest = getNS(packet[1:], 2)
     pubKey = keys.getPublicKeyObject(data=blob)
     signature = hasSig and getNS(rest)[0] or None
     if hasSig:
         b = NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) + \
             NS(self.user) + NS(self.nextService) + NS('publickey') + \
             chr(hasSig) +  NS(keys.objectType(pubKey)) + NS(blob)
         c = credentials.SSHPrivateKey(self.user, algName, blob, b,
                                       signature)
         return self.portal.login(c, None, interfaces.IConchUser)
     else:
         c = credentials.SSHPrivateKey(self.user, algName, blob, None, None)
         return self.portal.login(c, None,
                                  interfaces.IConchUser).addErrback(
                                      self._ebCheckKey, packet[1:])
Esempio n. 29
0
 def _cbPassword(self, password):
     self.askForAuth('password', '\x00' + NS(password))
Esempio n. 30
0
 def auth_keyboard_interactive(self):
     log.msg('authing with keyboard-interactive')
     self.askForAuth('keyboard-interactive', NS('') + NS(''))
     return 1