def dev_write(self, line): self.dprint(0, "CMD: " + line) fid = line.split(":")[0] length = line.split(":")[1] data = line.split(":")[2] self.server.write_can(CANMessage.init_data(int(fid), int(length), bytes.fromhex(data)[:int(length)])) return "Sent!"
def handle(self): # self.request is the TCP socket connected to the client print("TCP2CAN connected to " + str(self.server.prt)) self.server.selfx.set_error_text("TCP2CAN connected to " + str(self.server.prt)) self.server._access_in.clear() self.server._access_out.clear() while True: # Get header first data = self.request.recv(4) if data[0:1] == b'c': # Header if data[1] == 1: # Request for frames while self.server._access_out.is_set(): time.sleep(0.0001) self.server._access_out.set() ready = len(self.server.CANList_out) sz = struct.pack("!H", ready) send_msg = b'c\x02' + sz self.request.sendall(send_msg) send_msg = b'' for can_msg in self.server.CANList_out: # 16 byte send_msg += b'ct\x03' + (b'\x00' * (4 - len(can_msg.frame_raw_id))) + can_msg.frame_raw_id + can_msg.frame_raw_length + can_msg.frame_raw_data + (b'\x00' * (8 - can_msg.frame_length)) if ready > 0: self.request.sendall(send_msg) self.server.CANList_out = [] self.server._access_out.clear() elif data[1] == 4: # Incoming frames... ready = struct.unpack("!H", data[2:4])[0] inc_size = 16 * ready if ready > 0: inc_data = self.request.recv(inc_size) idx = 0 while ready != 0: packet = inc_data[idx:idx + 16] if packet[0:3] != b'ct\x05': print('SERVER GOT INCORRECT DATA') self.server.selfx.set_error_text('SERVER GOT INCORRECT DATA') break else: fid = struct.unpack("!I", packet[3:7])[0] flen = packet[7] fdata = packet[8:16] while self.server._access_in.is_set(): time.sleep(0.0001) self.server._access_in.set() self.server.CANList_in.append( CANMessage.init_data(int(fid), flen, fdata) ) self.server._access_in.clear() idx += 16 ready -= 1
def handle(self): while True: try: self.socket.sendall(b'c\x01\x00\x00') # Request for frames inc_header = self.socket.recv(4) # Get header first if inc_header[0:2] != b'c\x02': self.selfx.dprint(0, "HEADER ERROR") self.selfx.set_error_text('HEADER ERROR') continue else: ready = struct.unpack("!H", inc_header[2:4])[0] inc_size = 16 * ready if ready > 0: inc_data = self.socket.recv(inc_size) # Get frames idx = 0 while ready != 0: packet = inc_data[idx:idx + 16] if packet[0:3] != b'ct\x03': self.selfx.dprint(0, 'CLIENT GOT INCORRECT DATA') self.selfx.set_error_text('CLIENT GOT INCORRECT DATA') break else: fid = struct.unpack("!I", packet[3:7])[0] flen = packet[7] fdata = packet[8:16] while self._access_in.is_set(): time.sleep(0.0001) self._access_in.set() self.CANList_in.append( CANMessage.init_data(int(fid), flen, fdata) ) self._access_in.clear() idx += 16 ready -= 1 while self._access_out.is_set(): time.sleep(0.0001) self._access_out.set() ready = len(self.CANList_out) if ready > 0: sz = struct.pack("!H", ready) send_msg = b'c\x04' + sz self.socket.sendall(send_msg) send_msg = b'' for can_msg in self.CANList_out: # 16 byte send_msg += b'ct\x05' + (b'\x00' * (4 - len(can_msg.frame_raw_id))) + can_msg.frame_raw_id + can_msg.frame_raw_length + can_msg.frame_raw_data + (b'\x00' * (8 - can_msg.frame_length)) if ready > 0: self.socket.sendall(send_msg) self.CANList_out = [] self._access_out.clear() except Exception as e: self.selfx.set_error_text('TCPClient: recv response error:' + str(e)) traceback.print_exc()
def generate_can(fid, data, padding=None): # generate CAN messages seq """Generate a CAN message in ISO TP format. :param int fid: CAN ID for the message :param list data: CAN message data :param int padding: Value of the padding, e.g. 0x00 (if padding is required) :return: List of cantoolz.can.CANMessage messages in ISO TP format representing the data. :rtype: list """ _length = len(data) can_msg_list = [] if _length < 8: padding_data = [] padding_length = 0 if padding is not None: padding_data = [int(padding)] * (7 - _length) padding_length = 8 - _length - 1 can_msg_list.append(CANMessage.init_data(fid, _length + 1 + padding_length, [_length] + data[:_length] + padding_data)) # Single elif _length > 4095: return [] else: can_msg_list.append(CANMessage.init_data(fid, 8, [(_length >> 8) + 0x10] + [_length & 0xFF] + data[:6])) seq = 1 bytes = 6 while bytes != _length: # Rest sent = min(_length - bytes, 7) padding_data = [] padding_length = 0 if padding and sent < 7: padding_data = [int(padding)] * (7 - sent) padding_length = 8 - sent - 1 can_msg_list.append(CANMessage.init_data(fid, 1 + sent + padding_length, [seq + 0x20] + data[bytes:bytes + sent] + padding_data)) bytes += sent seq += 1 if seq > 0xF: seq = 0 return can_msg_list
def generate_vin(self): curr_t = time.process_time() if self.vin_gen[0] == 0 or curr_t - self.vin_gen[0] > self.vin_gen[2]: if self.vin_gen[ 1] == 0 or curr_t - self.vin_gen[1] > self.vin_gen[3]: self.frames.append( CANMessage.init_data(self._status2.get('vin_id', 1), len(self.vin[self.count_part]), self.vin[self.count_part])) self.count_part += 1 self.vin_gen[1] = curr_t if self.count_part == len(self.vin): self.vin_gen[0] = curr_t self.count_part = 0
def send_command(self, index): cmd = self._commands[index] name = list([x for x in list(cmd.keys()) if x not in ["cmd"]])[0] (fid, length, data_hex) = cmd[name].split(":") fid = fid.strip() length = int(length) data_hex = data_hex.strip() fid = int(fid, 0) data_hex = bytes.fromhex(data_hex)[:8] self._frames.append(CANMessage.init_data(fid, length, data_hex)) return name + " has been added to queue!"
def cmd_write(self, frame): frame = frame.strip().split(":") fid = frame[0].strip() fid = int(fid, 0) if len(frame) == 2: length = len(bytes.fromhex(frame[1].strip())) data = bytes.fromhex(frame[1].strip()) elif len(frame) == 3: length = int(frame[1].strip()) data = bytes.fromhex(frame[2].strip()) else: return "Bad format" self.can_buffer_write.append(CANMessage.init_data(fid, length, data)) return "Added to queue"
def do_read(self, can_msg): if self._run and not can_msg.CANData: try: can_frame = self.socket.recv(16) self.dprint(2, "READ: " + self.get_hex(can_frame)) if len(can_frame) == 16: idf = struct.unpack("I", can_frame[0:4])[0] if idf & 0x80000000: idf &= 0x7FFFFFFF can_msg.CANFrame = CANMessage.init_data( idf, can_frame[4], can_frame[8:8 + can_frame[4]]) can_msg.bus = self._bus can_msg.CANData = True except: return can_msg return can_msg
def do_start(self, args): self.queue_messages = [] self.last = time.clock() data = [0, 0, 0, 0, 0, 0, 0, 0] if 'body' in args: data = list(bytes.fromhex(args['body'])) iso_mode = self._get_iso_mode(args) padding = args.get('padding', None) shift = int(args.get('shift', 0x8)) if 'range' not in args: self.dprint(1, "No range specified") self._active = False self.set_error_text("ERROR: No range specified") return start, end = args.get('range', [0, 0]) for i in range(int(start), int(end)): if iso_mode == 1: iso_list = ISOTPMessage.generate_can(i, data, padding) iso_list.reverse() self.queue_messages.extend(iso_list) elif iso_mode == 0: self.queue_messages.append( CANMessage.init_data(i, len(data), data[:8])) elif iso_mode == 2: for service in args.get('services', []): uds_m = UDSMessage(shift, padding) for service_id in self._get_range(service['service']): # https://github.com/eik00d/CANToolz/issues/93 by @DePierre subservice_ids = service.get('sub', None) if subservice_ids is None: subservice_ids = [None] else: subservice_ids = self._get_range(subservice_ids) for subservice_id in subservice_ids: iso_list = uds_m.add_request( i, service_id, subservice_id, service.get('data', [])) iso_list.reverse() self.queue_messages.extend(iso_list) self._full = len(self.queue_messages) self._last = 0
def fuzz(self, fuzz_list, idf, data, bytes_to_fuzz, level, iso_mode): messages = [] x_data = [] + data for byte in fuzz_list: x_data[bytes_to_fuzz[level]] = byte if level != 0: messages.extend( self.fuzz(fuzz_list, idf, x_data, bytes_to_fuzz, level - 1, iso_mode)) else: if iso_mode == 1: iso_list = ISOTPMessage.generate_can(idf, x_data) iso_list.reverse() messages.extend(iso_list) else: messages.append( CANMessage.init_data(idf, len(x_data), x_data[:8])) return messages
def cmd_write(self, def_p, frame): frame = frame.strip().split(":") fid = frame[0].strip() if fid[0:2] == '0x': fid = int(fid, 16) else: fid = int(fid) if len(frame) == 2: length = len(bytes.fromhex(frame[1].strip())) data = bytes.fromhex(frame[1].strip()) elif len(frame) == 3: length = int(frame[1].strip()) data = bytes.fromhex(frame[2].strip()) else: return "Bad format" self.can_buffer_write.append(CANMessage.init_data(fid, length, data)) return "Added to queue"
def dev_write(self, data): self.dprint(1, "CMD: " + data) ret = "Sent!" if self._run: try: idf, dataf = data.strip().split('#') dataf = bytes.fromhex(dataf) idf = int(idf, 16) lenf = min(8, len(dataf)) message = CANSploitMessage() message.CANData = True message.CANFrame = CANMessage.init_data( idf, lenf, dataf[0:lenf]) self.do_write(message) except Exception as e: traceback.print_exc() ret = str(e) else: ret = "Module is not active!" return ret
def parse_file(self, name, _bus): try: with open(name.strip(), "r") as ins: # "[TIME_STAMP]0x111:4:11223344" for line in ins: if len(line[:].split(":")) >= 3: fid = line[:].split(":")[0].strip() if fid[0] == "[" and fid.find(']') > 0: time_stamp = float(fid[1:fid.find(']')]) fid = fid.split(']')[1].strip() elif fid[0] == "<" and fid.find('>') > 0: time_stamp = float(fid[1:fid.find('>')]) self.add_timestamp(time_stamp) continue elif len(line[:-1].split(":")) >= 3: time_stamp = -1.0 else: time_stamp = -1.0 num_fid = int(fid, 0) length = line[:].split(":")[1] data = line[:].split(":")[2] if data[-1:] == "\n": data = data[:-1] if data[-1:] == "\r": data = data[:-1] msg = CANSploitMessage() msg.CANFrame = CANMessage.init_data( num_fid, int(length), bytes.fromhex(data)[:8]) msg.CANData = True msg.bus = _bus self._stream.append([time_stamp, msg]) self._size += 1 except Exception as e: print(str(e)) return "Can't open files with CAN messages: " + str(e) return "Loaded from file: " + str(len(self)) + " messages"