def rdt_send(self, filename, data, segment_size): offset = 0 seq = 0 is_first = False start = timer() while offset < len(data): end = timer() print(end - start) if int(end - start) >= 200: print("TIMER EXPIRED") break if is_first == True: if offset + segment_size > len(data): segment = data[offset:] else: segment = data[offset:offset + segment_size] offset += segment_size ack = False while not ack: end = timer() print(end - start) if int(end - start) >= 200: print("TIMER EXPIRED") break if is_first == False: tosend = (filename + ' ' + str(len(data))).encode() #self.sock.sendto((str(utils.checksum(filename+ ' ' +str(len(data))))+str(seq)+filename+' '+str(len(data))).encode(), self.address) self.sock.sendto( utils.checksum(tosend).encode() + str(seq).encode() + tosend, self.address) print("sending filename " + (utils.checksum(tosend).encode() + tosend).decode()) else: print("sending DATA") self.sock.sendto( utils.checksum(segment).encode() + str(seq).encode() + segment, self.address) print('checksum :' + utils.checksum(segment) + 'seq: ' + str(seq)) try: message, self.address = self.sock.recvfrom(2048) except socket.timeout: print('timeout') else: try: print(message) checksum = message[:64] print('checksunm is ' + checksum.decode()) ack_seq = message[67:68] print('ack is ' + str(ack_seq)) if utils.checksum(message[64:]) == checksum.decode( ) and ack_seq.decode() == str(seq): print('got valid ack ' + ack_seq.decode()) ack = True is_first = True except: pass seq = 1 - seq
def icmp_echo_request(self, ip_src, ip_dst): # Protocol # protocol = 0x0800 # Ethernet Header # eth_hdr = struct.pack("!6s6sH", mac_dst, mac_src, protocol) # IP Header 20 bytes ip_ver = 4 ip_ihl = 5 ip_tos = 0 ip_id = 5432 ip_frag_off = 0 ip_ttl = 255 ip_proto = 0x1 ip_total_len = 20 + 21 # ip_check = 0xc6a0 ip_check = 0 ip_saddr = ip_src ip_daddr = ip_dst # ip_saddr = socket.inet_aton(ip_src) # ip_daddr = socket.inet_aton(ip_dst) ip_ihl_ver = (ip_ver << 4) + ip_ihl # First time to calculate the checksum ip_header = struct.pack("!BBHHHBBH4s4s", ip_ihl_ver, ip_tos, \ ip_total_len, ip_id, ip_frag_off, ip_ttl,\ ip_proto, ip_check, ip_saddr, ip_daddr) # Second time with the correct checksum # print("ip header:",ip_header) ip_check = utils.checksum(ip_header) ip_header = struct.pack("!BBHHHBBH4s4s", ip_ihl_ver, ip_tos, \ ip_total_len, ip_id, ip_frag_off, ip_ttl,\ ip_proto, ip_check, ip_saddr, ip_daddr) # ICMP Echo Request Header icmp_type = 8 code = 0 mychecksum = 0 identifier = 12345 seqnumber = 0 payload = b"istoehumteste" icmp_packet = struct.pack("!BBHHH13s", icmp_type, code,\ mychecksum, identifier, seqnumber, payload) mychecksum = utils.checksum(icmp_packet) icmp_packet = struct.pack("!BBHHH13s", icmp_type, code,\ mychecksum, identifier, seqnumber, payload) # dest_addr = socket.gethostbyname(ip_dst) # return eth_hdr+ip_header+icmp_packet return ip_header + icmp_packet
def getJson(partyId, filters): global mc if partyId == None: return {} # check if in cache with the particular current filter filterString = str(filters) cachedItem = mc.get(str(partyId)) # for memcached, key must be string both on set and get if ( not cachedItem == None ) and (cachedItem['filters'] == utils.checksum(filterString)): return cachedItem['graph'] else: graph = loadGraph(partyId, filters) mc.set(str(partyId), {'filters': utils.checksum(filterString), 'graph': graph }, 60) return graph
def unpack(self, ip_datagram): ''' Unpack the given IP datagram string, the unpacked data would be stored in the current object. ''' # get the basic IP headers without opts field ip_header_size = calcsize(IP_HDR_FMT) ip_headers = ip_datagram[:ip_header_size] # use the ip_hdr_cksum field to hold the # checksum verification result, because # we no longer use it hdr_fields = unpack(IP_HDR_FMT, ip_headers) self.ip_tos = hdr_fields[1] self.ip_tlen = hdr_fields[2] self.ip_id = hdr_fields[3] self.ip_frag_off = hdr_fields[4] self.ip_ttl = hdr_fields[5] self.ip_proto = hdr_fields[6] self.ip_src_addr = hdr_fields[8] self.ip_dest_addr = hdr_fields[9] # process the IP opts fields if there are # currently just skip it ip_ver_ihl = hdr_fields[0] self.ip_ihl = ip_ver_ihl - (self.ip_ver << 4) if self.ip_ihl > 5: opts_size = (self.ip_ihl - 5) * 4 ip_header_size += opts_size ip_headers = ip_datagram[:ip_header_size] self.data = ip_datagram[ip_header_size:self.ip_tlen] self.ip_hdr_cksum = checksum(ip_headers)
def unpack(self, tcp_segment): ''' Unpack the given TCP segment string, the unpacked data would be stored in the current object. ''' tcp_header_size = calcsize(TCP_HDR_FMT) tcp_headers = tcp_segment[:tcp_header_size] hdr_fields = unpack(TCP_HDR_FMT, tcp_headers) self.tcp_src_port = hdr_fields[0] self.tcp_dest_port = hdr_fields[1] self.tcp_seq = hdr_fields[2] self.tcp_ack_seq = hdr_fields[3] tcp_doff_resvd = hdr_fields[4] self.tcp_doff = tcp_doff_resvd >> 4 # get the data offset self.tcp_adwind = hdr_fields[6] self.tcp_urg_ptr = hdr_fields[7] # parse TCP flags tcp_flags = hdr_fields[5] self.tcp_ffin, self.tcp_fsyn, self.tcp_frst, \ self.tcp_fpsh, self.tcp_fack, \ self.tcp_furg = self._deshift_flags(tcp_flags) # process the TCP options if there are # currently just skip it if self.tcp_doff > 5: opts_size = (self.tcp_doff - 5) * 4 tcp_header_size += opts_size tcp_headers = tcp_segment[:tcp_header_size] # get the TCP data self.data = tcp_segment[tcp_header_size:] # compute the checksum of the recv packet with psh tcp_psh = self._tcp_pseudo_headers(tcp_headers) self.tcp_cksum = checksum(''.join( [tcp_psh, tcp_headers, self.data]))
def make_packet(seqnum, data, flag=0): """ Make a bytes packet from given information """ packet_content = (seqnum.to_bytes(2, byteorder='big') + flag.to_bytes(1, byteorder='big') + data) csum = checksum(packet_content) return csum.to_bytes(1, byteorder='big') + packet_content
def preparePayload(message, command): #payload = struct.pack('4s', b'\xfc\xc1\xb7\xdc') payload = struct.pack('4s', b'\xc0\xc0\xc0\xc0') payload += struct.pack('12s', command) payload += struct.pack('I', len(message)) payload += struct.pack('4s', checksum(message)[0:4]) payload += message return payload
def udp_packet(self, ip_src, srcp, ip_dst, dstp): ip_ver = 4 ip_ihl = 5 ip_tos = 0 ip_id = 5432 ip_frag_off = 0 ip_ttl = 255 ip_proto = 17 ip_total_len = 20 + 8 # UDP # ip_check = 0xc6a0 ip_check = 0 ip_saddr = ip_src ip_daddr = ip_dst # ip_saddr = socket.inet_aton(ip_src) # ip_daddr = socket.inet_aton(ip_dst) ip_ihl_ver = (ip_ver << 4) + ip_ihl # First time to calculate the checksum ip_header = struct.pack("!BBHHHBBH4s4s", ip_ihl_ver, ip_tos, \ ip_total_len, ip_id, ip_frag_off, ip_ttl,\ ip_proto, ip_check, ip_saddr, ip_daddr) # Second time with the correct checksum # print("ip header:",ip_header) ip_check = utils.checksum(ip_header) ip_header = struct.pack("!BBHHHBBH4s4s", ip_ihl_ver, ip_tos, \ ip_total_len, ip_id, ip_frag_off, ip_ttl,\ ip_proto, ip_check, ip_saddr, ip_daddr) udp_len = 8 # It's actually 8 + len(data) , but we do not pass any protocol = socket.IPPROTO_UDP # udp_check = 0 udp_pseudo_header = ip_src + ip_dst + struct.pack( '!BBH', 0, protocol, udp_len) udp_header = struct.pack('!4H', srcp, dstp, udp_len, udp_check) udp_check = utils.checksum(udp_pseudo_header + udp_header) # + data , we don't pass any udp_header = struct.pack('!4H', srcp, dstp, udp_len, udp_check) return ip_header + udp_header
def assemble(self): header = self._header() self.cksum = utils.checksum(header + '\000\000' + self.src_ip + self.dst_ip) packet = [self._header(), struct.pack('H', self.cksum), self.src_ip, self.dst_ip, self.payload] return ''.join(packet)
def rdt_recv(self): expecting_sequence = 0 is_first = True all_data = b'' start = timer() while True: end = timer() print(end-start) if int(end-start) >= 300: print("TIMER EXPIRED") break; if self.data_size != None and int(self.data_size) <= 0: break message, self.address = self.sock.recvfrom(2048) checksum = message[:64] seq = message[64:65] content = message[65:] try : if utils.checksum(content) == checksum.decode(): checksum = utils.checksum(content) ##print('checksum passed sending ACK ' +(str(utils.checksum("ACK" +str(seq.decode())))+"ACK" +str(seq.decode()))) print('checksum passed sending ack ' + utils.checksum("ACK".encode()+seq)+ "ACK"+seq.decode()) self.sock.sendto(utils.checksum("ACK".encode()+seq).encode()+"ACK".encode()+seq, self.address) print("expecting_sequence " + str(expecting_sequence)) if int(seq) == expecting_sequence: if is_first: print('first_datagram') self.recv_output_filename(content.decode()) is_first = False else: self.data_size = self.data_size - len(content) print('content recieved writing to file data left is '+ str(self.data_size)) all_data += content expecting_sequence = 1 - expecting_sequence else: print("checksum failed sending NAk "+ utils.checksum(content)) #self.sock.sendto((str(utils.checksum("ACK" +str(1 - expecting_sequence)))+"ACK" +str(1 - expecting_sequence)).encode(), self.address) self.sock.sendto(utils.checksum("ACK".encode()+ str((1-expecting_sequence)).encode()).encode()+"ACK".encode()+str((1-expecting_sequence)).encode(), self.address) except: print("checksum failed sending NAk "+ utils.checksum(content)) #self.sock.sendto((str(utils.checksum("ACK" +str(1 - expecting_sequence)))+"ACK" +str(1 - expecting_sequence)).encode(), self.address) self.sock.sendto(utils.checksum("ACK".encode()+ str((1-expecting_sequence)).encode()).encode()+"ACK".encode()+str((1-expecting_sequence)).encode(), self.address) print('writing data') self.fout.write(all_data) self.fout.flush() os.fsync(self.fout) self.fout.close()
def parse_packet(data): """ Parse a packet from at most MAX_SIZE bytes data. """ checked_sum = checksum(data[1:]) received_sum = int.from_bytes(data[:1], byteorder='big') seqnum = int.from_bytes(data[1:3], byteorder='big') flag = int.from_bytes(data[3:4], byteorder='big') data = data[4:] return checked_sum, received_sum, seqnum, flag, data
def assemble(self): header = self._header() self.cksum = utils.checksum(header + '\000\000' + self.src_ip + self.dst_ip) packet = [ self._header(), struct.pack('H', self.cksum), self.src_ip, self.dst_ip, self.payload ] return ''.join(packet)
def redeemscript_to_p2sh_address(redeem_script, main_net=True): redeem_script = redeem_script.decode("hex") script_prefix = SCRIPT_PREFIX if not main_net: script_prefix = SCRIPT_PREFIX_TEST h20 = utils.hash160(redeem_script) d21 = script_prefix + h20 c4 = utils.checksum(d21) d25 = d21 + c4 return base58.b58encode(d25)
def pubkey_to_legacy_address(pubkey, main_net=True): pubkey = pubkey.decode("hex") addr_prefix = ADDR_PREFIX if not main_net: addr_prefix = ADDR_PREFIX_TEST h20 = utils.hash160(pubkey) d21 = addr_prefix + h20 c4 = utils.checksum(d21) d25 = d21 + c4 return base58.b58encode(d25)
def offer_policy(self, policy_id, price): if policy_id not in self.policies: raise ValueError, "Seller doesn't have this policy" chk = checksum(self.id, policy_id, price, self.token) data = { 'seller_id': self.id, 'policy_id': policy_id, 'price': price, 'checksum': chk, } return data
def pack(self): ''' Pack the TCPSegment object to a TCP segment string. ''' tcp_hdr_buf = self._tcp_headers_buf() tcp_psh = self._tcp_pseudo_headers(tcp_hdr_buf.raw) self.tcp_cksum = checksum(''.join( [tcp_psh, tcp_hdr_buf.raw, self.data])) pack_into('!H', tcp_hdr_buf, calcsize(TCP_HDR_FMT[:8]), self.tcp_cksum) tcp_segment = ''.join([tcp_hdr_buf.raw, self.data]) return tcp_segment
def witness_redeemscript_to_p2sh_address(redeemscript, main_net=True): redeemscript = redeemscript.decode("hex") d32 = utils.sha256(redeemscript) witness_script = OP_0 + chr(len(d32)) + d32 script_prefix = SCRIPT_PREFIX if not main_net: script_prefix = SCRIPT_PREFIX_TEST h20 = utils.hash160(witness_script) d21 = script_prefix + h20 c4 = utils.checksum(d21) d25 = d21 + c4 return base58.b58encode(d25)
def pack(self, payload, peek=None): s1 = chr((self.version << 4) + (self.headlen / 4)) s2 = chr(0) # different service field s3 = pack("!H", 20 + len(payload)) s4 = pack("!H", self.identification) s5 = chr((self.flags << 5) + (self.segment_id >> 8)) s6 = chr(self.segment_id & 0xff) s7 = chr(self.TTL) s8 = chr(self.protocol) s10 = "".join([chr(x) for x in self.src_ip]) s11 = "".join([chr(x) for x in self.dst_ip]) s9 = pack("!H", checksum(s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s10 + s11)) return s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10 + s11 + payload
def witness_pubkey_to_p2sh_address(pubkey, main_net=True): pubkey = pubkey.decode("hex") d20 = utils.hash160(pubkey) witness_script = OP_0 + chr(len(d20)) + d20 script_prefix = SCRIPT_PREFIX if not main_net: script_prefix = SCRIPT_PREFIX_TEST h20 = utils.hash160(witness_script) d21 = script_prefix + h20 c4 = utils.checksum(d21) d25 = d21 + c4 return base58.b58encode(d25)
def pull(self, file_): f = open(file_, 'r') file_meta = [] for line in f: file_meta.append(line) f.close() name = file_meta[0].replace('\n', '') size = int(file_meta[1].replace('\n', '')) n_segments = int(file_meta[2].replace('\n', '')) checksum_ = file_meta[3].replace('\n', '') data = ''.encode() # chunk = ''.encode() threads = [] data_array = [None] * n_segments for i in range(0, n_segments): seg_name = name + '_' + str(i) ip, port = self.find_successor(hash_(seg_name)).split(':') s = self.send(Address(ip, port), 'return_segment {}'.format(seg_name)) seg_size = int(s.recv(1024).decode('utf-8')) print('seg_size:', seg_size) s.sendall('READY'.encode()) # chunk = s.recv(seg_size) t = Thread(target=get_segment, args=(s, data_array, seg_name, seg_size, i)) t.start() threads.append(t) # while True: # chunk += s.recv(seg_size) # if len(chunk) >= seg_size: # break # data += chunk # print('{}: {}/{} bytes recieved'.format(seg_name, len(chunk), seg_size)) # chunk = b'' # # chunk = len(data) # s.close() for th in threads: th.join() for b in data_array: data += b f = open(name, 'wb+') f.write(data) f.close() if checksum_ == checksum(name): return 'File pulled successfully' else: os.remove(name) return 'Failed to pull file/Corrupted file'
def _send(self, packetType, payload): """ Utility method to calculate the checksum, the payload length and combine everything into a nice package. """ if not isinstance(payload, str): buf = BytesIO() payload.toWire(buf) payload = buf.getvalue() message = mainnetMagic message += packetType.ljust(12, chr(0)) message += struct.pack("<I", len(payload)) message += checksum(payload) message += payload self.bytes_out += len(message) self.transport.write(message)
def __packet(self): # pseudo header fields placeholder = 0 protocol = socket.IPPROTO_TCP tcp_length = len(self.tcp_packet) psh = self.ip_header.src_address_ipv6 + \ self.ip_header.dst_address_ipv6 + \ pack('!BBH', placeholder, protocol, tcp_length) psh = psh + self.tcp_packet # make the tcp header again and fill the correct checksum self.tcp_header.checksum = checksum(psh) self.tcp_packet = self.tcp_header.assembly() # final full packet - syn packets dont have any data packet = self.eth_packet + self.ip_packet + self.tcp_packet return packet
def witness_pubkey_to_p2sh_address(pubkey): assert (type(pubkey) == bytes) assert (len(pubkey) == 33) pubkey = pubkey.decode('iso-8859-15') d20 = utils.hash160(pubkey.encode('iso-8859-15')).decode('iso-8859-15') witness_script = OP_0 + chr(len(d20)) + d20 script_prefix = SCRIPT_PREFIX h20 = utils.hash160( witness_script.encode('iso-8859-15')).decode('iso-8859-15') d21 = script_prefix + h20 c4 = utils.checksum(d21.encode('iso-8859-15')).decode('iso-8859-15') d25 = d21 + c4 return base58.b58encode(d25.encode('iso-8859-15'))
def file_server(train_dir, port): """ Worker process that will handle file transfers in the server (trainer) side. A client can send a message containing the name of training file followed by a line break. This server then looks for the file in train_dir and returns: (1) the checksum of the file in one package then (2) the file itself in the remaining packages. Args: train_dir: string: path to directory where the trainer is storing training files. port: int: port number opened for file transfers. """ s = socket.socket() ip = '' s.bind((ip, port)) while True: s.listen(60) c, addr = s.accept() print('FileServer: got connection from', addr) message = c.recv(PACKET_SIZE).decode('utf-8') tokens = message.splitlines() file_name = tokens[0] file_path = osp.join(train_dir, file_name) if osp.exists(file_path): file_checksum = checksum(file_path) print('Sending checksum...') c.send(file_checksum.ljust(PACKET_SIZE)) print('Checksum sent.') print('Sending file %s ...' % file_path) with open(file_path, 'rb') as f: packet = f.read(PACKET_SIZE) while packet: c.send(packet) packet = f.read(PACKET_SIZE) print('%s sent.' % file_path) else: print('File %s cannot be found, ignoring request.' % file_path) c.close() s.close()
def setup(self, x=500, y=50): start = time.time() last = 0 count = 0 a = self.w // 2 - x // 2 b = self.h // 2 - y // 2 with mss() as sct: while True: shot = sct.grab((a, b, a + x, b + y)) count += 1 c = checksum(shot.rgb) if c: self.update_checksum(c) dt = time.time() - start dt_int = int(dt) if dt_int > last: last = dt_int print('%.2f FPS' % (count / dt))
def pack(self, payload, peek=None): s1 = pack("!H", self.src_port) s2 = pack("!H", self.dst_port) s3 = pack("!I", self.seq_num) s4 = pack("!I", self.ack_num) s6 = chr(self.flags & 0xff) s7 = pack("!H", self.window) s9 = pack("!H", self.urgent) s10 = self.pack_options() self.headlen = len(s1+s2+s3+s4+' '+s6+s7+s9+s10+' ') s5 = chr(((self.headlen /4) <<4) + (self.flags >> 8)) # construct fake IP header: src_ip, dst_ip, reserved(0x00), protocol(tcp is 0x06), length(header+payload) fake_header = "".join([chr(x) for x in peek.src_ip]) + "".join([chr(x) for x in peek.dst_ip]) + "\x00\x06"+pack("!H", self.headlen+len(payload)) csum = checksum(fake_header + s1+s2+s3+s4+s5+s6+s7+s9+s10+payload) s8 = pack("!H", csum) return s1+s2+s3+s4+s5+s6+s7+s8+s9+s10+payload
def loadCachableData(fileName, sql): if utils.isValidCacheFile(fileName, utils.checksum(sql)): return cPickle.load(open(fileName, "rb")) else: try: conn = getMysqlConnection() cur = conn.cursor() cur.execute(sql) rows = cur.fetchall() cur.close() except Exception as e: logger.error("query failed: " + sql + "\n" + str(e)) raise if not rows == None and len(rows) > 0: cPickle.dump(rows, open(fileName, "wb"), True) return rows else: logger.error("SQL ERROR: Query Returned 0 Results: " + fileName) raise
def pack(self): ''' Pack the IPDatagram object to an IP datagram string. We compute the IP headers checksum with leaving the checksum field empty, and then pack the checksum into the IP headers. So that the verification of the header checksum could use the same checksum algorithm, and then simply check if the result is 0. ''' ip_hdr_buf = create_string_buffer(calcsize(IP_HDR_FMT)) ip_ver_ihl = (self.ip_ver << 4) + self.ip_ihl pack_into(IP_HDR_FMT, ip_hdr_buf, 0, ip_ver_ihl, self.ip_tos, self.ip_tlen, self.ip_id, self.ip_frag_off, self.ip_ttl, self.ip_proto, self.ip_hdr_cksum, self.ip_src_addr, self.ip_dest_addr) self.ip_hdr_cksum = checksum(ip_hdr_buf.raw) pack_into('!H', ip_hdr_buf, calcsize(IP_HDR_FMT[:8]), self.ip_hdr_cksum) ip_datagram = ''.join([ip_hdr_buf.raw, self.data]) return ip_datagram
def file_client(server_ip, server_port, plmanager_fileclient_queue, fileclient_plmanager_queue): """ Worker process that will handle file transfers in the client (player) side. Args: server_ip: string: IP address of the server (trainer). server_port: int: port number opened for file transfers in the server. plmanager_fileclient_queue: Queue: transfer data from player_manager to this process. fileclient_plmanager_queue: Queue: transfer data from this process to player_manager. """ while True: file_dir, file_name = plmanager_fileclient_queue.get() s = socket.socket() print('Connecting file_client to %s:%d ...' % (server_ip, server_port)) s.connect((server_ip, server_port)) print('Connected.') s.send((file_name + '\n').ljust(PACKET_SIZE).encode('utf-8')) server_checksum = s.recv(PACKET_SIZE) write_file_path = osp.join(file_dir, file_name) print('Receiving %s ...' % write_file_path) with open(write_file_path, 'wb') as f: packet = s.recv(PACKET_SIZE) while packet: f.write(packet) packet = s.recv(PACKET_SIZE) print('Done receiving.') s.shutdown(socket.SHUT_WR) s.close() local_checksum = checksum(write_file_path) server_checksum = server_checksum[:len(local_checksum)] if server_checksum == local_checksum: print('Checksum is correct for %s' % write_file_path) fileclient_plmanager_queue.put(True) else: print('Incorrect checksum, file %s is corrupted' % write_file_path) fileclient_plmanager_queue.put(False)
def buy_policy(self, seller, policy, price, chk): salt = seller.token if chk != checksum(seller.id, policy.id, price, salt): raise ValueError, "Checksum mismatch" # check the seller has the funds: if self.balance < price: raise ValueError, "Not enough funds for sale" # check the buyer doesn't alreay have this policy if policy.id in self.policies: raise ValueError, "The buyer already has this policy" # sort out the money first seller.balance += price self.balance -= price # then give the buyer the policy self.policies[policy.id] = 0.0 return True
def get_checksum(self, packet): internet_checksum = checksum(packet) return internet_checksum
# verify data magic, command, m_length, chcksm = struct.unpack( '4s12sI4s', data[0:24]) if b'block' not in command: print("ERROR : wrong command") sys.exit() if len(data[24:]) != m_length: print("ERROR : Wrong length") sys.exit() block_message = data[24:] count -= 1 hash = checksum(block_message[0:80])[::-1].hex() blocks_list.remove(hash) print("Count : {} - Block hash {}".format(blocks_count + 500 - count, hash)) log += "----- {} -----\n".format(hash) auxpow_activated = False if blocks_count + 500 - count > 371336: auxpow_activated = True try: txouts = unpackBlock(block_message, auxpow_activated) except Exception as e: bug_file = open("bug/{}.txt".format(hash), "w")
def test_example(self): spreadsheet = """5 1 9 5 7 5 3 2 4 6 8""" self.assertEqual(utils.checksum(spreadsheet, " "), 18)
def check_csum(self): acsum = socket.htons(utils.checksum(self._header() + '\000\000' + self.src_ip + self.dst_ip)) return (acsum == self.csum)
import utils with open('input') as f: captcha = f.read().strip() print(utils.checksum(captcha, "\t")) print(utils.checksum_modulo(captcha, "\t"))
def tcp_syn(self, ip_src, srcp, ip_dst, dstp): # Protocol # protocol = 0x0800 # Ethernet Header # eth_hdr = struct.pack("!6s6sH", mac_dst, mac_src, protocol) # IP Header 20 bytes ip_ver = 4 ip_ihl = 5 ip_tos = 0 ip_id = 5432 ip_frag_off = 0 ip_ttl = 255 ip_proto = 0x6 ip_total_len = 20 + 20 # ip_check = 0xc6a0 ip_check = 0 ip_saddr = ip_src ip_daddr = ip_dst # ip_saddr = socket.inet_aton(ip_src) # ip_daddr = socket.inet_aton(ip_dst) ip_ihl_ver = (ip_ver << 4) + ip_ihl # First time to calculate the checksum ip_header = struct.pack("!BBHHHBBH4s4s", ip_ihl_ver, ip_tos, \ ip_total_len, ip_id, ip_frag_off, ip_ttl,\ ip_proto, ip_check, ip_saddr, ip_daddr) # Second time with the correct checksum # print("ip header:",ip_header) ip_check = utils.checksum(ip_header) ip_header = struct.pack("!BBHHHBBH4s4s", ip_ihl_ver, ip_tos, \ ip_total_len, ip_id, ip_frag_off, ip_ttl,\ ip_proto, ip_check, ip_saddr, ip_daddr) #srcp,dstp args # tcp_srcp = srcp # tcp_dstp = dstp tcp_seq = 0 tcp_ack = 0 tcp_hl = 5 tcp_r = 0 tcp_offset = (tcp_hl << 4) + 0 # # tcp_flags = 2 # Syn tcp_wsize = socket.htons(5840) # tcp_wsize= 5840 tcp_check = 0 tcp_urgptr = 0 # tcp_payload = 1 # payload = ("[("*30)+"Hello"+("]"*30) tcp_header = struct.pack("!HHLLBBHHH",\ srcp,dstp,tcp_seq,tcp_ack,tcp_offset,tcp_flags,tcp_wsize,tcp_check,tcp_urgptr) tcp_pseudo_header = struct.pack("!4s4sBBH",\ ip_src , ip_dst , 0 , socket.IPPROTO_TCP, len(tcp_header)) tcp_check = utils.checksum(tcp_pseudo_header + tcp_header) tcp_header = struct.pack("!HHLLBBHHH",\ srcp,dstp,tcp_seq,tcp_ack,tcp_offset,tcp_flags,tcp_wsize,tcp_check,tcp_urgptr) # return ip_header+tcp_header return ip_header + tcp_header
def create_packet(self, id, data): # calculate checksum from clear header header = struct.pack('bbhhh', 8, 0, 0, id, 1) header = struct.pack('bbHHh', 8, 0, socket.htons(checksum(header + bytes(data, 'utf-8'))), id, 1) return header + bytes(data, 'utf-8')