def interp(plugin, nuin): family = nuin.value(0) res_id = nuin.value(1); pattrs = (ctypes.POINTER(mnl.Attr) * (nfqnl.NFQA_MAX + 1)).from_buffer(nuin.value(2)) ph = pattrs[nfqnl.NFQA_PACKET_HDR].contents.get_payload_as(nfqnl.NfqnlMsgPacketHdr) packet_id = socket.ntohl(ph.packet_id) log.info("res_id: %d, qid: %d", res_id, packet_id) nfq_send_accept(res_id, packet_id) if pattrs[nfqnl.NFQA_PAYLOAD]: ip = IP(bytes(pattrs[nfqnl.NFQA_PAYLOAD].contents.get_payload_v())) log.info(ip.summary()) if pattrs[nfqnl.NFQA_IFINDEX_INDEV]: ifin = pattrs[nfqnl.NFQA_IFINDEX_INDEV].contents.get_u32() log.info("indev: %d", socket.ntohl(ifin)); if pattrs[nfqnl.NFQA_IFINDEX_OUTDEV]: ifout = pattrs[nfqnl.NFQA_IFINDEX_OUTDEV].contents.get_u32() log.info("outdev: %d", socket.ntohl(ifout)); if pattrs[nfqnl.NFQA_CT]: ct = nfct.Conntrack() ct.payload_parse(pattrs[nfqnl.NFQA_CT].contents.get_payload_v(), family) s = ct.snprintf(4096, nfct.NFCT_T_UNKNOWN, nfct.NFCT_O_DEFAULT, 0) log.info("conntrack: %s", s) return nurs.NURS_RET_OK
def update(self, filt=None): """update([filter]) Update the RouteTable with current values. If a filter function is supplied then it will be called with a RouteEntry and must return a true or false value. If true, the RouterEntry will be included in the table. If false, it will not. """ self._entries = [] lines = open(FILE).readlines() for line in lines[1:]: [iface, dest, gateway, flags, refcnt, use, metric, mask, mtu, window, irtt] = line.split() rt = RouteEntry(iface, Destination=ntohl(int(dest, 16)), Gateway=ntohl(int(gateway, 16)), Flags=RouteFlags(flags), RefCnt=int(refcnt, 16), Use=int(use, 16), Metric=int(metric, 16), Mask=ntohl(int(mask, 16)), MTU=int(mtu, 16), Window=int(window, 16), IRTT=int(irtt, 16)) if filt: if filt(rt): self._entries.append(rt) else: self._entries.append(rt)
def DecodeWin7(values, verbose=False): ignoreTypes = list() if not verbose: ignoreTypes.append('UEME_CTLSESSION') ignoreTypes.append('UEME_CTLCUACount') i = 0 while i < len(values): dsz.script.CheckStop() try: name = dsz.cmd.data.ObjectGet(values[i], 'Name', dsz.TYPE_STRING) value = dsz.cmd.data.ObjectGet(values[i], 'Value', dsz.TYPE_STRING) type = dsz.cmd.data.ObjectGet(values[i], 'Type', dsz.TYPE_STRING) j = 0 while j < len(name): decodedName = rot13decode(name[j]) if decodedName.startswith('UEME_'): nameParts = decodedName.split(':', 1) else: nameParts = [ 'UEME_RUNPATH', decodedName] ignore = False for ignored in ignoreTypes: if nameParts[0] == ignored: ignore = True break dsz.script.data.Start('Value') dsz.script.data.Add('Type', nameParts[0], dsz.TYPE_STRING) if len(nameParts) > 1: nameParts[1] = translateKnownFolders(nameParts[1]) dsz.script.data.Add('Data', nameParts[1], dsz.TYPE_STRING) if not ignore: dsz.ui.Echo('%s' % nameParts[0]) if len(nameParts) > 1: dsz.ui.Echo(' Data : %s' % nameParts[1]) if type[j] == 'REG_BINARY': if len(value[j]) == 144: count = socket.ntohl(int(value[j][8:16], 16)) timestamp2 = socket.ntohl(int(value[j][120:128], 16)) timestamp1 = socket.ntohl(int(value[j][128:136], 16)) timestamp = long('%08x%08x' % (timestamp1, timestamp2), 16) dsz.script.data.Add('Count', '%u' % count, dsz.TYPE_INT) if not ignore: dsz.ui.Echo(' Count : %u' % count) if timestamp > 0: timestamp /= 10000000 timestamp -= 11644473600L t = datetime.datetime.utcfromtimestamp(timestamp) dsz.script.data.Add('Timestamp', t.ctime(), dsz.TYPE_STRING) if not ignore: dsz.ui.Echo(' Last Used : %s' % t.ctime()) dsz.script.data.End() j += 1 except: pass i += 1 return True
def decode_ip_packet(s): d = {} d['version'] = (ord(s[0]) & 0xf0) >> 4 d['header_len'] = ord(s[0]) & 0x0f d['tos'] = ord(s[1]) d['total_len'] = socket.ntohs(struct.unpack('H',s[2:4])[0]) d['id'] = socket.ntohs(struct.unpack('H',s[4:6])[0]) d['flags'] = (ord(s[6]) & 0xe0) >> 5 d['fragment_offset'] = socket.ntohs(struct.unpack('H',s[6:8])[0] & 0x1f) d['ttl'] = ord(s[8]) d['protocol'] = ord(s[9]) d['checksum'] = socket.ntohs(struct.unpack('H',s[10:12])[0]) d['source_address'] = pcap.ntoa(struct.unpack('i',s[12:16])[0]) d['destination_address'] = pcap.ntoa(struct.unpack('i',s[16:20])[0]) if d['header_len'] > 5: d['options'] = s[20:4*(d['header_len']-5)] else: d['options'] = None d['data'] = s[4*d['header_len']:] d['source_port'] = socket.ntohs(struct.unpack('H',d['data'][0:2])[0]) d['destination_port'] = socket.ntohs(struct.unpack('H',d['data'][2:4])[0]) d['seq'] = socket.ntohl(struct.unpack('I',d['data'][4:8])[0]) d['ack'] = socket.ntohl(struct.unpack('I',d['data'][8:12])[0]) d['tcp_header_len'] = (ord(d['data'][12]) & 0xf0) >> 4 d['tcp_bit'] = (ord(d['data'][13]) & 0x3f) d['tcp_data'] = d['data'][4*d['tcp_header_len']:] return d
def random_ipv4(cls, val_range): ''' This returns a IPv4 address in the range ''' ipmin, ipmax = cls.get_ipv4_range_as_int(val_range) iprand = socket.htonl(random.randint(socket.ntohl(ipmin), socket.ntohl(ipmax))) return socket.inet_ntop(socket.AF_INET, struct.pack('I',iprand))
def decode_tcp_packet(s): d = {} d["sport"] = socket.ntohs(struct.unpack('H',s[0:2])[0]) d["dport"] = socket.ntohs(struct.unpack('H',s[2:4])[0]) d["seq"] = socket.ntohl(struct.unpack('I',s[4:8])[0]) d["acknowlege"] = socket.ntohl(struct.unpack('I',s[8:12])[0]) d["header_len"] = (ord(s[12]) & 0xf0) >> 4 d["sign"] = ord(s[13]) d["URG"] = (ord(s[13]) & 0x20) >> 5 d["ACK"] = (ord(s[13]) & 0x10) >> 4 d["PSH"] = (ord(s[13]) & 0x08) >> 3 d["RST"] = (ord(s[13]) & 0x04) >> 2 d["SYN"] = (ord(s[13]) & 0x02) >> 1 d["FIN"] = (ord(s[13]) & 0x01) d["window"] = socket.ntohs(struct.unpack('H',s[14:16])[0]) d["checksum"] = socket.ntohs(socket.ntohs(struct.unpack('H',s[16:18])[0])) d["URG_POINT"] = socket.ntohs(struct.unpack('H',s[18:20])[0]) if d['header_len'] > 5: #d['options']=s[20:4*(d['header_len']-5)] d["options"] = None d["options_kind"] = ord(s[20]) if d["options_kind"] == 2: d["options_mss"] = socket.ntohs(struct.unpack('H',s[22:24])[0]) d["options"] = "mss:%d" % d["options_mss"] elif d["options_kind"] == 3: d["options_windows_factor"] = ord(s[22]) d["options"] = "window factor:%d" % d["options_windows_factor"] elif d["options_kind"] == 8: d["options_timestamp"] = socket.ntohl(struct.unpack('I',s[22:26])[0]) d["options_timestamp_ack"] = socket.ntohl(struct.unpack('I',s[26:30])[0]) d["options"] = "timestamp:%d timestamp_ack:%d" %(d["options_timestamp"],d["options_timestamp_ack"]) else: d['options']=None d['data'] = s[4*d['header_len']:] return d
def decode_ip_packet(s): d={} #---IP Header--- #d['version']=(ord(s[0]) & 0xf0) >> 4 #d['header_len']=ord(s[0]) & 0x0f #d['tos']=ord(s[1]) #d['total_len']=socket.ntohs(struct.unpack('H',s[2:4])[0]) #d['id']=socket.ntohs(struct.unpack('H',s[4:6])[0]) #d['flags']=(ord(s[6]) & 0xe0) >> 5 #d['fragment_offset']=socket.ntohs(struct.unpack('H',s[6:8])[0] & 0x1f) #d['ttl']=ord(s[8]) d['protocol']=ord(s[9]) #d['checksum']=socket.ntohs(struct.unpack('H',s[10:12])[0]) d['source_address']=pcap.ntoa(struct.unpack('i',s[12:16])[0]) d['destination_address']=pcap.ntoa(struct.unpack('i',s[16:20])[0]) #if d['header_len']>5: # d['options']=s[20:4*(d['header_len']-5)] #else: # d['options']=None #d['data']=s[4*d['header_len']:] #---TCP Header--- #The difference between ntohs and ntohl is the difference between 16bit and 32bit integers. #d['source_port'] = socket.ntohs(struct.unpack('H',s[20:22])[0]) #d['destination_port'] = socket.ntohs(struct.unpack('H',s[22:24])[0]) d['sequence_number'] = socket.ntohl(struct.unpack('I',s[24:28])[0]) d['ack_number'] = socket.ntohl(struct.unpack('I',s[28:32])[0]) return d
def main(): threads = int(sys.argv[2]) timeout = int(sys.argv[3]) if ',' in sys.argv[1]: host_list = sys.argv[1].split(',') for host in host_list: while(True): if activeCount() <= threads: Thread(target=modbus_scan, args=(host, timeout)).start() break else: continue elif '-' in sys.argv[1]: host_list = sys.argv[1].split('-') start_ip = socket.ntohl(struct.unpack('I', socket.inet_aton(str(host_list[0])))[0]) end_ip = socket.ntohl(struct.unpack('I', socket.inet_aton(str(host_list[1])))[0]) for host in range(start_ip, end_ip + 1): host = socket.inet_ntoa(struct.pack('I', socket.htonl(host))) while (True): if activeCount() <= threads: Thread(target=modbus_scan, args=(host, timeout)).start() break else: continue else: host = sys.argv[1] modbus_scan(host, timeout) while(True): if activeCount() < 2: return 1
def BuildHostRange(strHost): slash=[] startIpStr="" endIpStr="" ranges=0 submask=0 realStartIP=0 realEndIP=0 if strHost.find('-')>0: slash = strHost.split('-') startIpStr=slash[0] endIpStr=slash[1] else: startIpStr=strHost try: startIpStr=socket.gethostbyname(startIpStr) if strHost.find('-')>0: realStartIP = socket.ntohl(struct.unpack('I',socket.inet_aton(startIpStr))[0]) realEndIP = socket.ntohl(struct.unpack('I',socket.inet_aton(endIpStr))[0]) else: realStartIP=realEndIP=socket.ntohl(struct.unpack('I',socket.inet_aton(startIpStr))[0]) except: return [0,0] return [realStartIP,realEndIP]
def buildKZorpMessage(self): """<method internal="yes"> </method> """ messages = [] flags = 0 if self.umbrella: flags = kznf.kznfnetlink.KZF_ZONE_UMBRELLA if self.admin_parent: parent_name = self.admin_parent.name else: parent_name = None if self.address: address = ntohl(self.address.ip) mask = ntohl(self.address.mask) else: address = None mask = None messages.append((kznf.kznfnetlink.KZNL_MSG_ADD_ZONE, kznf.kznfnetlink.create_add_zone_msg(self.getName(), flags, address, mask, self.name, parent_name))) for i in self.inbound_services.keys(): messages.append((kznf.kznfnetlink.KZNL_MSG_ADD_ZONE_SVC_IN, kznf.kznfnetlink.create_add_zone_svc_msg(self.name, i))) for i in self.outbound_services.keys(): messages.append((kznf.kznfnetlink.KZNL_MSG_ADD_ZONE_SVC_OUT, kznf.kznfnetlink.create_add_zone_svc_msg(self.name, i))) return messages
def parse_ir(data, dlen): global last_ir stamp = socket.ntohl(struct.unpack('<L', data[0:4])[0]) format = struct.unpack('<B', data[4:5])[0] nr_bits = struct.unpack('<B', data[5:6])[0] code = socket.ntohl(struct.unpack('<L', data[6:10])[0]) if code not in IR.codes_debug: print('stamp %d' % stamp) print('format %d' % format) print('nr bits %d' % nr_bits) print('UNKNOWN ir code %d' % code) last_ir = None return None stress = 0 if last_ir and last_ir[0] == code: # the same key was pressed again. if it was done fast enough, # then we *guess* that the user is keeping it pressed, rather # than hitting it again real fast. unfortunately the remote # doesn't generate key release events. #print('Stamp %d, diff %d' % (stamp, stamp - last_ir[1])) if stamp - last_ir[1] < 130: # milliseconds # the threshold can't be set below 108 which seems to be the # rate at which the SB3 generates remote events. at the same # time it is quite impossible to manually hit keys faster # than once per 140ms, so 130ms should be a good threshold. stress = last_ir[2] + 1 else: stress = 0 last_ir = (code, stamp, stress) return Tactile(code, stress)
def pb2dict(pb, pretty = False, is_hex = False): """ Convert protobuf msg to dictionary. Takes a protobuf message and returns a dict. """ d = collections.OrderedDict() if pretty else {} for field, value in pb.ListFields(): if field.label == FD.LABEL_REPEATED: d_val = [] if pretty and _marked_as_ip(field): if len(value) == 1: v = socket.ntohl(value[0]) addr = ipaddr.IPv4Address(v) else: v = 0 + (socket.ntohl(value[0]) << (32 * 3)) + \ (socket.ntohl(value[1]) << (32 * 2)) + \ (socket.ntohl(value[2]) << (32 * 1)) + \ (socket.ntohl(value[3])) addr = ipaddr.IPv6Address(v) d_val.append(addr.compressed) else: for v in value: d_val.append(_pb2dict_cast(field, v, pretty, is_hex)) else: d_val = _pb2dict_cast(field, value, pretty, is_hex) d[field.name] = d_val return d
def getRoutes(): """Reads the routing table from /proc""" routes = [] f=open("/proc/net/route","r") for l in f.readlines()[1:]: # Parse the line iface,network,gateway,flags,x,x,metric,mask,x,x,x = l.split() # Parse the flags flags = int(flags, 16) flag_str = "" for flag, char in ROUTE_FLAG_CHARS.items(): if (flags & flag)==flag: flag_str += char # Store the values route = {} route["network"] = formatIP(socket.ntohl(long(network, 16))) route["gateway"] = formatIP(socket.ntohl(long(gateway, 16))) route["netmask"] = formatIP(socket.ntohl(long(mask, 16))) route["iface"] = iface route["metric"] = metric route["flags"] = flag_str routes.append(route) f.close() # Kernel gives us a list sorted by netmask length, sort by prefix # as well routes.sort(route_cmp) return routes
def get_full_msg_packet_hdr(nfa): pkg_hdr = get_msg_packet_hdr(nfa) return { 'packet_id' : ntohl(pkg_hdr.contents.packet_id), 'hw_protocol' : ntohl(pkg_hdr.contents.hw_protocol), 'hook' : pkg_hdr.contents.hook }
def find(self,ip,ovs_info): int_ip = socket.ntohl(struct.unpack('i',socket.inet_aton(ip))[0]) for ovs in ovs_info: start = socket.ntohl(struct.unpack('i',socket.inet_aton(ovs['OVS_Start_Ip']))[0]) end = socket.ntohl(struct.unpack('i',socket.inet_aton(ovs['OVS_End_Ip']))[0]) if start <= int_ip and int_ip >= end: return ovs return None
def convert_integer(): data = 1234; #32bit print "Original: %s => Long host byte order: %s, Network byte order: %s" \ %(data, socket.ntohl(data), socket.htonl(data)) #16bit print "Original: %s => Short host bype order: %s, Network byte order: %s" \ %(data, socket.ntohl(data), socket.htonl(data))
def parse_message_choke(self, stream, n, length): index = ntohl(struct.unpack('I', stream[n+5:n+9])[0]) begin = ntohl(struct.unpack('I', stream[n+9:n+13])[0]) length = ntohl(struct.unpack('I', stream[n+13:n+17])[0]) self.logger.info( '[MESSAGE] CANCEL: index={} begin={} length={}'.format( index, begin, length)) self.__new_message('cancel', index=index, begin=begin, length=length)
def ipv6_from_string(ipv6_string): data = socket.inet_pton(socket.AF_INET6, ipv6_string) ipv6_n = struct.unpack('IIII', data) ipv6 = (socket.ntohl(ipv6_n[0]), socket.ntohl(ipv6_n[1]), socket.ntohl(ipv6_n[2]), socket.ntohl(ipv6_n[3])) return ipv6
def dhcp_wan_ip_should_in_ip_pool(self, start_ip, end_ip, ip): if ip == '0.0.0.0': raise RuntimeError('the wan ip not in dhcp range') start = socket.ntohl(struct.unpack("I", socket.inet_aton(str(start_ip)))[0]) end = socket.ntohl(struct.unpack("I", socket.inet_aton(str(end_ip)))[0]) ip = socket.ntohl(struct.unpack("I", socket.inet_aton(str(ip)))[0]) if ip < start and ip > end: raise RuntimeError('the wan ip not in dhcp range')
def parse_message_reject(self, stream, n, length): index = ntohl(struct.unpack('I', stream[n+5:n+9])[0]) begin = ntohl(struct.unpack('I', stream[n+9:n+13])[0]) length = ntohl(struct.unpack('I', stream[n+13:n+17])[0]) self.logger.info( '[MESSAGE] REJECT: index={} begin={} length={}'.format( index, begin, length)) self.__new_message('reject')
def gen_ip_by_range(seg): seg_lst = seg.split('-') ip_start = seg_lst[0].strip() ip_end = seg_lst[1].strip() start = socket.ntohl(struct.unpack("I", socket.inet_aton(str(ip_start)))[0]) end = socket.ntohl(struct.unpack("I", socket.inet_aton(str(ip_end)))[0]) for key in xrange(end - start + 1): yield socket.inet_ntoa(struct.pack('I', socket.htonl(start + key)))
def _get_pcap_rec_header(pcap_rec_header): rec_hdr_as_dict = { 'ts_sec' : socket.ntohl(pcap_rec_header[0]), 'ts_usec': socket.ntohl(pcap_rec_header[1]), 'incl_len': socket.ntohl(pcap_rec_header[2]), 'orig_len': socket.ntohl(pcap_rec_header[3]) } return rec_hdr_as_dict
def _GetS64(demarsh): import socket val1 = socket.ntohl(demarsh.GetU32()) val2 = socket.ntohl(demarsh.GetU32()) fullVal = val2 << 32 | val1 if fullVal & 9223372036854775808: fullVal = (fullVal & 9223372036854775807) - 9223372036854775808 return fullVal
def read_routes(): try: f=open("/proc/net/route", "rb") except IOError: warning("Can't open /proc/net/route !") return [] routes = [] s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x", LOOPBACK_NAME.encode("utf8"))) addrfamily = struct.unpack("h",ifreq[16:18])[0] if addrfamily == socket.AF_INET: ifreq2 = ioctl(s, SIOCGIFNETMASK,struct.pack("16s16x", LOOPBACK_NAME.encode("utf8"))) msk = socket.ntohl(struct.unpack("I",ifreq2[20:24])[0]) dst = socket.ntohl(struct.unpack("I",ifreq[20:24])[0]) & msk ifaddr = scapy.utils.inet_ntoa(ifreq[20:24]) routes.append((dst, msk, "0.0.0.0", LOOPBACK_NAME, ifaddr, 1)) else: warning("Interface lo: unkown address family (%i)"% addrfamily) for l in f.readlines()[1:]: l = plain_str(l) iff,dst,gw,flags,x,x,metric,msk,x,x,x = l.split() flags = int(flags,16) if flags & RTF_UP == 0: continue if flags & RTF_REJECT: continue try: ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x", iff.encode("utf8"))) except IOError: # interface is present in routing tables but does not have any assigned IP ifaddr="0.0.0.0" else: addrfamily = struct.unpack("h",ifreq[16:18])[0] if addrfamily == socket.AF_INET: ifaddr = scapy.utils.inet_ntoa(ifreq[20:24]) else: warning("Interface %s: unkown address family (%i)", iff, addrfamily) continue # Attempt to detect an interface alias based on addresses inconsistencies dst_int = socket.htonl(int(dst, 16)) & 0xffffffff msk_int = socket.htonl(int(msk, 16)) & 0xffffffff ifaddr_int = struct.unpack("!I", ifreq[20:24])[0] gw_str = scapy.utils.inet_ntoa(struct.pack("I", int(gw, 16))) metric = int(metric) if ifaddr_int & msk_int != dst_int: tmp_route = get_alias_address(iff, dst_int, gw_str, metric) if tmp_route: routes.append(tmp_route) else: routes.append((dst_int, msk_int, gw_str, iff, ifaddr, metric)) else: routes.append((dst_int, msk_int, gw_str, iff, ifaddr, metric)) f.close() return routes
def ip2sql(ip_begin, ip_end): #filepath = "geoip_" + ip_begin + ".txt" #fp = open(filepath, 'w') ip_b = socket.ntohl(struct.unpack("I",socket.inet_aton(ip_begin))[0]) ip_e = socket.ntohl(struct.unpack("I",socket.inet_aton(ip_end))[0]) while True: ip_b = line2sql_sina(ip_b) if ip_b >= ip_e: break
def convert_integer(): data = 1234 #32-bit print "Original: %s => Long host byte order: %s, Network byte order: %s"\ %(data, socket.ntohl(data), socket.ntohl(data)) #16-bit print "Original: %s => Long host byte order: %s, Network byte order: %s"\ %(data, socket.ntohs(data), socket.ntohs(data))
def addr_tuple_from_sockaddr_u(su): if su.ss.ss_family == socket.AF_INET6: return (inet_ntop(socket.AF_INET6, su.s6.sin6_addr), socket.ntohs(su.s6.sin6_port), socket.ntohl(su.s6.sin6_flowinfo), socket.ntohl(su.s6.sin6_scope_id)) assert su.ss.ss_family == socket.AF_INET return inet_ntop(socket.AF_INET, su.s4.sin_addr), \ socket.ntohs(su.s4.sin_port)
def parse_message_piece(self, stream, n, length): index = ntohl(struct.unpack('I', stream[n+5:n+9])[0]) begin = ntohl(struct.unpack('I', stream[n+9:n+13])[0]) block_size = length - 1 - 8 data = stream[n+13:n+13+length-1-8] assert(len(data) == block_size) self.logger.info( '[MESSAGE] PIECE: index={} begin={} length={}'.format( index, begin, block_size)) self.__new_message('piece', index=index, begin=begin, data=data)
def parseNetflow5Packet(self, packet): # parse to Header , Records header = {} header['SysUpTime'] = socket.ntohl(struct.unpack('I',packet[4:8])[0]) # fix time to localtime zone #header['EpochSeconds'] = socket.ntohl(struct.unpack('I',packet[8:12])[0]) - (time.timezone) header['EpochSeconds'] = socket.ntohl(struct.unpack('I',packet[8:12])[0]) return (header,packet[SIZE_OF_HEADER:])
def inet_calcNetBroad (ip, nm): (ipaddr,) = struct.unpack('!I', socket.inet_pton(socket.AF_INET, ip)) ipaddr = socket.ntohl(ipaddr) (nmaddr,) = struct.unpack('!I', socket.inet_pton(socket.AF_INET, nm)) nmaddr = socket.ntohl(nmaddr) netaddr = ipaddr & nmaddr bcaddr = netaddr | (~nmaddr) nw = socket.inet_ntop(socket.AF_INET, struct.pack('I', netaddr)) bc = socket.inet_ntop(socket.AF_INET, struct.pack('I', bcaddr)) return (nw, bc)
def nToIP(n): ipint = socket.ntohl(n) return '.'.join([str(ipint >> (i << 3) & 0xFF) for i in range(4)[::-1]])
def unpack_long(self): msg, = struct.unpack( "l", self.__data[self.__msg_cur_offset:self.__msg_cur_offset + 4]) msg = socket.ntohl(msg) self.__msg_cur_offset += 4 return msg
def dataReceived(self, data): global lastMSSQL tds_type, size = struct.unpack('!BxH', data[:4]) if(size == len(data)): p1 = 8 nexttoken = 0 if(tds_type == 0x12): tds_response_created = 0 p2 = p1 + 6; logprint("TDS 7/8 Prelogin packet on port %d from: %s (%d/TCP):" % (self.transport.getHost().port, self.transport.getPeer().host, self.transport.getPeer().port)) while nexttoken != 0xff: tokentype, p, l, nexttoken = struct.unpack('!BHHB', data[p1:p2]) if tokentype == 0: maj, minor = struct.unpack('!LH', data[p + 8:p + l + 8]) tds_response = tds_response_a + binascii.hexlify(data[p + 8:p + l + 8]) + '0200' tds_response_created = 1 print "\tVersion:\n\t\tMaj: %s\n\t\tMin: %s" % (hex(socket.ntohl(maj)), hex(socket.ntohl(minor))) if tokentype == 1: enc, = struct.unpack('!B', data[p + 8:p + l + 8]) print "\tEncryption: ", enctype[enc] if (tokentype == 2) & (l > 1): print "\tInstance: ", data[p + 8:p + l + 8] if tokentype == 3: threadid, = struct.unpack('!L', data[p + 8:p + l + 8]) print "\tThread ID: ", threadid if tokentype == 4: mars, = struct.unpack('!B', data[p + 8:p + l + 8]) print "\tMARS: ", marstype[mars] p1 = p2 - 1 p2 = p1 + 6 if tds_response_created == 0: tds_response = tds_response_a + '080002fe00000200' self.transport.write(binascii.unhexlify(tds_response)) elif(tds_type == 0x10): p2 = p1 + 36 logprint("TDS 7/8 Login packet on port %d from: %s (%d/TCP):" % (self.transport.getHost().port, self.transport.getPeer().host, self.transport.getPeer().port)) if len(data) > p2: l, v, ps, cv, pid, cid, o1, o2, o3, r, tz, lc = struct.unpack('=LLLLLLBBBBLL', data[p1:p2]) print '\tLen: ', l print '\tVersion: ', hex(socket.ntohl(v)) print '\tPacket Size: ', ps print '\tClient Version: ', socket.ntohl(cv) print '\tClient PID: ', pid print '\tConnection ID: ', cid print '\tOption Flag 1: ', o1 print '\tOption Flag 2: ', o2 print '\tOption Flag 3: ', o3 print '\tType Flag: ', r print '\tClient TZ: ', tz print '\tClient Language Code: ', lc p1 = p2 p2 = p1 + 4 for n in logindata: o, l = struct.unpack('=HH', data[p1:p2]) if l > 0: if n == 'Password': pw = '' p = data[o + 8:o + (2 * l) + 8] for byte in p: b = ord(byte) ^ 0xa5 reverse_b = (b & 0xf) << 4 | (b & 0xf0) >> 4 pw = pw + chr(reverse_b) print '\t%s: %s' % (n, pw.encode("utf-8")) else: s = data[o + 8:o + (2 * l) + 8] print '\t%s: %s' % (n, s.encode("utf-8")) p1 = p2 p2 = p1 + 4 print '\tClient ID: ', binascii.hexlify(data[p1:p1+6]) self.transport.loseConnection() if(lastMSSQL != self.transport.getPeer().host): lastMSSQL = self.transport.getPeer().host thread.start_new_thread(twitter_it, ("A host at %s (%s, %s - %s) tried to log into my honeypot's fake MSSQL Server... #netmenaces", lastMSSQL)) else: logprint("TCPData on port %d from: %s (%d/TCP):\n%s" % (self.transport.getHost().port, self.transport.getPeer().host, self.transport.getPeer().port, binascii.hexlify(data))) self.transport.loseConnection()
def _receive_non_blocking(self): """ Receive a message from the TCP connection (non-blocking), assumes the following messaging format: | length (4-bytes) | string of bytes | """ if self._socket is None: return None message = None self._socket.setblocking(False) try: if -1 == self._msg_len_remaining: if 0 == self._msg_len: read_len = struct.calcsize('!L') else: read_len = struct.calcsize('!L') - self._msg_len msg_block = self._socket.recv(read_len) if 0 == len(msg_block): DLOG.verbose("Connection closed.") self.close() else: self._msg_parts.append(msg_block) msg = b"".join(self._msg_parts) self._msg_len = len(msg_block) if struct.calcsize('!L') == len(msg): self._msg_parts[:] = list() self._msg_len = socket.ntohl( struct.unpack('!L', msg)[0]) self._msg_len_remaining = self._msg_len else: msg_block = self._socket.recv(self._msg_len_remaining) if 0 == len(msg_block): DLOG.verbose("Connection closed.") self.close() else: self._msg_parts.append(msg_block) self._msg_len_remaining -= len(msg_block) if 0 == self._msg_len_remaining: msg = b"".join(self._msg_parts) self._msg_parts[:] = list() self._msg_len = 0 self._msg_len_remaining = -1 if self._auth_key is None: message = msg else: auth_vector = msg[:self.AUTH_VECTOR_MAX_SIZE] message = msg[self.AUTH_VECTOR_MAX_SIZE:] expected = hmac.new( self._auth_key, msg=message, digestmod=hashlib.sha512).digest() if auth_vector != expected: auth_vector_str = base64.b64encode(auth_vector) expected_str = base64.b64encode(expected) DLOG.info( "Authorization vector mismatch, msg=%s, " "auth_vector=%s, expected=%s." % (message, auth_vector_str, expected_str)) message = None except socket.timeout as e: DLOG.info("TCP socket timeout, ip=%s, por=%s, error=%s." % (self._ip, self._port, e)) except socket.error as e: DLOG.error("TCP socket error, ip=%s, port=%s, error=%s." % (self._ip, self._port, e)) self.close() finally: if self._socket is not None: self._socket.setblocking(self._blocking) return message
def ntohll(val): return (socket.ntohl(val & 0xFFFFFFFF) << 32) + (socket.ntohl(val >> 32))
def e_rwnak(self): return (socket.ntohl(self.control) >> 17) & 1
def main(): # create a list of logs we can append json to and call for a post when we want. logcache = Queue() logger.info('started') sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('0.0.0.0', int(options.netflowport))) # start a process to post our stuff. logcache = JoinableQueue() postingProcess = Process(target=postLogs, args=(logcache, ), name="netflow2MozdefMQPost") postingProcess.start() while True: try: buf, address = sock.recvfrom(1500) netflowsource = address[0] netflowsource = socket.getfqdn(netflowsource) #is the sender in a whitelist of accepted senders? if len(options.senderwhitelist) > 0: if netflowsource not in options.senderwhitelist.split(','): logger.debug('ignoring: {0}'.format(netflowsource)) continue header = {} # NetFlow export format version number # Number of flows exported in this packet (1-30) (header['version'], header['count']) = struct.unpack('!HH', buf[0:4]) if header['version'] != 5: logger.error("Not NetFlow v5!") continue # It's pretty unlikely you'll ever see more then 1000 records in a 1500 byte UDP packet if header['count'] <= 0 or header['count'] >= 1000: logger.error("Invalid count %s" % header['count']) continue # Current time in milliseconds since the export device booted header['uptime'] = socket.ntohl(struct.unpack('I', buf[4:8])[0]) # Current count of seconds since 0000 UTC 1970 header['unixseconds'] = socket.ntohl( struct.unpack('I', buf[8:12])[0]) # Residual nanoseconds since 0000 UTC 1970 header['unixnanoseconds'] = socket.ntohl( struct.unpack('I', buf[12:16])[0]) # Sequence counter of total flows seen header['flowsequence'] = socket.ntohl( struct.unpack('I', buf[16:20])[0]) # Type of flow-switching engine header['enginetype'] = socket.ntohl(struct.unpack('B', buf[20])[0]) # Slot number of the flow-switching engine header['engineid'] = socket.ntohl(struct.unpack('B', buf[21])[0]) # First two bits hold the sampling mode; remaining 14 bits hold value of sampling interval header['samplinginterval'] = struct.unpack( '!H', buf[22:24])[0] & 0b0011111111111111 for i in range(0, header['count']): try: base = SIZE_OF_HEADER + (i * SIZE_OF_RECORD) data = struct.unpack('!IIIIHH', buf[base + 16:base + 36]) data2 = struct.unpack('!BBBHHBB', buf[base + 37:base + 46]) record = header # Netflow source record['hostname'] = netflowsource # Source IP addressess record['sourceipaddress'] = inet_ntoa(buf[base + 0:base + 4]) # Destination IP addressess record['destinationipaddress'] = inet_ntoa(buf[base + 4:base + 8]) # IP addressess of next hop router record['nexthop'] = inet_ntoa(buf[base + 8:base + 12]) # Packets in the flow record['packets'] = data[0] # Total number of Layer 3 bytes in the packets of the flow record['octets'] = data[1] # SysUptime at start of flow record['first'] = data[2] # SysUptime at the time the last packet of the flow was received record['last'] = data[3] # TCP/UDP source port number or equivalent record['sourceport'] = data[4] # TCP/UDP destination port number or equivalent record['destinationport'] = data[5] # Cumulative OR of TCP flags record['tcpflags'] = data2[0] # IP protocol type (for example, TCP = 6; UDP = 17) record['protocol'] = data2[1] # IP type of service (ToS) record['tos'] = data2[2] # Autonomous system number of the source, either origin or peer record['sourceasn'] = data2[3] # Autonomous system number of the destination, either origin or peer record['destinationasn'] = data2[4] # Source addressess prefix mask bits record['sourcemask'] = data2[5] # Destination addressess prefix mask bits record['destinationmask'] = data2[6] #publish record if str(record['sourceport'] ) not in options.sourceportignore.split(','): nfevent = dict( utctimestamp=toUTC(datetime.now()).isoformat()) nfevent['tags'] = ['netflow', 'network'] nfevent['category'] = 'netflow' nfevent['summary'] = '{0}:{1} --> {2}:{3}'.format( record['sourceipaddress'], record['sourceport'], record['destinationipaddress'], record['destinationport']) nfevent['details'] = record logcache.put(json.dumps(nfevent)) logger.debug(json.dumps(nfevent)) except Exception as e: logger.error('%r' % e) continue except KeyboardInterrupt: sys.exit(1) except ValueError as e: logger.fatal('Exception while handling netflow message: %r' % e) sys.exit(1) logger.info('finished')
def read_routes(): try: f = open("/proc/net/route", "rb") except IOError: warning("Can't open /proc/net/route !") return [] routes = [] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: ifreq = ioctl( s, SIOCGIFADDR, struct.pack("16s16x", conf.loopback_name.encode("utf8"))) # noqa: E501 addrfamily = struct.unpack("h", ifreq[16:18])[0] if addrfamily == socket.AF_INET: ifreq2 = ioctl( s, SIOCGIFNETMASK, struct.pack("16s16x", conf.loopback_name.encode("utf8"))) # noqa: E501 msk = socket.ntohl(struct.unpack("I", ifreq2[20:24])[0]) dst = socket.ntohl(struct.unpack("I", ifreq[20:24])[0]) & msk ifaddr = scapy.utils.inet_ntoa(ifreq[20:24]) routes.append((dst, msk, "0.0.0.0", conf.loopback_name, ifaddr, 1)) # noqa: E501 else: warning("Interface %s: unknown address family (%i)" % (conf.loopback_name, addrfamily)) # noqa: E501 except IOError as err: if err.errno == 99: warning("Interface %s: no address assigned" % conf.loopback_name) # noqa: E501 else: warning("Interface %s: failed to get address config (%s)" % (conf.loopback_name, str(err))) # noqa: E501 for line in f.readlines()[1:]: line = plain_str(line) iff, dst, gw, flags, _, _, metric, msk, _, _, _ = line.split() flags = int(flags, 16) if flags & RTF_UP == 0: continue if flags & RTF_REJECT: continue try: ifreq = ioctl(s, SIOCGIFADDR, struct.pack("16s16x", iff.encode("utf8"))) # noqa: E501 except IOError: # interface is present in routing tables but does not have any assigned IP # noqa: E501 ifaddr = "0.0.0.0" ifaddr_int = 0 else: addrfamily = struct.unpack("h", ifreq[16:18])[0] if addrfamily == socket.AF_INET: ifaddr = scapy.utils.inet_ntoa(ifreq[20:24]) ifaddr_int = struct.unpack("!I", ifreq[20:24])[0] else: warning("Interface %s: unknown address family (%i)", iff, addrfamily) # noqa: E501 continue # Attempt to detect an interface alias based on addresses inconsistencies # noqa: E501 dst_int = socket.htonl(int(dst, 16)) & 0xffffffff msk_int = socket.htonl(int(msk, 16)) & 0xffffffff gw_str = scapy.utils.inet_ntoa(struct.pack("I", int(gw, 16))) metric = int(metric) if ifaddr_int & msk_int != dst_int: tmp_route = get_alias_address(iff, dst_int, gw_str, metric) if tmp_route: routes.append(tmp_route) else: routes.append((dst_int, msk_int, gw_str, iff, ifaddr, metric)) else: routes.append((dst_int, msk_int, gw_str, iff, ifaddr, metric)) f.close() s.close() return routes
""" If you ever need to write a low-level network application, it may be necessary to handle the low-level data transmission over the wire between two machines. This operation requires some sort of conversion of data from the native host operating system to the network format and vice versa. This is because each one has its own specific representation of data. """ import socket data = 1234 # 32-bit print "Original: %s => Long host byte order: %s, Network byte order: %s"\ %(data, socket.ntohl(data), socket.htonl(data)) # 16-bit print "Original: %s => Short host byte order: %s, Network byte order: %s"\ %(data, socket.ntohs(data), socket.htons(data))
def get(self): x_btn = self.get_argument("btn", "1") x_adid = self.get_argument("ad_id", '') x_perid = self.get_argument("per_id", '') x_pip = self.get_argument("p_ip", '') list = [] if (x_pip!=""): try: ipint = socket.ntohl(struct.unpack("i",socket.inet_aton(x_pip))[0]) except: ipint = 111 else: ipint = "" if x_btn == '1': cmd = "rm -rf /data/adsmart/log/*" ssh(host, port, user, passwd, cmd) self.render("click_info.html", ad_id = "", per_id = "", p_ip = "", show_log = "", ret = []) if x_btn == '2': time.sleep(10) result = getdb(x_adid,ipint) ad_ret = gen_ad_ret(result) tm = time.strftime("%Y%m%d",time.localtime(time.time())) if (x_adid!="" and x_perid!="" and ipint!=""): cmd = "cat /data/adsmart/log/%s* |grep cpc_click |grep %s|grep %s|grep %s" % (tm, x_adid, x_perid, ipint) elif (x_adid=="" and x_perid!="" and ipint!=""): cmd = "cat /data/adsmart/log/%s* |grep cpc_click |grep %s|grep %s" % (tm, x_perid, ipint) elif (x_adid!="" and x_perid=="" and ipint!=""): cmd = "cat /data/adsmart/log/%s* |grep cpc_click |grep %s|grep %s" % (tm, x_adid, ipint) elif (x_adid!="" and x_perid!="" and ipint==""): cmd = "cat /data/adsmart/log/%s* |grep cpc_click |grep %s|grep %s" % (tm, x_adid, x_perid) elif (x_adid=="" and x_perid=="" and ipint!=""): cmd = "cat /data/adsmart/log/%s* |grep cpc_click |grep %s" % (tm, ipint) elif (x_adid=="" and x_perid!="" and ipint==""): cmd = "cat /data/adsmart/log/%s* |grep cpc_click |grep %s" % (tm, x_perid) elif (x_adid!="" and x_perid=="" and ipint==""): cmd = "cat /data/adsmart/log/%s* |grep cpc_click |grep %s" % (tm, x_adid) else: cmd = "cat /data/adsmart/log/%s* |grep cpc_click" % (tm) x_log = ssh(host, port, user, passwd, cmd) for i in range(0, x_log.__len__()): zidian = {} str_1 = x_log[i].split(" ") mytime = convert_time(float(str_1[0])) zidian["lclick_time"] = mytime ipint = socket.inet_ntoa(struct.pack('I',socket.htonl(int(str_1[1])))) zidian["lip"] = ipint zidian["lpermanent_id"] = str_1[3] zidian["ladid"] = str_1[4] zidian["lcost"] = int(str_1[5])/10000 print zidian["lcost"] zidian["lthroughid"] = str_1[14] zidian["lurl"] = str_1[16] list.append(zidian) self.render("click_info.html", ad_id = x_adid, per_id = x_perid, p_ip = x_pip, show_log = list, ret = ad_ret)
def ip_ntostr(ip_address): if isinstance(ip_address, ct.c_uint): ip_address = ip_address.value return ipaddress.ip_address(socket.ntohl(ip_address))
#!/usr/bin/env python3 import socket import json HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() with conn: print('Connected by ', addr[0]) number = conn.recv(1024) print(int(number)) var1 = socket.ntohl(int(number)) conn.send(str(var1).encode()) s.close()
def ip_int_cmp(cls, ip1): # 两个ip的字符串表示,12.34.56.78 return socket.ntohl(struct.unpack("I", socket.inet_aton(ip1))[0])
def reverse(self, val): if self.size == 16: val = socket.ntohs(val) elif self.size == 32: val = socket.ntohl(val) return val
def e_len(self): return (socket.ntohl(self.control) >> 7) & 0x3FF
def decode_ip_packet(self, s): d = {} d['version'] = (ord(s[0]) & 0xf0) >> 4 d['header_len'] = ord(s[0]) & 0x0f #This is ip header length. 32bit d['tos'] = ord(s[1]) d['total_len'] = socket.ntohs(struct.unpack('H', s[2:4])[0]) d['id'] = socket.ntohs(struct.unpack('H', s[4:6])[0]) d['flags'] = (ord(s[6]) & 0xe0) >> 5 d['fragment_offset'] = socket.ntohs( struct.unpack('H', s[6:8])[0] & 0x1f) d['ttl'] = ord(s[8]) d['protocol'] = ord(s[9]) d['checksum'] = socket.ntohs(struct.unpack('H', s[10:12])[0]) d['source_address'] = pcap.ntoa(struct.unpack('i', s[12:16])[0]) d['destination_address'] = pcap.ntoa(struct.unpack('i', s[16:20])[0]) if d['header_len'] > 5: d['options'] = s[20:4 * (d['header_len'] - 5)] else: d['options'] = None d['data'] = s[4 * d['header_len']:] # UDP parser: if d['protocol'] == socket.IPPROTO_UDP: udp_data = d['data'] d['udp'] = {} d['udp']['source_port'] = socket.ntohs( struct.unpack('H', udp_data[0:2])[0]) d['udp']['dest_port'] = socket.ntohs( struct.unpack('H', udp_data[2:4])[0]) d['udp']['length'] = socket.ntohs( struct.unpack('H', udp_data[4:6])[0]) #including header and data d['udp']['headerlen'] = 2 # UDP header length. 32bit d['udp']['checksum'] = socket.ntohs( struct.unpack('H', udp_data[6:8])[0]) udp_payload = udp_data[8:] # UDP header contains 8 bytes header. if d['udp']['source_port'] == 53 or d['udp']['dest_port'] == 53: d['udp']['type'] = 'dns' elif d['udp']['source_port'] == 137 or d['udp']['dest_port'] == 137: d['udp']['type'] = 'nbns' elif d['udp']['source_port'] == 123 or d['udp']['dest_port'] == 123: d['udp']['type'] = 'ntp' elif d['destination_address'] == '224.0.0.251': d['udp']['type'] = 'mdns' elif d['destination_address'] == '239.255.255.250': d['udp']['type'] = 'ssdp' else: maybe_rtp = {} maybertp_flag_0 = (((ord(udp_payload[0]) & 0xC0) >> 6) == 2) # 32 is a normal rtp header length. maybertp_flag_1 = (len(udp_payload) > 12) maybertp_flag_2 = 0 maybertp_flag_3 = 0 if maybertp_flag_0 and maybertp_flag_1: maybe_rtp['total_len'] = d['udp'][ 'length'] - d['udp']['headerlen'] * 4 maybe_rtp['headerlen'] = 3 maybe_rtp['V'] = maybertp_flag_0 maybe_rtp['P'] = (ord(udp_payload[0]) & 0x20) >> 5 maybe_rtp['X'] = (ord(udp_payload[0]) & 0x10) >> 4 maybe_rtp['CC'] = (ord(udp_payload[0]) & 0xF) maybe_rtp['PT'] = (ord(udp_payload[1]) & 0x7F) maybe_rtp['SequenceNumber'] = socket.ntohs( struct.unpack('H', udp_payload[2:4])[0]) maybe_rtp['TimeStamp'] = socket.ntohl( struct.unpack('I', udp_payload[4:8])[0]) maybe_rtp['SSRC'] = socket.ntohl( struct.unpack('I', udp_payload[8:12])[0]) maybe_rtp['CSRC'] = [] maybertp_flag_2 = (maybe_rtp['PT'] >= 97) and (maybe_rtp['PT'] <= 200) #maybertp_flag_2 = True if maybertp_flag_2: for idx in range(maybe_rtp['CC']): maybe_rtp['CSRC'].append( socket.ntohl( struct.unpack( 'I', udp_payload[12 + idx * 4:16 + idx * 4])[0])) maybe_rtp['headerlen'] += 1 start_pos = 12 + maybe_rtp['CC'] * 4 payload_start_pos = start_pos if maybe_rtp['X'] == 1: maybe_rtp['headerlen'] += 1 maybe_rtp['X_LEN'] = socket.ntohs( struct.unpack( 'H', udp_payload[start_pos + 2:start_pos + 4])[0]) maybe_rtp['headerlen'] += maybe_rtp['X_LEN'] maybe_rtp['EX'] = udp_payload[start_pos + 4:start_pos + 4 + maybe_rtp['X_LEN'] * 4] payload_start_pos += (maybe_rtp['X_LEN'] + 1) * 4 else: maybe_rtp['X_LEN'] = 0 maybe_rtp['EX'] = [] if maybe_rtp['P'] == 1: maybe_rtp['P_len'] = ord(s[d['total_len'] - 1]) else: maybe_rtp['P_len'] = 0 # d['rtp']['payload_len'] = d['rtp']['total_len'] - d['udp']['headerlen'] * 4 - d['rtp']['P_len'] maybe_rtp['payload_len'] = maybe_rtp[ 'total_len'] - maybe_rtp['headerlen'] * 4 - maybe_rtp[ 'P_len'] maybe_rtp['payload'] = udp_payload[ payload_start_pos:payload_start_pos + 4 + maybe_rtp['payload_len']] if len(maybe_rtp['payload']) > 1: h264_payloas_first_octet = ord(maybe_rtp['payload'][0]) # 0x67 SPS, 0x68 PPS 0x65 IDR, 0x61 non-IDR maybertp_flag_3 = ( h264_payloas_first_octet == 0x67) or (h264_payloas_first_octet == 0x68) or ( h264_payloas_first_octet == 0x65) or (h264_payloas_first_octet == 0x61) maybe_rtp['payload'] = 0 #print "flag_0 : ", maybertp_flag_0 #print "flag_1 : ", maybertp_flag_1 #print "flag_2 : ", maybertp_flag_2 #print "flag_3 : ", maybertp_flag_3 if maybertp_flag_0 and maybertp_flag_1 and maybertp_flag_2 and maybertp_flag_3: d['udp']['type'] = 'rtp-h264' d['udp']['rtp'] = maybe_rtp pass else: d['udp']['type'] = 'other' return d
def e_seq(self): return socket.ntohl(self.control) >> 18
def dottedQuadToNum(ip): """Convert decimal dotted quad string to long integer""" return socket.ntohl(struct.unpack('=L', socket.inet_aton(ip))[0])
""" try: cryptor = AES.new(self.key, self.mode, self.key[:16]) # 使用BASE64对密文进行解码,然后AES-CBC解密 plain_text = cryptor.decrypt(base64.b64decode(text)) except Exception, e: #print e return ierror.WXBizMsgCrypt_DecryptAES_Error, None try: pad = ord(plain_text[-1]) # 去掉补位字符串 #pkcs7 = PKCS7Encoder() #plain_text = pkcs7.encode(plain_text) # 去除16位随机字符串 content = plain_text[16:-pad] xml_len = socket.ntohl(struct.unpack("I", content[:4])[0]) xml_content = content[4:xml_len + 4] from_appid = content[xml_len + 4:] # print xml_content except Exception, e: print e return ierror.WXBizMsgCrypt_IllegalBuffer, None if from_appid != appid: return ierror.WXBizMsgCrypt_ValidateAppid_Error, None return 0, xml_content def get_random_str(self): """ 随机生成16位字符串 @return: 16位字符串 """ rule = string.letters + string.digits
sys.path.append(".") from lib_ovs import * ofproto_dpif = get_ofproto_dpif("br") print("ofproto_dpif: %lx" % ofproto_dpif) ofproto = ofproto_dpif.up print("ofproto.type: %s" % ofproto.type) print(ofproto_dpif.sflow) # ofproto_dpif = container_of(ofproto.address_of_(), "struct ofproto_dpif", "up") parts = ofproto_dpif.uuid.parts print("%x-%x-%x-%x" % \ (ntohl(parts[0].value_()), ntohl(parts[1].value_()), ntohl(parts[2].value_()), ntohl(parts[3].value_()))) tables_version = ofproto.tables_version print("tables_version: %d" % tables_version) set_sflow = ofproto.ofproto_class.set_sflow print(address_to_name(hex(set_sflow.value_()))) set_tables_version = ofproto.ofproto_class.set_tables_version print(address_to_name(hex(set_tables_version.value_()))) # print(ofproto.ofproto_class)
def ipv4_from_string(ipv4_string): data = socket.inet_pton(socket.AF_INET, ipv4_string) ipv4_n = struct.unpack('I', data) ipv4 = socket.ntohl(ipv4_n[0]) return ipv4
def dottedQuadToLong(ip): "convert decimal dotted quad string to long integer" return ntohl(unpack('!L',inet_pton(AF_INET,ip))[0])
def convert_integer(): data = 1234 # 32-bit 网络字节序转换为长整形主机字节序 print "Original: %s => Long host byte order: %s, Network byte order: %s" % (data, socket.ntohl(data), socket.htonl(data)) # 16-bit print "Original: %s => Short host byte order: %s, Network byte order: %s" % (data, socket.ntohs(data), socket.htons(data))
def read_routes(): try: f = open("/proc/net/route", "rb") except IOError: warning("Can't open /proc/net/route !") return [] routes = [] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ifreq = ioctl(s, SIOCGIFADDR, struct.pack("16s16x", LOOPBACK_NAME.encode("utf8"))) addrfamily = struct.unpack("h", ifreq[16:18])[0] if addrfamily == socket.AF_INET: ifreq2 = ioctl(s, SIOCGIFNETMASK, struct.pack("16s16x", LOOPBACK_NAME.encode("utf8"))) msk = socket.ntohl(struct.unpack("I", ifreq2[20:24])[0]) dst = socket.ntohl(struct.unpack("I", ifreq[20:24])[0]) & msk ifaddr = scapy.utils.inet_ntoa(ifreq[20:24]) routes.append((dst, msk, "0.0.0.0", LOOPBACK_NAME, ifaddr, 1)) else: warning("Interface lo: unkown address family (%i)" % addrfamily) for l in f.readlines()[1:]: l = plain_str(l) iff, dst, gw, flags, x, x, metric, msk, x, x, x = l.split() flags = int(flags, 16) if flags & RTF_UP == 0: continue if flags & RTF_REJECT: continue try: ifreq = ioctl(s, SIOCGIFADDR, struct.pack("16s16x", iff.encode("utf8"))) except IOError: # interface is present in routing tables but does not have any assigned IP ifaddr = "0.0.0.0" else: addrfamily = struct.unpack("h", ifreq[16:18])[0] if addrfamily == socket.AF_INET: ifaddr = scapy.utils.inet_ntoa(ifreq[20:24]) else: warning("Interface %s: unkown address family (%i)", iff, addrfamily) continue # Attempt to detect an interface alias based on addresses inconsistencies dst_int = socket.htonl(int(dst, 16)) & 0xffffffff msk_int = socket.htonl(int(msk, 16)) & 0xffffffff ifaddr_int = struct.unpack("!I", ifreq[20:24])[0] gw_str = scapy.utils.inet_ntoa(struct.pack("I", int(gw, 16))) metric = int(metric) if ifaddr_int & msk_int != dst_int: tmp_route = get_alias_address(iff, dst_int, gw_str, metric) if tmp_route: routes.append(tmp_route) else: routes.append((dst_int, msk_int, gw_str, iff, ifaddr, metric)) else: routes.append((dst_int, msk_int, gw_str, iff, ifaddr, metric)) f.close() return routes
fd = os.open('Record.csv', os.O_RDWR | os.O_CREAT) with open('Record.zc', 'rb') as f: pos = 0 tot = os.path.getsize('Record.zc') print('Processing %d records' % (tot / 32)) while pos < tot: data = f.read(32) pos = pos + 32 p = 0 for d in data[0:27]: p = p + d p = p % 256 if data[0:3] != b'\xab\x00\x06': print('Invaild Header at %d, %s != ab0006' % (pos / 32, data[0:3].hex())) if p != data[27]: print('Invaild CRC at %d, %x != %s' % (pos / 32, p, data[27:28].hex())) os.write(fd, ("%s,%s,%s,%s,%s,%s,%s\r" % (socket.ntohl(bytetoint(data[19:23])) / 1000, socket.ntohl(bytetoint(data[3:7])) / 10000, socket.ntohl(bytetoint(data[7:11])) / 10000, socket.ntohl(bytetoint(data[11:15])) / 10000, socket.ntohl(bytetoint(data[15:19])) / 10000, socket.ntohl(bytetoint(data[23:27])) % 65536 / 1000, int(socket.ntohl(bytetoint(data[23:27])) / 65536) / 10000)).encode()) os.close(fd)
def get_ip_address(self): try: ip = inet_ntoa(pack('!I', ntohl(call(self._getIP4Address)))) except Exception, e: PRINT_EXCEPTION(e) ip = None
def get_ip(): """Generate a random IP address for attack vector.""" max = 4294967295 return socket.inet_ntoa( struct.pack('>L', socket.ntohl(random.randrange(1, max))))
def ntohl(self): """transform self.ipaddress by applying ntohl to it""" ip_int = int(self.ipaddress) self.ipaddresss = ipaddress.ip_address(socket.ntohl(ip_int)) return self
def check(self): # 测试 argv第一元素一定是'-h', 否则给出使用提示 if len(CheckArgv.lowercase_argv) <= 0: return False, "Invalid number of arguments!" if CheckArgv.lowercase_argv[0] != "-h": return False, "Argument must begin with -h or -H " if len(CheckArgv.lowercase_argv) < 2: return False, "host domain name or ip must be provided!" # 检查第二元素,应该是主机的描述。且是用逗号隔开的,连续数字或字母。 ip_p = re.compile( '^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$' ) domainname_p = re.compile('^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$') hostlist = CheckArgv.lowercase_argv[1].split(',')[:] for item in hostlist: if ip_p.match(item): # found an ip TargetHosts.hostip_list.append(item) #print("TargetHosts {}".format(TargetHosts.hostip_list)) elif domainname_p.match(item): # found a domainname TargetHosts.hostdomain_list.append(item) #print("TargetHostsDomain {}".format(TargetHosts.hostdomain_list)) elif re.search('-', item): # is range expr? startip = item.split('-')[0] endip = item.split('-')[1] if ip_p.match(startip) and ip_p.match(endip): startip_int = socket.ntohl( struct.unpack("I", socket.inet_aton(str(startip)))[0]) endip_int = socket.ntohl( struct.unpack("I", socket.inet_aton(str(endip)))[0]) if endip_int < startip_int: startip_int, endip_int = endip_int, startip_int # exchange for item1 in range(startip_int, endip_int + 1): ip_str = socket.inet_ntoa( struct.pack('I', socket.htonl(item1))) TargetHosts.hostip_list.append(ip_str) else: # not valid range return False, "Invalid host range! [{}]".format(item) #print("TargetHosts {}".format(TargetHosts.hostip_list)) else: return False, "Invalid hostname or host ip! [{}]".format(item) if len(CheckArgv.lowercase_argv) == 2: # no -p for i in range(DEFAULT_PORT_LOWERLIMIT, DEFAULT_PORT_UPPERLIMIT + 1): TargetHosts.port_list.append(i) return True, "Arguments check completed." if len(CheckArgv.lowercase_argv) == 3: if CheckArgv.lowercase_argv[2] == "-p": return False, "Port number or port range cannot be null!" else: return False, "Unknow switch! [{}]".format( CheckArgv.lowercase_argv[2]) if len(CheckArgv.lowercase_argv) == 4: # ports portlist = CheckArgv.lowercase_argv[3].split(',')[:] print(portlist) int_p = re.compile('^[0-9]+$') for item in portlist: if int_p.match(item): port_int = int(item) if port_int <= 65535 and port_int >= 0: TargetHosts.port_list.append(port_int) else: return False, "Port number should be no more than 65535, and not negative! [{}]".format( item) elif re.search('-', item): # port range expr? startport = item.split('-')[0] endport = item.split('-')[1] if int_p.match(startport) and int_p.match(endport): startport_int = int(startport) endport_int = int(endport) if startport_int > 65535 or startport_int < 0 or endport_int > 65535 or endport_int < 0: return False, "Port number should be no more than 65535, \ and not negative ! [{}]".format(item) if startport_int > endport_int: startport_int, endport_int = endport_int, startport_int for i in range(startport_int, endport_int + 1): TargetHosts.port_list.append(i) else: return False, "Invalid port range ![{}]".format(item) else: # not a valid port or port range return False, "Invalid port or port range ![{}]".format( item) return True, "Argument check completed."