Example #1
0
 def ping(test_params, show_result=False):
     """Check CoAP service availability by sending ping packet and waiting for response."""
     if not test_params:
         return None
     coap_ping_packets = [COAP_PING_1_RAW, COAP_PING_2_RAW]
     for coap_ping_raw in coap_ping_packets:
         packet_raw = dehex(coap_ping_raw)
         response = udp_sr1(test_params, packet_raw, test_params.wrap_secure_layer)
         if response:
             for response_packet in response:
                 response_packet.show()
                 if (
                     response_packet.haslayer(CoAP)
                     and response_packet[CoAP].ver == 1
                 ):
                     return True
                 coap_response = coap_scrap_response(response_packet)
                 print_verbose(test_params, coap_response)
                 if (
                     "ver       = 1" in coap_response
                     and coap_convert_type(coap_response) != "Empty"
                 ):
                     print_verbose(test_params, "Found CoAP response")
                     return True
     print_verbose(test_params, "NOT found CoAP response")
     return False
Example #2
0
def search_string():
    string = input("Search String : ")
    for i in cap_raw:
        try:
            id_to_name = {'6': 'TCP', '17': 'UDP'}
            proto = id_to_name[i['ip'].proto]
            if bytes(string,
                     'utf-8') in hexdump.dehex(i[proto].payload_raw[0]):
                for j in hexdump.dehex(i[proto].payload_raw[0]):
                    if chr(j).isprintable():
                        print(chr(j), end='')
                    else:
                        print('.', end='')
                print()
        except:
            pass
    input("press <enter> to continue ...")
Example #3
0
 def ping(test_params, show_result=False):
     """Checks MQTT service availability by sending ping packet and waiting for response."""
     # MQTT ping is using Connect message
     for packet_hex in [MQTT_CONN_MQTT, MQTT_CONN_MQISDP]:
         packet_data = dehex(packet_hex)
         out_packet = MQTT(packet_data)
         if mqtt_request(test_params, out_packet):
             return True
     return False
Example #4
0
def write_block(ctx, input, hexdata, seek, length, address):
    """Write data to radio memory.

    This command will by default read data from stdin. Use the --input (-i)
    option to read data from a file instead, or --hexdata (-d) to provide
    hexadecimal data on the command line.

    Examples:

    1. Write four bytes to address 0x1700

       tmv71 memory write-block 0x1700 -d 'F0 15 AB 08'

    2. Open 'backup.dat', seek to position 0x1700, read 16 bytes, and
       write them to address 0x1700:

       tmv71 memory write-block 0x1700 -i backup.dat -s 0x1700 -l 16
    """

    LOG.debug("seek %d length %d address %d", seek, length, address)

    if input:
        LOG.debug("reading data from %s", input.name)
        with input:
            input.seek(seek)
            data = input.read(length)
    elif hexdata:
        LOG.debug("reading data from hexdata option")
        data = hexdump.dehex(hexdata)
        if seek:
            data = data[seek:]
        if length:
            data = data[:length]
    elif sys.stdin.buffer.seekable():
        LOG.debug("reading data from stdin (seekable)")
        sys.stdin.buffer.seek(seek)
        data = sys.stdin.buffer.read(length)
    else:
        LOG.debug("reading data from stdin (not seekable)")
        data = sys.stdin.buffer.read()[seek:]
        if length:
            data = data[:length]

    with ctx.api.programming_mode():
        addr = address
        for chunk in hexdump.chunks(data, 256):
            chunklen = len(chunk)
            LOG.info(
                "writing %d bytes of data to address 0x%04X",
                256 if chunklen == 0 else chunklen,
                addr,
            )

            addr += 256
            ctx.api.write_block(address, chunk)
Example #5
0
 def ping(test_params, show_result=False):
     """Check MQTT-SN service availability by sending ping packet and waiting for response."""
     if not test_params:
         return None
     # MQTT-SN ping is using Search Gateway message
     for packet_hex in [MQTTSN_SEARCH_GATEWAY]:
         packet_data = dehex(packet_hex)
         out_packet = MQTT(packet_data)
         if mqttsn_request(test_params, out_packet):
             return True
     return False
Example #6
0
 def ping(test_params, show_result=False):
     """Checks CoAP service availability by sending ping packet and waiting for response."""
     coap_ping_packets = [COAP_PING_1_RAW, COAP_PING_2_RAW]
     for coap_ping_raw in coap_ping_packets:
         packet_raw = dehex(coap_ping_raw)
         response = udp_sr1(test_params, packet_raw,
                            test_params.wrap_secure_layer)
         if response is not None:
             for response_packet in response:
                 coap_response = coap_scrap_response(response_packet)
                 print_verbose(test_params, coap_response)
                 if ("ver       = 1" in coap_response
                         and coap_convert_type(coap_response) != "Empty"):
                     return True
     return False
Example #7
0
    def _wrapper_info(self):
        memory = self._info['memory']
        self._out_dict['type'] = memory['operation']
        self._out_dict['data target address'] = memory['address']

        symbol = self._info["symbol"]
        pc_str = symbol['address'] + " "
        # 如果能解析出来符号则解析
        if symbol["moduleName"]:
            pc_str = pc_str + symbol["moduleName"] + "!" + symbol["name"]
        self._out_dict['PC'] = pc_str
        self._out_dict['ins str'] = self._info["ins"]

        operands = self._info["operands"]
        self._out_dict['Register'] = self._handle_operands(operands)

        data = self._info['data']
        self._out_dict['data'] = hexdump.hexdump(hexdump.dehex(data),
                                                 result="return")
Example #8
0
def mqtt_ping(test_params):
    """Checks MQTT service availability by sending ping packet and waiting for response."""
    # MQTT ping is using Connect message
    packet_data = dehex(MQTT_CONN)
    out_packet = MQTT(packet_data)
    try:
        for i in range(1 + test_params.nr_retries):
            in_data = tcp_sr1(test_params, out_packet)
            in_packet = MQTT(in_data)
            show_verbose(test_params, in_packet)
            if (
                in_packet[MQTT].type in CONTROL_PACKET_TYPE
                and CONTROL_PACKET_TYPE[in_packet[MQTT].type] == "CONNACK"
            ):
                print_verbose(
                    test_params,
                    "MQTT ping {}: in_packet[MQTTConnack].retcode: {}".format(
                        i + 1, RETURN_CODE[in_packet[MQTTConnack].retcode]
                    ),
                )
                return True
    except (socket.timeout, socket.error) as error:
        print_verbose(test_params, error)
    return False
Example #9
0
import socket
import telnetlib


# 88.87.208.163:6969
# 11111111111111111
def xor_encrypt(data, key):
    decode_string = ''
    for i in range(len(data)):
        decode_string += chr((ord(data[i])
                              ^ ord(key[len(key) - i % len(key) - 1])) & 0xFF)
    return decode_string


data = '55 75 44 B6 0B 33 06 03 E9 02 60 71 47 B2 44 33'
data1 = hexdump.dehex(data)
print data.encode('hex')
key = '65 87 33 45 12'
key1 = hexdump.dehex(key)

flag = xor_encrypt(data1, key1)
print flag.encode('hex')
print flag
print hashlib.sha1(flag).hexdigest()
a = '01101111080101100801101010110101'.decode('hex')
print hashlib.sha1(a).hexdigest()
s = socket.create_connection(('88.87.208.163', 6969))
t = telnetlib.Telnet()
t.sock = s
t.interact()
Example #10
0
    def true_sendall(self, data, *args, **kwargs):
        req = decode_from_bytes(data)
        # make request unique again
        req_signature = hashlib.md5(encode_to_bytes(''.join(sorted(req.split('\r\n'))))).hexdigest()
        # port should be always a string
        port = text_type(self._port)

        # prepare responses dictionary
        responses = dict()

        if Mocket.get_truesocket_recording_dir():
            path = os.path.join(
                Mocket.get_truesocket_recording_dir(),
                Mocket.get_namespace() + '.json',
            )
            # check if there's already a recorded session dumped to a JSON file
            try:
                with io.open(path) as f:
                    responses = json.load(f)
            # if not, create a new dictionary
            except (FileNotFoundError, JSONDecodeError):
                pass

        try:
            response_dict = responses[self._host][port][req_signature]
        except KeyError:
            # preventing next KeyError exceptions
            responses.setdefault(self._host, dict())
            responses[self._host].setdefault(port, dict())
            responses[self._host][port].setdefault(req_signature, dict())
            response_dict = responses[self._host][port][req_signature]

        # try to get the response from the dictionary
        try:
            try:
                encoded_response = hexdump.dehex(response_dict['response'])
            except TypeError:  # pragma: no cover
                # Python 2
                encoded_response = hexdump.restore(encode_to_bytes(response_dict['response']))
        # if not available, call the real sendall
        except KeyError:
            self._connect()
            self.true_socket.sendall(data, *args, **kwargs)
            encoded_response = b''
            # https://github.com/kennethreitz/requests/blob/master/tests/testserver/server.py#L13
            while select.select([self.true_socket], [], [], 0.5)[0]:
                recv = self.true_socket.recv(self._buflen)
                if recv:
                    encoded_response += recv
                else:
                    break

            # dump the resulting dictionary to a JSON file
            if Mocket.get_truesocket_recording_dir():

                # update the dictionary with request and response lines
                response_dict['request'] = req
                response_dict['response'] = hexdump.dump(encoded_response)

                with io.open(path, mode='w') as f:
                    f.write(decode_from_bytes(json.dumps(responses, indent=4, sort_keys=True)))

        # response back to .sendall() which writes it to the mocket socket and flush the BytesIO
        return encoded_response
Example #11
0
def read_hex(data):
    return hexdump.dehex(data)
Example #12
0
def read_hex(data):
    return hexdump.dehex(data)
Example #13
0
R: 11:56:30.129    .....>..          BD 8F FE 04 D3 3E 2E BD
""".split('\n')

x = "T: 11:56:28.622    ..........#.....  "

msg = " ".join([z[len(x):] for z in msg])

import logging
logging.basicConfig(level=logging.INFO)
import hexdump
import io

from PyCampbellCR1000.pycampbellcr1000.pakdecode import PakBusDecode


class pbByteIo(io.BytesIO):
    # pakbus assumes there is a timeout member...
    timeout = 1


link = pbByteIo(hexdump.dehex(msg))

pb = PakBusDecode(link)
packet = pb.read()
while packet:

    logging.debug("packet is {}: {}".format(hexdump.dump(packet), packet))
    hdr, msg = pb.decode_packet(bytes(packet))
    logging.info('HEAD: {}'.format(hdr))
    logging.info(' MSG: {}'.format(msg))
    packet = pb.read()
Example #14
0
import hashlib
import base64
import hexdump
import socket
import telnetlib

# 88.87.208.163:6969
# 11111111111111111
def xor_encrypt(data, key):
    decode_string = ''
    for i in range(len(data)):
        decode_string += chr((ord(data[i])^ord(key[len(key)-i%len(key)-1]))&0xFF)
    return decode_string

data='55 75 44 B6 0B 33 06 03 E9 02 60 71 47 B2 44 33'
data1=hexdump.dehex(data)
print data.encode('hex')
key='65 87 33 45 12'
key1=hexdump.dehex(key)



flag=xor_encrypt(data1,key1)
print flag.encode('hex')
print flag
print hashlib.sha1(flag).hexdigest()
a='01101111080101100801101010110101'.decode('hex')
print hashlib.sha1(a).hexdigest()
s = socket.create_connection(('88.87.208.163', 6969))
t = telnetlib.Telnet()
t.sock = s
Example #15
0
    def true_sendall(self, data, *args, **kwargs):
        req = decode_from_bytes(data)
        # make request unique again
        req_signature = _hash_request(hasher, req)
        # port should be always a string
        port = text_type(self._port)

        # prepare responses dictionary
        responses = dict()

        if Mocket.get_truesocket_recording_dir():
            path = os.path.join(Mocket.get_truesocket_recording_dir(),
                                Mocket.get_namespace() + ".json")
            # check if there's already a recorded session dumped to a JSON file
            try:
                with io.open(path) as f:
                    responses = json.load(f)
            # if not, create a new dictionary
            except (FileNotFoundError, JSONDecodeError):
                pass

        try:
            try:
                response_dict = responses[self._host][port][req_signature]
            except KeyError:
                if hasher is not hashlib.md5:
                    # Fallback for backwards compatibility
                    req_signature = _hash_request(hashlib.md5, req)
                    response_dict = responses[self._host][port][req_signature]
                else:
                    raise
        except KeyError:
            # preventing next KeyError exceptions
            responses.setdefault(self._host, dict())
            responses[self._host].setdefault(port, dict())
            responses[self._host][port].setdefault(req_signature, dict())
            response_dict = responses[self._host][port][req_signature]

        # try to get the response from the dictionary
        try:
            try:
                encoded_response = hexdump.dehex(response_dict["response"])
            except TypeError:  # pragma: no cover
                # Python 2
                encoded_response = hexdump.restore(
                    encode_to_bytes(response_dict["response"]))
        # if not available, call the real sendall
        except KeyError:
            host, port = Mocket._address
            host = true_gethostbyname(host)

            if isinstance(self.true_socket,
                          true_socket) and self._secure_socket:
                try:
                    self = MocketSocket(sock=self)
                except TypeError:
                    ssl_context = self.kwargs.get("ssl_context")
                    server_hostname = self.kwargs.get("server_hostname")
                    self.true_socket = true_ssl_context.wrap_socket(
                        self=ssl_context,
                        sock=self.true_socket,
                        server_hostname=server_hostname,
                    )

            try:
                self.true_socket.connect((host, port))
            except (OSError, socket.error, ValueError):
                # already connected
                pass
            self.true_socket.sendall(data, *args, **kwargs)
            encoded_response = b""
            # https://github.com/kennethreitz/requests/blob/master/tests/testserver/server.py#L13
            while True:
                if not select.select([self.true_socket], [], [],
                                     0.1)[0] and encoded_response:
                    break
                recv = self.true_socket.recv(self._buflen)

                if not recv and encoded_response:
                    break
                encoded_response += recv

            # dump the resulting dictionary to a JSON file
            if Mocket.get_truesocket_recording_dir():

                # update the dictionary with request and response lines
                response_dict["request"] = req
                response_dict["response"] = hexdump.dump(encoded_response)

                with io.open(path, mode="w") as f:
                    f.write(
                        decode_from_bytes(
                            json.dumps(responses, indent=4, sort_keys=True)))

        # response back to .sendall() which writes it to the Mocket socket and flush the BytesIO
        return encoded_response
Example #16
0
    def true_sendall(self, data, *args, **kwargs):
        req = decode_from_bytes(data)
        # make request unique again
        req_signature = _hash_request(hasher, req)
        # port should be always a string
        port = text_type(self._port)

        # prepare responses dictionary
        responses = dict()

        if Mocket.get_truesocket_recording_dir():
            path = os.path.join(
                Mocket.get_truesocket_recording_dir(), Mocket.get_namespace() + ".json"
            )
            # check if there's already a recorded session dumped to a JSON file
            try:
                with io.open(path) as f:
                    responses = json.load(f)
            # if not, create a new dictionary
            except (FileNotFoundError, JSONDecodeError):
                pass

        try:
            try:
                response_dict = responses[self._host][port][req_signature]
            except KeyError:
                if hasher is not hashlib.md5:
                    # Fallback for backwards compatibility
                    req_signature = _hash_request(hashlib.md5, req)
                    response_dict = responses[self._host][port][req_signature]
                else:
                    raise
        except KeyError:
            # preventing next KeyError exceptions
            responses.setdefault(self._host, dict())
            responses[self._host].setdefault(port, dict())
            responses[self._host][port].setdefault(req_signature, dict())
            response_dict = responses[self._host][port][req_signature]

        # try to get the response from the dictionary
        try:
            try:
                encoded_response = hexdump.dehex(response_dict["response"])
            except TypeError:  # pragma: no cover
                # Python 2
                encoded_response = hexdump.restore(
                    encode_to_bytes(response_dict["response"])
                )
        # if not available, call the real sendall
        except KeyError:
            host, port = Mocket._address
            host = true_gethostbyname(host)

            try:
                self.true_socket.connect((host, port))
            except (OSError, socket.error, ValueError):
                # already connected
                pass
            self.true_socket.sendall(data, *args, **kwargs)
            encoded_response = b""
            # https://github.com/kennethreitz/requests/blob/master/tests/testserver/server.py#L13
            while True:
                if not select.select(
                    [self.true_socket], [], [], 0.1
                )[0] and encoded_response:
                    break
                recv = self.true_socket.recv(self._buflen)

                if not recv and encoded_response:
                    break
                encoded_response += recv

            # dump the resulting dictionary to a JSON file
            if Mocket.get_truesocket_recording_dir():

                # update the dictionary with request and response lines
                response_dict["request"] = req
                response_dict["response"] = hexdump.dump(encoded_response)

                with io.open(path, mode="w") as f:
                    f.write(
                        decode_from_bytes(
                            json.dumps(responses, indent=4, sort_keys=True)
                        )
                    )

        # response back to .sendall() which writes it to the mocket socket and flush the BytesIO
        return encoded_response
Example #17
0
T: 11:56:30.129    ...?........      BD B4 D3 3F FE 04 D3 0F FE DA BB BD
R: 11:56:30.129    .....>..          BD 8F FE 04 D3 3E 2E BD
""".split('\n')

x = "T: 11:56:28.622    ..........#.....  "

msg = " ".join([z[len(x):] for z in msg])

import logging
logging.basicConfig(level=logging.INFO)
import hexdump
import io

from PyCampbellCR1000.pycampbellcr1000.pakdecode import PakBusDecode

class pbByteIo(io.BytesIO):
    # pakbus assumes there is a timeout member...
    timeout = 1
    

link = pbByteIo(hexdump.dehex(msg))

pb = PakBusDecode(link)
packet = pb.read()
while packet:

    logging.debug ("packet is {}: {}".format(hexdump.dump(packet), packet))
    hdr, msg = pb.decode_packet(bytes(packet))
    logging.info ('HEAD: {}'.format(hdr))
    logging.info (' MSG: {}'.format(msg))
    packet = pb.read()
Example #18
0
import hexdump
from pytun import TunTapDevice, IFF_TAP

tun = TunTapDevice(name='rfc6214')

with open("captured_in.hex", "r") as the_file:
    hex = the_file.readline()

buf = hexdump.dehex(hex)

tun.write(buf)

buf = tun.read(tun.mtu)
hex = hexdump.dump(buf, 2, '')

print(hex)

with open('captured_out.hex', 'w') as the_file:
    the_file.write(hex)
Example #19
0
pref = """78 9f 3e 22 01 00 01 06 90 08 00 04 00 00 00 00 00 01 00 01 00 01 07 90 06 00 08 00 00 00 e4 04 00 00 00 00 00 00
e8 00 01 08 80 07 00 20 00 00 00 49 50 4d 2e 4d 69 63 72 6f 73 6f 66 74 20 53 63 68 65 64 75 6c 65 2e 4d 74 67 52 65 73
70 4e 00 55 0b 01 0d 80 04 00 02 00 00 00 02 00 02 00 01 05 80 03 00 0e 00 00 00 d8 07 01 00 10 00 17 00 1c 00 08 00 03
00 2e 01 01 20 80 03 00 0e 00 00 00 d8 07 01 00 10 00 17 00 1c 00 08 00 03 00 2e 01 01 03 90 06 00 88 00 00 00 02 00 00
00 02 01 7f 00 01 00 00 00 0c 00 00 00"""
ckey = "38 71 6b 6a 30 30 73 67 6d 34 66 00"
mid = "02 01 09 10 01 00 00 00 5d 00 00 00"
rtf = """59 00 00 00 b3 00 00 00 4c 5a 46 75 a9 be bb ed 87 00 0a 01 0d 03 43 74 65 78 74 01 f7 ff 02 a4 03 e4 05 eb 02
83 00 50 02 f3 06 b4 02 83 26 32 03 c5 02 00 63 68 0a c0 73 65 d8 74 30 20 07 13 02 80 7d 0a 80 08 cf 3f 09 d9 02 80
0a 84 0b 37 12 c2 01 d0 20 46 10 59 49 00 7d 18 20"""
postf = "00 00 00 f7 21"

dt = datetime(2008, 1, 16, 23, 28, 8)
prop = MapiProps()
prop.add(MapiEnum.PR_TNEF_CORRELATION_KEY, hexdump.dehex(ckey))
prop.add(MapiEnum.PR_RTF_COMPRESSED, hexdump.dehex(rtf))
obj = TNEF()
data = obj.std().messageClass(TNEF.CLASS_MRESPN).priority().dateSent(
    dt).dateModified(dt).msgProps(prop).dump()

res = hexdump.dehex(pref + ' ' + ckey + ' ' + mid + ' ' + rtf + ' ' + postf)

print "test2:", "OK" if checkBuffers(res, data, True) else "FAILED"

# TEST3
# test p7s builder

pubkey = """00 30 82 01 0A 02 82 01 01 00 BE 93 B1 7E E5 7E 12 AE 4A C8 3F 56 AA 2D F1 EE F8 99 50 61 8A F2 3B 43 3A
11 31 57 D7 B9 FE 71 56 CB C0 A3 57 10 FC 79 1A 34 26 0D A4 67 3C 53 64 18 8B 70 AA A9 12 52 13 16 98 5E 65 2D 98 B5
66 8E 70 07 55 D4 C3 56 B1 8D 1A 87 94 9A 96 33 57 16 3E BF DC A2 D1 EB 96 6D CD 46 13 40 2C 1C 1D AF 54 B5 55 49 47