def init_crcs_permutation(crc_params): crcs = [] for seed in crc_params: crc = crcmod.Crc(seed[1], initCrc=0x00, rev=True, xorOut=0x00) crc.name = seed[0] crc.permutation = True crc.w = int(width(crc.poly) / 4) crcs.append(crc) crc = crcmod.Crc(seed[1], initCrc=0x00, rev=False, xorOut=0x00) crc.name = seed[0] crc.permutation = True crc.w = int(width(crc.poly) / 4) crcs.append(crc) crc = crcmod.Crc(seed[1], initCrc=0x00, rev=True, xorOut=0xffffffff) crc.name = seed[0] crc.permutation = True crc.w = int(width(crc.poly) / 4) crcs.append(crc) crc = crcmod.Crc(seed[1], initCrc=0x00, rev=False, xorOut=0xffffffff) crc.name = seed[0] crc.permutation = True crc.w = int(width(crc.poly) / 4) crcs.append(crc) return crcs
def __init__(self): self.buf = collections.deque(maxlen=1000) self.state = 'IDLE' self.crc16 = crcmod.Crc(0x18005, 0x3AA3) self.crc32 = crcmod.Crc(0x104C11DB7, 0x3AA3) self.aes = AESCodec.AESCodec(DEFAULT_KEY) self.header = None self.parsed_size = 0
def __init__(self, **cosa): crci = 22069 self.crc = crcmod.Crc(0x11021, crci, False, 0) timeout = 1.0 if 'timeout' in cosa: timeout = cosa['timeout'] if 'indip' in cosa: # socket tcp self.mdp = 1400 self.uart = _SOCK(cosa['indip'], 50741, timeout) if not self.uart.a_posto(): self.uart.close() self.uart = None else: self.mdp = 1024 # porta seriale brate = 115200 if 'brate' in cosa: brate = cosa['brate'] cfh = False if 'cfh' in cosa: cfh = cosa['cfh'] if 'porta' in cosa: # classica try: self.uart = serial.Serial(cosa['porta'], brate, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE, timeout, rtscts=cfh) self.prm = self.uart.getSettingsDict() except serial.SerialException as err: print(err) self.uart = None except ValueError as err: print(err) self.uart = None else: # usb try: self.uart = serial.serial_for_url( 'hwgrep://%s:%s' % (cosa['vid'], cosa['pid']), baudrate=brate, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=timeout, rtscts=cfh) self.prm = self.uart.getSettingsDict() except serial.SerialException as err: print(err) self.uart = None
def dot11crc(pkt): crc_fun = crcmod.Crc(0b100000100110000010001110110110111, rev=True, initCrc=0x0, xorOut=0xFFFFFFFF) crc_fun.update(str(pkt)) crc = struct.pack('<I', crc_fun.crcValue) return crc
def calculate_crc64(data): _POLY = 0x142F0E1EBA9EA3693 _XOROUT = 0XFFFFFFFFFFFFFFFF crc64 = crcmod.Crc(_POLY, initCrc=0, xorOut=_XOROUT) crc64.update(data) return crc64.crcValue
def __init__(self, porta=None, logga=False): # prima di sincro! bl.CY_BL_SERVICE.__init__(self) self.sincro = { # cypress bootloader service 'blr': queue.Queue(), # list of devices 'scan': queue.Queue(), # user list of devices 'user': None, # signaled by gap_auth_req_cb 'authReq': threading.Event(), # signaled by gap_passkey_entry_request_cb 'pairReq': threading.Event(), # command response 'rsp': queue.Queue() } self.priv = None self.crc = crcmod.Crc(0x11021, 0xC681, False, 0x0000) self.srvdata = None CY567x.CY567x.__init__(self, porta=porta) self.mio = None self.disc = None if logga: self.logger = utili.LOGGA('ghost') else: self.logger = utili.LOGGA() try: if not self.is_ok(): raise utili.Problema('not OK') if not self.init_ble_stack(): raise utili.Problema('err init') if not self.set_device_io_capabilities('KEYBOARD DISPLAY'): raise utili.Problema('err capa') if not self.set_local_device_security('3'): raise utili.Problema('err security') mio = self.my_address() if mio is None: raise utili.Problema('err bdaddr') self.mio = mio self.logger.debug('io sono ' + utili.str_da_mac(mio)) except utili.Problema as err: self.logger.critical(str(err))
def extract(self, sample): r2 = r2pipe.open(self.file_name) r2.cmd('aaa') # analyse all sample.functions = [] for r2_func in json.loads( r2.cmd('aflj')): # list all functions (to JSON) sample_func = SampleFunction() sample_func.offset = r2_func['offset'] sample_func.size = r2_func['size'] sample_func.real_size = r2_func['realsz'] sample_func.name = r2_func['name'] sample_func.calltype = r2_func['calltype'] sample_func.cc = r2_func['cc'] sample_func.cost = r2_func['cost'] sample_func.ebbs = r2_func['ebbs'] sample_func.edges = r2_func['edges'] sample_func.indegree = r2_func['indegree'] sample_func.nargs = r2_func['nargs'] sample_func.nbbs = r2_func['nbbs'] sample_func.nlocals = r2_func['nlocals'] sample_func.outdegree = r2_func['outdegree'] sample_func.type = r2_func['type'] instructions = json.loads( r2.cmd('pdj @' + r2_func['name'])) # disassemble (to JSON) sample_func.opcodes = [ instr['opcode'] for instr in instructions if 'opcode' in instr ] cleaned_opcodes = [ self._clean_ops(opcode) for opcode in sample_func.opcodes ] data = (''.join(sample_func.opcodes)).encode('utf-8') sample_func.opcodes_sha256 = hashlib.sha256(data).hexdigest() sample_func.opcodes_crc32 = crcmod.Crc(0x104c11db7).new( data).hexdigest().lower() cleaned_data = (''.join(cleaned_opcodes)).encode('utf-8') sample_func.cleaned_opcodes_sha256 = hashlib.sha256( cleaned_data).hexdigest() sample_func.cleaned_opcodes_crc32 = crcmod.Crc(0x104c11db7).new( cleaned_data).hexdigest().lower() sample.functions.append(sample_func)
def post_build(self, p, pay): p += pay if self.digest is None: crc32 = crcmod.Crc(0x104c11db7, initCrc=0, xorOut=0xFFFFFFFF) crc32.update(str(p)) c = bytes(bytearray.fromhex("%08x" % crc32.crcValue)) p = p[:2] + c + p[6:] #ck = checksum(p) #p = p[:2]+"\x00\x00"+chr(ck>>8)+chr(ck&0xff)+p[6:] return p
def __init__(self, init_crc=0): self.crc64 = crcmod.Crc(self._POLY, initCrc=init_crc, rev=True, xorOut=self._XOROUT) self.crc64_combineFun = mkCombineFun(self._POLY, initCrc=init_crc, rev=True, xorOut=self._XOROUT)
def writeMessage(self, message): c = crcmod.Crc(0x11021) c.update(message) message += c.digest() #the bootloader needs escaping message = message.replace('\\', '\\\\') enc = "\\5" + message + "\\2" data = enc.replace('\\', '\\\\') #print "writing",list(enc) self.ser.write(data)
def calculate_crc64(data): """计算文件的MD5 :param data: 数据 :return 数据的MD5值 """ _POLY = 0x142F0E1EBA9EA3693 _XOROUT = 0XFFFFFFFFFFFFFFFF crc64 = crcmod.Crc(_POLY, initCrc=0, xorOut=_XOROUT) crc64.update(data) return crc64.crcValue
def test_crc64_combine(self): _POLY = 0x142F0E1EBA9EA3693 _XOROUT = 0XFFFFFFFFFFFFFFFF string_a = oss2.to_bytes('12345') string_b = oss2.to_bytes('67890') combine_fun = oss2.crc64_combine.mkCombineFun(_POLY, 0, True, _XOROUT) crc64_a = crcmod.Crc(_POLY, initCrc=0, xorOut=_XOROUT) crc64_a.update(string_a) crc1 = crc64_a.crcValue crc64_b = crcmod.Crc(_POLY, initCrc=0, xorOut=_XOROUT) crc64_b.update(string_b) crc2 = crc64_b.crcValue crc_combine = combine_fun(crc1, crc2, len(string_b)) crc64_c = crcmod.Crc(_POLY, initCrc=0, xorOut=_XOROUT) crc64_c.update(string_a + string_b) crc_raw = crc64_c.crcValue self.assertEqual(crc_combine, crc_raw)
def __init__(self, sourceID=0, destID=0x0A): super().__init__() self._controller = None self.com_ports = self.get_ressources() self.SYNC = 0x16 #Sync byte self.STX = 0x02 #Start byte self.message_len_without_data = 9 self.sourceID = sourceID self.destID = destID logger.debug( f'Serial object initialized with sourceID {sourceID} and destID {destID}' ) self.crc16 = crcmod.Crc(0x18005, initCrc=0x0000)
def Calculate(self, string): if self.name == "md5": hash = hashlib.md5(string).hexdigest() elif self.name == "sha1": hash = hashlib.sha1(string).hexdigest() elif self.name == "crc": crc32 = crcmod.Crc(0x104c11db7, initCrc=0, xorOut=0xFFFFFFFF) crc32.update(string) hash = crc32.hexdigest() elif self.name == "murmur": hash = mmh3.hash(string) return hash
def init_crcs(crc_params): crcs = [] for item in crc_params: crc = crcmod.Crc(item[1], initCrc=item[2], rev=item[3], xorOut=item[4]) test = crc.copy() crc.name = item[0] crc.permutation = False crc.w = int(width(crc.poly) / 4) test.update(b"123456789") if test.crcValue != item[5]: print("Test for %s failed: expected: %x got: %x" % (item[0], item[5], test.crcValue)) sys.exit() crcs.append(crc) return crcs
def _crc_block(self, block): """ CRC's a block of 32 bit words This is necessary as the STM32F4's CRC engine operates 32 bits at a time """ crc32 = crcmod.Crc(0x104c11db7, initCrc=0xffffffff, rev=False) for idx in range(0, len(block), 4): tmpblock = block[idx:idx + 4] #Make sure that the block is 4 octets long, if not, pad it if not len(tmpblock) == 4: tmpblock += '\xff' * (4 - len(tmpblock)) tmp = struct.unpack("<I", tmpblock)[0] crc32.update(struct.pack(">I", tmp)) return crc32.crcValue
def __init__(self, input_file, output_file, max_rec_size, fill_space, header_loc, in_valid_mask): self.mot_filename = input_file self.out_filename = output_file self.max_block_size = max_rec_size self.max_fill_space = fill_space self.header_location = header_loc self.input_valid_mask = in_valid_mask self.header_bytes_left = self.FL_LI_STRUCT_SIZE self.fileheader = "" self.filesize = 0 #Used for CRC - CCITT - x^16 + x^12 + x^5 + 1 self.g16 = 0x11021 self.crc_init = 0x1D0F #CRC used for the entire file - Image CRC self.file_crc = crcmod.Crc(self.g16, self.crc_init, 0) #CRC used for each block self.crc = crcmod.mkCrcFun(self.g16, self.crc_init, 0)
def sketch_cm(): with open(filename_cm_ip) as f: for line in f: regex_src_ip, regex_dst_ip = re.search( "\\d+\\.\\d+\\.\\d+\\.\\d+,\\d+\\.\\d+\\.\\d+\\.\\d+", line).group(0).split(",") crc32_cm_2 = crcmod.Crc(0x104c11db7, initCrc=0x00000000, xorOut=0xFFFFFFFF) try: crc32_cm_2.update(socket.inet_aton(regex_src_ip)) crc32_cm_2.update(socket.inet_aton(regex_dst_ip)) except socket.error: continue crc32_cm_2_hex = crc32_cm_2.hexdigest() crc32_cm_2_dec = int(crc32_cm_2_hex, 16) crc32_cm_2_mod = crc32_cm_2_dec % 131072 sketch_cm = str( subprocess.check_output([ "echo \"register_read cm_register_final " + str(crc32_cm_2_mod) + " \" | /usr/local/bin/simple_switch_CLI --json " + arg_json ], shell=True)) final_cm = re.search(" \\d+", sketch_cm).group(0)[1:] if os.path.exists(filename_cm_final): append_write = 'a' # append if already exists else: append_write = 'w' # make a new file if not file_write = open(filename_cm_final, append_write) file_write.write(line.rstrip() + " " + final_cm + "\n") file_write.close()
def _stato_1(self, rx): if self.nega: rx = ~rx & 0xFF self.pkt.append(rx) self.nega = False elif _PROTO._INIZIO_TRAMA == rx: self.pkt = bytearray() elif _PROTO._FINE_TRAMA == rx: # almeno: comando + crc if len(self.pkt) >= 2 + 2: crc = crcmod.Crc(0x11021, self.crc_ini, False, 0x0000) crc.update(self.pkt) msgcrc = bytes(crc.digest()) if msgcrc[0] == msgcrc[1] == 0: # tolgo crc del self.pkt[-1] del self.pkt[-1] intest = struct.unpack('<H', self.pkt[:2]) self.rsp = { 'tipo': 'rsp', 'cmd': intest[0], 'rsp': self.pkt[2:] } self.diario.info('pacchetto ok') return True else: self.diario.error('crc sbagliato') else: self.diario.error('pochi byte') elif _PROTO._CARATTERE_DI_FUGA == rx: self.nega = True else: self.pkt.append(rx) return False
def crea_pkt(self, msg): """ impacchetta il messaggio :param msg: bytearray contenente il messaggio :return: bytearray da trasmettere """ crc = crcmod.Crc(0x11021, self.crc_ini, False, 0x0000) crc.update(msg) msgcrc = bytes(crc.digest()) # Compongo il pacchetto pkt = bytearray([_PROTO._INIZIO_TRAMA]) for x in msg: self._aggiungi(pkt, x) self._aggiungi(pkt, msgcrc[0]) self._aggiungi(pkt, msgcrc[1]) pkt.append(_PROTO._FINE_TRAMA) return pkt
import crcmod crc16 = crcmod.mkCrcFun(0x1A2EB) print(f"0x{format(crc16(bytes()), '04X')}") print(f"0x{format(crc16(bytes([0])), '04X')}") crc8 = crcmod.mkCrcFun(0x1D7) print(f"0x{format(crc8(bytes()), '02X')}") print(f"0x{format(crc8(bytes([0xFF])), '02X')}") with open('./crc.c', 'w') as c_file: crcmod.Crc(0x1A2EB).generateCode('crc16', c_file, 'uint8_t', 'uint16_t') crcmod.Crc(0x1D7).generateCode('crc8', c_file, 'uint8_t', 'uint8_t')
def make_crc(): return crcmod.Crc(0x11021, 0)
def main(): resource_dir = os.path.dirname(os.path.abspath(__file__)) args = get_argparser().parse_args() if args.action in ("uf2", "dfu"): device = None else: try: vid, pid = args.device device = FX2Device(vid, pid) except FX2DeviceError as e: raise SystemExit(e) try: if device is not None: if args.bootloader: bootloader_ihex = os.path.join(resource_dir, "boot-cypress.ihex") device.load_ram(input_data(open(bootloader_ihex))) elif args.stage2: device.load_ram(input_data(args.stage2)) if args.action == "load": device.load_ram(input_data(args.firmware, args.format)) elif args.action == "read_ram": device.cpu_reset(True) data = device.read_ram(args.address, args.length) output_data(args.file, data, args.format, args.address) elif args.action == "write_ram": data = input_data(args.file or args.data, args.format, args.offset) device.cpu_reset(True) for address, chunk in data: device.write_ram(address, chunk) elif args.action == "read_xram": device.cpu_reset(False) data = device.read_ext_ram(args.address, args.length) output_data(args.file, data, args.format, args.address) elif args.action == "write_xram": data = input_data(args.file or args.data, args.format, args.offset) device.cpu_reset(False) for address, chunk in data: device.write_ext_ram(address, chunk) elif args.action == "read_eeprom": device.cpu_reset(False) data = device.read_boot_eeprom(args.address, args.length, args.address_width) output_data(args.file, data, args.format, args.address) elif args.action == "write_eeprom": data = input_data(args.file or args.data, args.format, args.offset) device.cpu_reset(False) for address, chunk in data: device.write_boot_eeprom(address, chunk, args.address_width, chunk_size=min( args.page_size * 4, 64), page_size=args.page_size) elif args.action == "reenumerate": device.reenumerate() elif args.action == "program": device.cpu_reset(False) if args.firmware: firmware = input_data(args.firmware, args.format) else: firmware = [] config = FX2Config(args.vendor_id, args.product_id, args.device_id, args.disconnect, args.i2c_400khz) for address, chunk in firmware: config.append(address, chunk) image = config.encode() device.write_boot_eeprom(0, image, args.address_width, chunk_size=min(args.page_size * 4, 64), page_size=args.page_size) image = device.read_boot_eeprom(0, len(image), args.address_width) if FX2Config.decode(image) != config: raise SystemExit("Verification failed") elif args.action == "update": device.cpu_reset(False) if args.firmware: firmware = input_data(args.firmware, args.format) elif args.no_firmware: firmware = [] else: firmware = None old_image = read_entire_boot_eeprom(device, args.address_width) config = FX2Config.decode(old_image) if args.vendor_id is not None: config.vendor_id = args.vendor_id if args.product_id is not None: config.product_id = args.product_id if args.device_id is not None: config.device_id = args.device_id if args.disconnect is not None: config.disconnect = args.disconnect if args.i2c_400khz is not None: config.i2c_400khz = args.i2c_400khz if firmware is not None: config.firmware = [] for (addr, chunk) in firmware: config.append(addr, chunk) new_image = config.encode() for (addr, chunk) in diff_data(old_image, new_image): device.write_boot_eeprom(addr, chunk, args.address_width, chunk_size=min( args.page_size * 4, 64), page_size=args.page_size) new_image = device.read_boot_eeprom(0, len(new_image), args.address_width) if FX2Config.decode(new_image) != config: raise SystemExit("Verification failed") elif args.action == "dump": device.cpu_reset(False) image = read_entire_boot_eeprom(device, args.address_width) config = FX2Config.decode(image) if not config: print("Device erased") else: print("USB VID: {:04x}\n" " PID: {:04x}\n" " DID: {:04x}\n" "Disconnect: {}\n" "I2C clock: {}\n" "Firmware: {}".format( config.vendor_id, config.product_id, config.device_id, "enabled" if config.disconnect else "disabled", "400 kHz" if config.i2c_400khz else "100 kHz", "present" if len(config.firmware) > 0 else "absent"), file=sys.stderr) if args.firmware and len(config.firmware) > 0: output_data(args.firmware, config.firmware, args.format) elif args.action == "uf2": config = FX2Config(args.vendor_id, args.product_id, args.device_id, args.disconnect, args.i2c_400khz) for address, chunk in input_data(args.firmware_file, args.format): config.append(address, chunk) image = config.encode() UF2_MAGIC_START_0 = 0x0A324655 UF2_MAGIC_START_1 = 0x9E5D5157 UF2_MAGIC_END = 0x0AB16F30 UF2_FLAG_NOT_MAIN_FLASH = 0x00000001 UF2_FLAG_FILE_CONTAINER = 0x00001000 UF2_FLAG_FAMILY_ID_PRESENT = 0x00002000 UF2_FAMILY_CYPRESS_FX2 = 0x5a18069b block_size = 256 num_blocks = (len(image) + block_size - 1) // block_size block_no = 0 while len(image) > 0: uf2_block = struct.pack("<IIIIIIII", UF2_MAGIC_START_0, UF2_MAGIC_START_1, UF2_FLAG_FAMILY_ID_PRESENT, block_no * block_size, block_size, block_no, num_blocks, UF2_FAMILY_CYPRESS_FX2) uf2_block += image[:block_size] uf2_block += b"\x00" * (512 - 4 - len(uf2_block)) uf2_block += struct.pack("<I", UF2_MAGIC_END) args.uf2_file.write(uf2_block) image = image[block_size:] block_no += 1 elif args.action == "dfu": config = FX2Config(args.vendor_id, args.product_id, args.device_id, args.disconnect, args.i2c_400khz) for address, chunk in input_data(args.firmware_file, args.format): config.append(address, chunk) image = config.encode() suffix = struct.pack( ">BBBBHHHH", struct.calcsize(">LBBBBHHHH"), 0x44, 0x46, 0x55, # ucDfuSignature 0x0100, # bcdDFU args.vendor_id, args.dfu_product_id or args.product_id, args.device_id) image += bytes(reversed(suffix)) crc = crcmod.Crc(poly=0x104c11db7, initCrc=0xffffffff) crc.update(image) image += struct.pack("<L", crc.crcValue) args.dfu_file.write(image) except usb1.USBErrorPipe: if args.action in ["read_eeprom", "write_eeprom"]: raise SystemExit("Command not acknowledged (wrong address width?)") else: raise SystemExit("Command not acknowledged") except usb1.USBErrorTimeout: if args.action in ["read_eeprom", "write_eeprom"]: raise SystemExit("Command timeout (bootloader not loaded?)") else: raise SystemExit("Command timeout") except ValueError as e: raise SystemExit(str(e)) finally: if device is not None: device.usb_context.close()
def main(): import sys import os import wave from optparse import OptionParser import crcmod from hexdump import hexdump import binascii import zlib usage = "usage: %prog [options] FILENAME" parser = OptionParser(usage) parser.add_option("-d", "--dump", help="dump configuration to text", action="store_true", dest="dump") parser.add_option("-s", "--summary", help="summarize DFU as human readable text", action="store_true", dest="summary") parser.add_option("-o", "--output", dest="outfile", help="write data to OUTFILE") parser.add_option("-u", "--unpack", help="unpack Samples to UNPACK directory", dest="unpack") parser.add_option("-p", "--pack", help="pack Samples to PACK directory", dest="pack") parser.add_option("-r", "--replace", help="pack REPLACE directory of samples to DFU " + \ "(overwrites contents, either padded or clipped to original size)", dest="replace") parser.add_option("-R", "--raw", help="use '.raw' sample files (rather than '.wav')", action="store_true", dest="raw") parser.add_option("-t", "--test", help="scripted test, dev use only", action="store_true", dest="test") (options, args) = parser.parse_args() if len(args) != 1: parser.error("FILE not specified") print("Opening:", args[0]) infile = open(args[0], "rb") if not infile: sys.exit("Unable to open FILE for reading") else: data = infile.read() infile.close() if data: config = DFU.parse(data) if options.summary: print("Number of samples:", config['block']['total']) total = 0 btotal = 0 a_count = 1 b_count = 1 for sample in config['block']['samples']: print("Sample %d-%d: %s (%s bytes, %f sec)" % \ (a_count, b_count, sample['length'], sample['bytes'], int(sample['length'])/32000)) total += int(sample['length']) btotal += int(sample['bytes']) if b_count == config['block']['elements'][a_count - 1]: a_count += 1 b_count = 1 while (a_count <= len(config['block']['elements']) and \ config['block']['elements'][a_count-1] == 0): a_count += 1 else: b_count += 1 print("Total length: %d bytes" % btotal) print("Total length: %f sec" % (total / 32000)) if options.unpack: path = os.path.join(os.getcwd(), options.unpack) if os.path.exists(path): sys.exit("Directory %s already exists" % path) os.mkdir(path) a_count = 1 b_count = 1 for data in config['block']['data']: unpacked = unpack_samples(data.data) if options.raw: name = os.path.join( path, "sample-{0:0=2d}-{1:0=1d}.raw".format( a_count, b_count)) outfile = open(name, "wb") for value in unpacked: outfile.write(value.to_bytes(2, byteorder='little')) outfile.close() else: name = os.path.join( path, "sample-{0:0=2d}-{1:0=1d}.wav".format( a_count, b_count)) outfile = wave.open(name, "wb") outfile.setsampwidth(2) outfile.setnchannels(1) outfile.setframerate(32000) for value in unpacked: outfile.writeframesraw( value.to_bytes(2, byteorder='big')) outfile.close() if b_count == config['block']['elements'][a_count - 1]: a_count += 1 b_count = 1 while (a_count <= len(config['block']['elements']) and \ config['block']['elements'][a_count-1] == 0): a_count += 1 else: b_count += 1 if options.pack or options.replace: if options.replace: path = os.path.join(os.getcwd(), options.replace) else: path = os.path.join(os.getcwd(), options.pack) if not os.path.exists(path): sys.exit("Directory %s does not exist" % path) count = 1 a_count = 1 b_count = 1 if options.pack: # create more than enough empty slots Empty = Array( 200, Struct( "length" / Computed(0), "bytes" / Computed(0), )) empty = Empty.parse(b"") config['block']['samples'] = empty Empty = Array(200, Struct("data" / Bytes(0), )) empty = Empty.parse(b"") config['block']['data'] = empty for sample in config['block']['samples']: unpacked = [] infile = None if options.raw: name = os.path.join( path, "sample-{0:0=2d}-{1:0=1d}.raw".format( a_count, b_count)) if os.path.isfile(name): infile = open(name, "rb") if infile: if options.pack: file_stats = os.stat(name) length = file_stats.st_size / 2 else: length = sample['length'] if length > 0xffff: length = 0xffff for temp in range(length): value = infile.read(2) unpacked.append( int.from_bytes(value, byteorder='little')) infile.close() else: name = os.path.join( path, "sample-{0:0=2d}-{1:0=1d}.wav".format( a_count, b_count)) if os.path.isfile(name): infile = wave.open(name, "rb") if infile: # checks if infile.getnchannels() != 1: sys.exit("Samples should be 1 channel: %s" % name) if infile.getsampwidth() != 2: sys.exit("Samples should be 16 bit: %s" % name) if infile.getframerate() != 32000: sys.exit("Samples should be 3200KHz: %s" % name) if options.pack: length = infile.getnframes() else: length = sample['length'] if length > 0xffff: length = 0xffff for temp in range(length): value = infile.readframes(1) unpacked.append( int.from_bytes(value, byteorder='big')) infile.close() if len(unpacked): config['block']['data'][count - 1].data = bytes( pack_samples(unpacked)) count += 1 if options.pack: if not infile: # file not found, advanced to next element count -= 1 config['block']['elements'][a_count - 1] = b_count - 1 config['block']['total'] = count - 1 a_count += 1 b_count = 1 if a_count == 13: # all elements done, truncate data arrays config['block']['samples'] = config['block'][ 'samples'][:count - 1] config['block']['data'] = config['block'][ 'data'][:count - 1] break else: config['block']['samples'][count - 2].length = length config['block']['samples'][count-2].bytes = \ len(config['block']['data'][count-2].data) b_count += 1 elif b_count == config['block']['elements'][a_count - 1]: a_count += 1 b_count = 1 while (a_count <= len(config['block']['elements']) and \ config['block']['elements'][a_count-1] == 0): a_count += 1 else: b_count += 1 if options.dump: print(config) if options.outfile: # re-calc inner checksum data = Block.build(config['block']) crc32 = crcmod.Crc(0x104c11db7, rev=False, initCrc=0, xorOut=0xFFFFFFFF) crc32.update(data) config['checksum'] = crc32.crcValue ^ 0xFFFFFFFF # re-calc outer checksum data = DFU.build(config) crc32 = crcmod.Crc(0x104c11db7, rev=True, initCrc=0, xorOut=0xFFFFFFFF) crc32.update(data) outfile = open(options.outfile, "wb") if outfile: outfile.write(data) outfile.write( (crc32.crcValue ^ 0xFFFFFFFF).to_bytes(4, byteorder='little')) outfile.close
def __init__(self, poly, initval): self.crc = crcmod.Crc(poly, initval) logging.getLogger('app').info( 'Init CRC with poly=0x{:X} initval=0x{:X}'.format(poly, initval))
def getInterface(filename): if len(filename) < 0: print "Enter the packet" sys.exit() file = open(filename, "r") filelen = len(file.read()) - 1 file.seek(28, 0) version = int(file.read(1), 16) if version != 4: print "Invalid IP version" sys.exit() headerLen = int(file.read(1), 16) * 4 if headerLen < 20: print "Header length is less than 20 bytes" sys.exit() # file.seek(32,0) # packetLen=int(file.read(4),16) # if (filelen/2)-14 != packetLen: # print "Packet length does not match Invalid packet" # sys.exit() file.seek(44, 0) ttl = int(file.read(2), 16) if ttl < 1: print "Invalid packet. Discarding it" sys.exit() file.seek(0, 0) crc32 = crcmod.Crc(0x104c11db7, initCrc=0, xorOut=0xFFFFFFFF) crc32.update(str(int(file.read(108), 16))) crc = file.read(8) if crc != crc32.hexdigest(): print "Invalid packet. Discarding it" sys.exit() print hex(crc32.crcValue) print crc32.hexdigest() file.seek(52, 0) sourceIp = str(int(file.read(2), 16)) + "." + str(int( file.read(2), 16)) + "." + str(int(file.read(2), 16)) + "." + str( int(file.read(2), 16)) destIp = str(int(file.read(2), 16)) + "." + str(int( file.read(2), 16)) + "." + str(int(file.read(2), 16)) + "." + str( int(file.read(2), 16)) interface = 0 file.seek(24, 0) ethType = int(file.read(4)) if ethType == 800: file.seek(46, 0) protocol = int(file.read(2), 16) if protocol == 6: file.seek(28 + headerLen * 2, 0) sourcePort = int(file.read(4), 16) destPort = int(file.read(4), 16) if sourcePort == 80: print "flow 1: IP TCP HTTP" elif sourcePort == 443: print "flow 2:IP TCP HTTPS" elif protocol == 11: file.seek(headerLen * 2, 0) sourcePort = int(file.read(4), 16) destPort = int(file.read(4), 16) if sourcePort == 80: print "flow 3:IP UDP HTTP" elif sourcePort == 443: print "flow 4:IP UDP HTTPS" elif protocol == 01: file.seek(headerLen * 2, 0) sourcePort = int(file.read(4), 16) destPort = int(file.read(4), 16) if sourcePort == 80: print "flow 5:ICMP echo reply" elif sourcePort == 443: print "flow 6:ICMP" file.close() with open("routerVssource.csv", "r") as f: for line in f: values = [x.rstrip('\n') for x in line.split(',')] address = ipaddress.ip_network(values[0].decode('utf-8')) if ipaddress.ip_address( sourceIp.decode('utf-8')) in address.hosts(): destFile = values[1] sourceNw = values[0] if ipaddress.ip_address(destIp.decode('utf-8')) in ipaddress.ip_network( sourceNw.decode('utf-8')).hosts(): print "Receiver and sender are in same network" else: filename = "routing_table_" + destFile + ".txt" flag = 0 print filename with open(filename, "r") as f: for line in f: if flag == 0: values = [x.rstrip('\n') for x in line.split(',')] if (values[1] != values[2]): if ipaddress.ip_address(destIp.decode( 'utf-8')) in ipaddress.ip_network( values[2].decode('utf-8')).hosts( ) and sourceIp == values[0]: flag = 1 print "source is", sourceIp print "Destination is", destIp print "interface is", values[3] print "next hop is", values[1] return values[3] if flag == 0: print "forwarding through default gateway" return -1
def __init__(self, init_crc=0): self.crc64 = crcmod.Crc(self._POLY, initCrc=init_crc, rev=True, xorOut=self._XOROUT)
def runTest(self): print "Test INT L45 Digest transit device - add and encode 2hop info" prepare_int_l45_bindings() config = SwitchConfig(self, params) # Enable INT transit processing self.client.switch_api_dtel_int_transit_enable(device) # create a packet coming from INT src - i.e. # - It has INT meta header, but no INT data # Each transit device will fill the data payload = 'int l45' pkt = simple_udp_packet(eth_dst=params.mac_self, eth_src=params.mac_nbr[0], ip_id=0, ip_dst=params.ipaddr_nbr[1], ip_src=params.ipaddr_nbr[0], ip_ttl=64, udp_sport=101, with_udp_chksum=False, udp_payload=payload) int_pkt = int_l45_src_packet(test=self, int_inst_mask=0xDC00, int_inst_cnt=5, pkt=pkt) exp_pkt = simple_udp_packet(eth_dst=params.mac_nbr[1], eth_src=params.mac_self, ip_id=0, ip_dst=params.ipaddr_nbr[1], ip_src=params.ipaddr_nbr[0], ip_ttl=63, udp_sport=101, with_udp_chksum=False, udp_payload=payload) exp_pkt = int_l45_src_packet(test=self, int_inst_mask=0xDC00, int_inst_cnt=5, pkt=exp_pkt) # add 1 hop info to the packet int_pkt = int_l45_packet_add_hop_info(Packet=int_pkt, val=5) int_pkt = int_l45_packet_add_hop_info(Packet=int_pkt, val=0x0) int_pkt = int_l45_packet_add_hop_info(Packet=int_pkt, val=0x0) int_pkt = int_l45_packet_add_hop_info(Packet=int_pkt, val=0x0) int_pkt = int_l45_packet_add_hop_info(Packet=int_pkt, val=0x22222222, incr_cnt=1) # add Digest headers digest = 0xab12 digest_pkt = int_l45_packet_add_update_digest(Packet=int_pkt, encoding=digest) exp_pkt = int_l45_packet_add_hop_info(Packet=exp_pkt, val=0x5) exp_pkt = int_l45_packet_add_hop_info(Packet=exp_pkt, val=0x0) exp_pkt = int_l45_packet_add_hop_info(Packet=exp_pkt, val=0x0) exp_pkt = int_l45_packet_add_hop_info(Packet=exp_pkt, val=0x0) exp_pkt = int_l45_packet_add_hop_info(Packet=exp_pkt, val=0x22222222, incr_cnt=1) exp_pkt = int_l45_packet_add_hop_info(Packet=exp_pkt, val=0x7FFFFFFF) exp_pkt = int_l45_packet_add_hop_info(Packet=exp_pkt, val=0x7FFFFFFF) exp_pkt = int_l45_packet_add_hop_info(Packet=exp_pkt, val=0x7FFFFFFF) exp_pkt = int_l45_packet_add_hop_info(Packet=exp_pkt, val=int_port_ids_pack( swports[0], swports[1])) exp_pkt = int_l45_packet_add_hop_info(Packet=exp_pkt, val=switch_id, incr_cnt=1) # add Digest headers exp_encoding = digest ^ (switch_id - 0) # latency unknown exp_pkt = int_l45_packet_add_update_digest( Packet=exp_pkt, encoding=exp_encoding) #exp_encoding will be ignore # set quantization shift self.client.switch_api_dtel_latency_quantization_shift(device=device, quant_shift=0) try: send_packet(self, swports[0], str(digest_pkt)) (rcv_encoding, rcv_metadata, nrcv) = verify_int_packet(test=self, pkt=exp_pkt, port=swports[1], digest=True, ignore_hop_indices=[3, 4, 5]) rcv_latency = rcv_metadata[2] - rcv_metadata[1] ports = nrcv.getlayer(INT_hop_info, 2) # ports # fields must be extended up to their length, then concatenate v = rcv_latency # 32 bit latency v = (v << 9) | ((ports.val >> 16) & 0x1ff) # 9 bits ingress port v = (v << 9) | (ports.val & 0x1ff) # 9 bits egress ports # we ignore switch ID in encoding # v = (v << 32) | (switch_id) # 32 bits switchid v = (v << 16) | digest v_len = ceil((32 + 9 + 9 + 16) / 4.0) v_hex = '%x' % v if (v_len % 2 == 1): v_len += 1 while (len(v_hex) < v_len): v_hex = '0' + v_hex crc32 = crcmod.Crc(0x18005, initCrc=0, xorOut=0x0000) crc32.update(bytes(bytearray.fromhex(v_hex))) exp_encoding = crc32.crcValue print("expected %x received %x latency %d\n" % (exp_encoding, rcv_encoding, rcv_latency)) self.assertTrue(rcv_encoding == exp_encoding, "Digest encoding doesn't match.") verify_no_other_packets(self) finally: ### Cleanup cleanup_int_l45_bindings() self.client.switch_api_dtel_int_transit_disable(device) config.cleanup(self)
def __init__(self): self.crc32c = crcmod.Crc(0x11EDC6F41, initCrc=0, xorOut=0xFFFFFFFF)
def __init__(self): self.buf = collections.deque(maxlen=1000) self.state = 'IDLE' self.crc16 = crcmod.Crc(0x18005, 0x3AA3) self.crc32 = crcmod.Crc(0x104C11DB7, 0x3AA3) self.header = None