Пример #1
0
    def parse_packet(self, parent, message_num, payload):
        self.data = payload
        self.packetSize = len(payload)
        self.sendOn = True

        try:
            packet = self.packetLayout[message_num]
        except:
            packet = 'UNKNOWN_%s' % message_num

        if not self.server.post_auth_started:
            if parent == '[SERVER]':
                direction = 'CLIENT -> SERVER'
            else:
                direction = 'SERVER -> CLIENT'
        else:
            if parent == '[SERVER]':
                direction = 'HONSSH -> SERVER'
            else:
                direction = 'SERVER -> HONSSH'

        self.out.packet_logged(direction, packet, payload)

        if self.cfg.has_option('devmode', 'enabled') and self.cfg.getboolean(
            ['devmode', 'enabled']):
            log.msg(
                log.LBLUE, '[SSH]',
                direction + ' - ' + packet.ljust(37) + ' - ' + repr(payload))

        # - UserAuth
        if packet == 'SSH_MSG_USERAUTH_REQUEST':
            self.username = self.extract_string()
            service = self.extract_string()
            auth_type = self.extract_string()

            if auth_type == 'password':
                self.extract_bool()
                self.password = self.extract_string()

                if self.password != "":
                    if not self.server.post_auth_started:
                        self.server.start_post_auth(self.username,
                                                    self.password)
                        self.sendOn = False

            elif auth_type == 'publickey':
                if self.cfg.getboolean(['hp-restrict', 'disable_publicKey']):
                    self.sendOn = False
                    self.server.sendPacket(
                        51,
                        self.string_to_hex('password') + chr(0))

        elif packet == 'SSH_MSG_USERAUTH_FAILURE':
            auth_list = self.extract_string()

            if 'publickey' in auth_list:
                if self.cfg.getboolean(['hp-restrict', 'disable_publicKey']):
                    log.msg(log.LPURPLE, '[SSH]',
                            'Detected Public Key Auth - Disabling!')
                    payload = self.string_to_hex('password') + chr(0)

            if not self.server.post_auth_started:
                if self.username != '' and self.password != '':
                    self.out.login_failed(self.username, self.password)
                    self.server.login_failed(self.username, self.password)

        elif packet == 'SSH_MSG_USERAUTH_SUCCESS':
            if len(self.username) > 0 and len(self.password) > 0:
                self.out.login_successful(self.username, self.password,
                                          self.server.spoofed)
                self.server.login_successful(self.username, self.password)

        # - End UserAuth
        # - Channels
        elif packet == 'SSH_MSG_CHANNEL_OPEN':
            channel_type = self.extract_string()
            id = self.extract_int(4)

            if channel_type == 'session':
                self.create_channel(parent, id, channel_type)
            elif channel_type == 'x11':
                if self.cfg.getboolean(['hp-restrict', 'disable_x11']):
                    log.msg(log.LPURPLE, '[SSH]',
                            'Detected X11 Channel - Disabling!')
                    self.sendOn = False
                    self.send_back(parent, 92, self.int_to_hex(id))
                else:
                    # LOG X11 Channel opened - not logging
                    the_uuid = uuid.uuid4().hex
                    the_name = '[X11-' + str(id) + ']'
                    self.create_channel(parent,
                                        id,
                                        channel_type,
                                        session=baseProtocol.BaseProtocol(
                                            uuid=the_uuid,
                                            name=the_name,
                                            ssh=self))
                    channel = self.get_channel(id, '[CLIENT]')
                    channel['name'] = the_name
                    self.out.channel_opened(the_uuid, channel['name'])
            elif channel_type == 'direct-tcpip' or channel_type == 'forwarded-tcpip':
                if self.cfg.getboolean(
                    ['hp-restrict', 'disable_port_forwarding']):
                    log.msg(log.LPURPLE, '[SSH]',
                            'Detected Port Forwarding Channel - Disabling!')
                    self.sendOn = False
                    self.send_back(
                        parent, 92,
                        self.int_to_hex(id) + self.int_to_hex(1) +
                        self.string_to_hex('open failed') + self.int_to_hex(0))
                else:
                    # LOG PORT FORWARDING Channel opened
                    self.extract_int(4)
                    self.extract_int(4)

                    conn_details = {
                        'dstIP': self.extract_string(),
                        'dstPort': self.extract_int(4),
                        'srcIP': self.out.end_ip,
                        'srcPort': self.extract_int(4)
                    }
                    the_uuid = uuid.uuid4().hex
                    self.create_channel(parent, id, channel_type)

                    if parent == '[SERVER]':
                        other_parent = '[CLIENT]'
                        the_name = '[LPRTF' + str(id) + ']'
                    else:
                        other_parent = '[SERVER]'
                        the_name = '[RPRTF' + str(id) + ']'

                    channel = self.get_channel(id, other_parent)
                    channel['name'] = the_name
                    self.out.channel_opened(the_uuid, channel['name'])
                    channel['session'] = portForward.PortForward(
                        self.out, the_uuid, channel['name'], self,
                        conn_details, parent, other_parent)
            else:
                # UNKNOWN CHANNEL TYPE
                if channel_type not in ['exit-status']:
                    log.msg(log.LRED, '[SSH]',
                            'Unknown Channel Type Detected - ' + channel_type)

        elif packet == 'SSH_MSG_CHANNEL_OPEN_CONFIRMATION':
            channel = self.get_channel(self.extract_int(4), parent)
            # SENDER
            sender_id = self.extract_int(4)

            if parent == '[SERVER]':
                channel['serverID'] = sender_id
            elif parent == '[CLIENT]':
                channel['clientID'] = sender_id
                # CHANNEL OPENED

        elif packet == 'SSH_MSG_CHANNEL_OPEN_FAILURE':
            channel = self.get_channel(self.extract_int(4), parent)
            self.out.channel_closed(channel['session'])
            self.channels.remove(channel)
            # CHANNEL FAILED TO OPEN

        elif packet == 'SSH_MSG_CHANNEL_REQUEST':
            channel = self.get_channel(self.extract_int(4), parent)
            channel_type = self.extract_string()
            the_uuid = uuid.uuid4().hex

            if channel_type == 'shell':
                channel['name'] = '[TERM' + str(channel['serverID']) + ']'
                self.out.channel_opened(the_uuid, channel['name'])
                channel['session'] = term.Term(self.out, the_uuid,
                                               channel['name'], self,
                                               channel['clientID'])
            elif channel_type == 'exec':
                if self.cfg.get(['hp-restrict', 'disable_exec']):
                    log.msg(log.LPURPLE, '[SSH]',
                            'Detected EXEC Channel Request - Disabling!')
                    self.sendOn = False
                    self.send_back(parent, 100,
                                   self.int_to_hex(channel['serverID']))
                    blocked = True
                else:
                    blocked = False

                channel['name'] = '[EXEC' + str(channel['serverID']) + ']'
                self.extract_bool()
                command = self.extract_string()
                self.out.channel_opened(the_uuid, channel['name'])
                channel['session'] = execTerm.ExecTerm(self.out, the_uuid,
                                                       channel['name'],
                                                       command, self, blocked)

                if blocked:
                    channel['session'].channel_closed()
                    self.out.channel_closed(channel['session'])
                    self.channels.remove(channel)
            elif channel_type == 'subsystem':
                self.extract_bool()
                subsystem = self.extract_string()

                if subsystem == 'sftp':
                    if self.cfg.getboolean(['hp-restrict', 'disable_sftp']):
                        log.msg(log.LPURPLE, '[SSH]',
                                'Detected SFTP Channel Request - Disabling!')
                        self.sendOn = False
                        self.send_back(parent, 100,
                                       self.int_to_hex(channel['serverID']))
                    else:
                        channel['name'] = '[SFTP' + str(
                            channel['serverID']) + ']'
                        self.out.channel_opened(the_uuid, channel['name'])
                        channel['session'] = sftp.SFTP(self.out, the_uuid,
                                                       channel['name'], self)
                else:
                    # UNKNOWN SUBSYSTEM
                    log.msg(log.LRED, '[SSH]',
                            'Unknown Subsystem Type Detected - ' + subsystem)
            elif channel_type == 'x11-req':
                if self.cfg.getboolean(['hp-restrict', 'disable_x11']):
                    self.sendOn = False
                    self.send_back(parent, 82, '')
            else:
                # UNKNOWN CHANNEL REQUEST TYPE
                if channel_type not in [
                        'window-change', 'env', 'pty-req', 'exit-status',
                        'exit-signal'
                ]:
                    log.msg(
                        log.LRED, '[SSH]',
                        'Unknown Channel Request Type Detected - ' +
                        channel_type)

        elif packet == 'SSH_MSG_CHANNEL_FAILURE':
            pass

        elif packet == 'SSH_MSG_CHANNEL_CLOSE':
            channel = self.get_channel(self.extract_int(4), parent)
            # Is this needed?!
            channel[parent] = True

            if '[SERVER]' in channel and '[CLIENT]' in channel:
                # CHANNEL CLOSED
                if channel['session'] is not None:
                    channel['session'].channel_closed()
                    self.out.channel_closed(channel['session'])

                self.channels.remove(channel)
        # - END Channels
        # - ChannelData
        elif packet == 'SSH_MSG_CHANNEL_DATA':
            channel = self.get_channel(self.extract_int(4), parent)
            channel['session'].parse_packet(parent, self.extract_string())

        elif packet == 'SSH_MSG_CHANNEL_EXTENDED_DATA':
            channel = self.get_channel(self.extract_int(4), parent)
            self.extract_int(4)
            channel['session'].parse_packet(parent, self.extract_string())
        # - END ChannelData

        elif packet == 'SSH_MSG_GLOBAL_REQUEST':
            channel_type = self.extract_string()
            if channel_type == 'tcpip-forward':
                if self.cfg.getboolean(
                    ['hp-restrict', 'disable_port_forwarding']):
                    self.sendOn = False
                    self.send_back(parent, 82, '')

        if self.server.post_auth_started:
            if parent == '[CLIENT]':
                self.server.post_auth.send_next()
                self.sendOn = False

        if self.sendOn:
            if parent == '[SERVER]':
                self.client.sendPacket(message_num, payload)
            else:
                self.server.sendPacket(message_num, payload)
Пример #2
0
    def parsePacket(self, parent, messageNum, payload):
        self.data = payload
        self.packetSize = len(payload)
        self.sendOn = True

        packet = self.packetLayout[messageNum]

        if parent == '[SERVER]':
            direction = 'CLIENT -> SERVER'
        else:
            direction = 'SERVER -> CLIENT'

        if self.cfg.get('packets', 'enabled') == 'true':
            self.out.advancedLog(direction + ' - ' + packet.ljust(35) + ' - ' +
                                 repr(payload))

        if self.cfg.has_option('devmode', 'enabled'):
            if self.cfg.get('devmode', 'enabled') == 'true':
                log.msg(direction + ' - ' + packet.ljust(35) + ' - ' +
                        repr(payload))

        # - UserAuth
        if packet == 'SSH_MSG_USERAUTH_REQUEST':
            self.username = self.extractString()
            service = self.extractString()
            authType = self.extractString()
            if authType == 'password':
                self.extractBool()
                psize = self.packetSize
                self.password = self.extractString()
                if self.password != "":
                    if self.cfg.get('spoof', 'enabled') == 'true':
                        user = self.getUsers(self.username)
                        rand = 0
                        if user != None:
                            if user[2] == 'fixed':
                                passwords = re.sub(r'\s', '',
                                                   user[3]).split(',')
                                if self.password in passwords:
                                    rand = 1
                            elif user[2] == 'random':
                                randomFactor = (100 / int(user[3])) + 1
                                rand = random.randrange(1, randomFactor)

                            found = False
                            logfile = self.cfg.get('folders',
                                                   'log_path') + "/spoof.log"
                            if os.path.isfile(logfile):
                                f = file(logfile, 'r')
                                creds = f.read().splitlines()
                                f.close()
                                for cred in creds:
                                    cred = cred.strip().split(' - ')
                                    if cred[0] == self.username and cred[
                                            1] == self.password:
                                        rand = 1
                                        self.out.writePossibleLink(cred[2:])
                                        break

                        if rand == 1:
                            payload = payload[:0 - psize] + self.stringToHex(
                                user[1])
                            self.out.addConnectionString(
                                "[SSH  ] Spoofing Login - Changing %s to %s" %
                                (self.password, user[1]))
                            self.out.writeSpoofPass(self.username,
                                                    self.password)

            elif authType == 'publickey':
                if self.cfg.get('hp-restrict', 'disable_publicKey') == 'true':
                    self.sendOn = False
                    self.server.sendPacket(
                        51,
                        self.stringToHex('password') + chr(0))

        elif packet == 'SSH_MSG_USERAUTH_FAILURE':
            authList = self.extractString()
            if 'publickey' in authList:
                if self.cfg.get('hp-restrict', 'disable_publicKey') == 'true':
                    log.msg("[SSH] - Detected Public Key Auth - Disabling!")
                    payload = self.stringToHex('password') + chr(0)
            if self.username != '' and self.password != '':
                self.out.loginFailed(self.username, self.password)

        elif packet == 'SSH_MSG_USERAUTH_SUCCESS':
            if self.username != '' and self.password != '':
                self.out.loginSuccessful(self.username, self.password)

        # - End UserAuth
        # - Channels
        elif packet == 'SSH_MSG_CHANNEL_OPEN':
            type = self.extractString()
            id = self.extractInt(4)
            if type == 'session':
                self.createChannel(parent, id, type)
            elif type == 'x11':
                if self.cfg.get('hp-restrict', 'disable_x11') == 'true':
                    log.msg("[SSH] - Detected X11 Channel - Disabling!")
                    self.sendOn = False
                    self.sendBack(parent, 92, self.intToHex(id))
                else:
                    ##LOG X11 Channel opened - not logging
                    theUUID = uuid.uuid4().hex
                    theName = '[X11-' + str(id) + ']'
                    self.createChannel(parent,
                                       id,
                                       type,
                                       session=baseProtocol.BaseProtocol(
                                           uuid=theUUID,
                                           name=theName,
                                           ssh=self))
                    channel = self.getChannel(id, '[CLIENT]')
                    channel['name'] = theName
                    self.out.channelOpened(theUUID, channel['name'])
            elif type == 'direct-tcpip' or type == 'forwarded-tcpip':
                if self.cfg.get('hp-restrict',
                                'disable_port_forwarding') == 'true':
                    log.msg(
                        "[SSH] - Detected Port Forwarding Channel - Disabling!"
                    )
                    self.sendOn = False
                    self.sendBack(
                        parent, 92,
                        self.intToHex(id) + self.intToHex(1) +
                        self.stringToHex('open failed') + self.intToHex(0))
                else:
                    ##LOG PORT FORWARDING Channel opened
                    self.extractInt(4)
                    self.extractInt(4)

                    connDetails = {
                        'dstIP': self.extractString(),
                        'dstPort': self.extractInt(4),
                        'srcIP': self.extractString(),
                        'srcPort': self.extractInt(4)
                    }
                    connDetails['srcIP'] = self.out.endIP
                    theUUID = uuid.uuid4().hex
                    self.createChannel(parent, id, type)

                    if parent == '[SERVER]':
                        otherParent = '[CLIENT]'
                        theName = '[LPRTF' + str(id) + ']'
                    else:
                        otherParent = '[SERVER]'
                        theName = '[RPRTF' + str(id) + ']'

                    channel = self.getChannel(id, otherParent)
                    channel['name'] = theName
                    self.out.channelOpened(theUUID, channel['name'])
                    channel['session'] = portForward.PortForward(
                        self.out, theUUID, channel['name'], self, connDetails,
                        parent, otherParent)
            else:
                ##UNKNOWN CHANNEL TYPE
                if type not in ['exit-status']:
                    log.msg("[SSH] - Unknown Channel Type Detected - " + type)

        elif packet == 'SSH_MSG_CHANNEL_OPEN_CONFIRMATION':
            channel = self.getChannel(self.extractInt(4), parent)
            senderID = self.extractInt(4)  #SENDER

            if parent == '[SERVER]':
                channel['serverID'] = senderID
            elif parent == '[CLIENT]':
                channel['clientID'] = senderID
            ##CHANNEL OPENED

        elif packet == 'SSH_MSG_CHANNEL_OPEN_FAILURE':
            channel = self.getChannel(self.extractInt(4), parent)
            self.out.channelClosed(channel['session'])
            self.channels.remove(channel)
            ##CHANNEL FAILED TO OPEN

        elif packet == 'SSH_MSG_CHANNEL_REQUEST':
            channel = self.getChannel(self.extractInt(4), parent)
            type = self.extractString()
            theUUID = uuid.uuid4().hex
            if type == 'shell':
                channel['name'] = '[TERM' + str(channel['serverID']) + ']'
                self.out.channelOpened(theUUID, channel['name'])
                channel['session'] = term.Term(self.out, theUUID,
                                               channel['name'], self,
                                               channel['clientID'])
            elif type == 'exec':
                if self.cfg.get('hp-restrict', 'disable_exec') == 'true':
                    log.msg(
                        "[SSH] - Detected EXEC Channel Request - Disabling!")
                    self.sendOn = False
                    self.sendBack(parent, 100,
                                  self.intToHex(channel['serverID']))
                else:
                    channel['name'] = '[EXEC' + str(channel['serverID']) + ']'
                    self.extractBool()
                    command = self.extractString()
                    self.out.channelOpened(theUUID, channel['name'])
                    channel['session'] = execTerm.ExecTerm(
                        self.out, theUUID, channel['name'], command, self)
            elif type == 'subsystem':
                self.extractBool()
                subsystem = self.extractString()
                if subsystem == 'sftp':
                    if self.cfg.get('hp-restrict', 'disable_sftp') == 'true':
                        log.msg(
                            "[SSH] - Detected SFTP Channel Request - Disabling!"
                        )
                        self.sendOn = False
                        self.sendBack(parent, 100,
                                      self.intToHex(channel['serverID']))
                    else:
                        channel['name'] = '[SFTP' + str(
                            channel['serverID']) + ']'
                        self.out.channelOpened(theUUID, channel['name'])
                        channel['session'] = sftp.SFTP(self.out, theUUID,
                                                       channel['name'], self)
                else:
                    ##UNKNOWN SUBSYSTEM
                    log.msg("[SSH] - Unknown Subsystem Type Detected - " +
                            subsystem)
            elif type == 'x11-req':
                if self.cfg.get('hp-restrict', 'disable_x11') == 'true':
                    self.sendOn = False
                    self.sendBack(parent, 82, '')
            else:
                ##UNKNOWN CHANNEL REQUEST TYPE
                if type not in [
                        'window-change', 'env', 'pty-req', 'exit-status'
                ]:
                    log.msg(
                        "[SSH] - Unknown Channel Request Type Detected - " +
                        type)

        elif packet == 'SSH_MSG_CHANNEL_FAILURE':
            pass

        elif packet == 'SSH_MSG_CHANNEL_CLOSE':
            channel = self.getChannel(self.extractInt(4), parent)
            channel[parent] = True  #Is this needed?!
            if '[SERVER]' in channel and '[CLIENT]' in channel:
                ##CHANNEL CLOSED
                if channel['session'] != None:
                    channel['session'].channelClosed()
                    self.out.channelClosed(channel['session'])
                self.channels.remove(channel)
        # - END Channels
        # - ChannelData
        elif packet == 'SSH_MSG_CHANNEL_DATA':
            channel = self.getChannel(self.extractInt(4), parent)
            channel['session'].parsePacket(parent, self.extractString())

        elif packet == 'SSH_MSG_CHANNEL_EXTENDED_DATA':
            channel = self.getChannel(self.extractInt(4), parent)
            self.extractInt(4)
            channel['session'].parsePacket(parent, self.extractString())
        # - END ChannelData

        elif packet == 'SSH_MSG_GLOBAL_REQUEST':
            type = self.extractString()
            if type == 'tcpip-forward':
                if self.cfg.get('hp-restrict',
                                'disable_port_forwarding') == 'true':
                    self.sendOn = False
                    self.sendBack(parent, 82, '')

        if self.sendOn:
            if parent == '[SERVER]':
                self.client.sendPacket(messageNum, payload)
            else:
                self.server.sendPacket(messageNum, payload)