Advertisement
opexxx

Pcredc.py

Jul 16th, 2014
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 26.13 KB | None | 0 0
  1. #! /usr/bin/env python
  2. # Pcredz 0.9
  3. # Created by Laurent Gaffie
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17.  
  18. try:
  19.     import pcap
  20. except ImportError:
  21.     print 'libpcap not installed.\ntry : apt-get remove python-pypcap && apt-get install python-libpcap\nOn Mac OS X download http://downloads.sourceforge.net/project/pylibpcap/pylibpcap/0.6.4/pylibpcap-0.6.4.tar.gz?r=&ts=1396732918&use_mirror=softlayer-dal \ntar xvf pylibpcap-0.6.4.tar.gz && cd pylibpcap-0.6.4\n./setup.py install'
  22.     exit()
  23. import logging
  24. import optparse
  25. import os
  26. import re
  27. import socket
  28. import struct
  29. import subprocess
  30. import sys
  31. import threading
  32. import time
  33. from base64 import b64decode
  34. from threading import Thread
  35.  
  36. def ShowWelcome():
  37.     Message = 'Pcredz 0.9\nAuthor: Laurent Gaffie\nPlease send bugs/comments/pcaps to: lgaffie@trustwave.com\nThis script will extract NTLM (http,ldap,smb,sql,etc), Kerberos,\nFTP, HTTP Basic and credit card data from a given pcap file or from a live interface.\n'
  38.     print Message
  39.  
  40. parser = optparse.OptionParser(usage='\npython %prog -f file.pcap\n%prog -d /tmp/pcap/\n%prog -i eth0',prog=sys.argv[0],)
  41. parser.add_option('-f', action="store", dest="fname", help = "Pcap file to parse", metavar="capture.pcap")
  42. parser.add_option('-d', action="store", dest="dir_path", help = "Pcap directory to parse recursivly", metavar="/home/pnt/pcap/")
  43. parser.add_option('-i', action="store", dest="interface", help = "interface for live capture", metavar="eth0")
  44. parser.add_option('-v', action="store_true", help="More verbose.", dest="Verbose")
  45. parser.add_option('-c', action="store_false", default='True', help = "deactivate CC number scanning (Can gives false positives!)", dest="activate_cc")
  46. parser.add_option('-t', action="store_true", help = "Include a timestamp in all generated messages (useful for correlation)", dest="timestamp")
  47.  
  48. options, args = parser.parse_args()
  49.  
  50. if options.fname is None and options.dir_path is None and options.interface is None:
  51.     print '\n\033[1m\033[31m -f or -d or -i mandatory option missing.\033[0m\n'
  52.     parser.print_help()
  53.     exit(-1)
  54.  
  55. if options.fname and options.dir_path:
  56.     print '\n\033[1m\033[31mYou can\'t use -f and -d at the same time.\033[0m\n'
  57.     parser.print_help()
  58.     exit(-1)
  59.  
  60. if options.fname and options.interface:
  61.     print '\n\033[1m\033[31mYou can\'t use -f and -i at the same time.\033[0m\n'
  62.     parser.print_help()
  63.     exit(-1)
  64.  
  65. if options.dir_path and options.interface:
  66.     print '\n\033[1m\033[31mYou can\'t use -i and -d at the same time.\033[0m\n'
  67.     parser.print_help()
  68.     exit(-1)
  69.  
  70. ShowWelcome()
  71. Verbose = options.Verbose
  72. fname = options.fname
  73. dir_path = options.dir_path
  74. interface = options.interface
  75. activate_cc = options.activate_cc
  76. timestamp = options.timestamp
  77. start_time = time.time()
  78.  
  79. Filename = str(os.path.join(os.path.dirname(__file__),"CredentialDump-Session.log"))
  80. l= logging.getLogger('Credential-Session')
  81. l.addHandler(logging.FileHandler(Filename,'a'))
  82.  
  83. if activate_cc:
  84.    print 'CC number scanning activated\n'
  85. else:
  86.    print 'CC number scanning is deactivated\n'
  87.  
  88. def PrintPacket(Filename,Message):
  89.     if Verbose == True:
  90.         return True
  91.     if os.path.isfile(Filename) == True:
  92.         with open(Filename,"r") as filestr:
  93.             if re.search(re.escape(Message), filestr.read()):
  94.                 filestr.close()
  95.                 return False
  96.             else:
  97.                 return True
  98.     else:
  99.         return True
  100.  
  101. def IsCookedPcap(version):
  102.     Cooked = re.search('Linux \"cooked\"', version)
  103.     TcpDump = re.search('Ethernet', version)
  104.     Wifi = re.search('802.11', version)
  105.     if Wifi:
  106.         print 'Using 802.11 format\n'
  107.         return 1
  108.     if Cooked:
  109.         print 'Using Linux Cooked format\n'
  110.         return 2
  111.     if TcpDump:
  112.         print 'Using TCPDump format\n'
  113.         return 3
  114.     else:
  115.         print 'Unknow format, trying TCPDump format\n'
  116.         return 3
  117.  
  118. protocols={6:'tcp',
  119.            17:'udp',
  120.            1:'icmp',
  121.            2:'igmp',
  122.            3:'ggp',
  123.            4:'ipcap',
  124.            5:'ipstream',
  125.            8:'egp',
  126.            9:'igrp',
  127.            29:'ipv6oipv4',
  128. }
  129.  
  130. def luhn(n):
  131.     r = [int(ch) for ch in str(n)][::-1]
  132.     return (sum(r[0::2]) + sum(sum(divmod(d*2,10)) for d in r[1::2])) % 10 == 0
  133.  
  134. def Is_Anonymous(data):
  135.     LMhashLen = struct.unpack('<H',data[14:16])[0]
  136.     if LMhashLen == 0 or LMhashLen == 1:
  137.         return False
  138.     else:
  139.         return True
  140.  
  141. def ParseNTLMHash(data,Challenge):
  142.     PacketLen = len(data)
  143.     if PacketLen > 0:
  144.         SSPIStart = data[:]
  145.         LMhashLen = struct.unpack('<H',data[14:16])[0]
  146.         LMhashOffset = struct.unpack('<H',data[16:18])[0]
  147.         LMHash = SSPIStart[LMhashOffset:LMhashOffset+LMhashLen].encode("hex").upper()
  148.         NthashLen = struct.unpack('<H',data[22:24])[0]
  149.         NthashOffset = struct.unpack('<H',data[24:26])[0]
  150.  
  151.     if NthashLen == 24:
  152.         NtHash = SSPIStart[NthashOffset:NthashOffset+NthashLen].encode("hex").upper()
  153.         DomainLen = struct.unpack('<H',data[30:32])[0]
  154.         DomainOffset = struct.unpack('<H',data[32:34])[0]
  155.         Domain = SSPIStart[DomainOffset:DomainOffset+DomainLen].replace('\x00','')
  156.         UserLen = struct.unpack('<H',data[38:40])[0]
  157.         UserOffset = struct.unpack('<H',data[40:42])[0]
  158.         User = SSPIStart[UserOffset:UserOffset+UserLen].replace('\x00','')
  159.         writehash = User+"::"+Domain+":"+LMHash+":"+NtHash+":"+Challenge
  160.         return "NTLMv1 complete hash is: %s\n"%(writehash), User+"::"+Domain
  161.  
  162.     if NthashLen > 60:
  163.         NtHash = SSPIStart[NthashOffset:NthashOffset+NthashLen].encode("hex").upper()
  164.         DomainLen = struct.unpack('<H',data[30:32])[0]
  165.         DomainOffset = struct.unpack('<H',data[32:34])[0]
  166.         Domain = SSPIStart[DomainOffset:DomainOffset+DomainLen].replace('\x00','')
  167.         UserLen = struct.unpack('<H',data[38:40])[0]
  168.         UserOffset = struct.unpack('<H',data[40:42])[0]
  169.         User = SSPIStart[UserOffset:UserOffset+UserLen].replace('\x00','')
  170.         writehash = User+"::"+Domain+":"+Challenge+":"+NtHash[:32]+":"+NtHash[32:]
  171.         return "NTLMv2 complete hash is: %s\n"%(writehash),User+"::"+Domain
  172.     else:
  173.         return False
  174.  
  175. def ParseMSKerbv5TCP(Data):
  176.     MsgType = Data[21:22]
  177.     EncType = Data[43:44]
  178.     MessageType = Data[32:33]
  179.     if MsgType == "\x0a" and EncType == "\x17" and MessageType =="\x02":
  180.         if Data[49:53] == "\xa2\x36\x04\x34" or Data[49:53] == "\xa2\x35\x04\x33":
  181.             HashLen = struct.unpack('<b',Data[50:51])[0]
  182.             if HashLen == 54:
  183.                 Hash = Data[53:105]
  184.                 SwitchHash = Hash[16:]+Hash[0:16]
  185.                 NameLen = struct.unpack('<b',Data[153:154])[0]
  186.                 Name = Data[154:154+NameLen]
  187.                 DomainLen = struct.unpack('<b',Data[154+NameLen+3:154+NameLen+4])[0]
  188.                 Domain = Data[154+NameLen+4:154+NameLen+4+DomainLen]
  189.                 BuildHash = "$krb5pa$23$"+Name+"$"+Domain+"$dummy$"+SwitchHash.encode('hex')
  190.                 return 'MSKerb hash found: %s\n'%(BuildHash),"$krb5pa$23$"+Name+"$"+Domain+"$dummy$"
  191.         if Data[44:48] == "\xa2\x36\x04\x34" or Data[44:48] == "\xa2\x35\x04\x33":
  192.             HashLen = struct.unpack('<b',Data[45:46])[0]
  193.             if HashLen == 53:
  194.                 Hash = Data[48:99]
  195.                 SwitchHash = Hash[16:]+Hash[0:16]
  196.                 NameLen = struct.unpack('<b',Data[147:148])[0]
  197.                 Name = Data[148:148+NameLen]
  198.                 DomainLen = struct.unpack('<b',Data[148+NameLen+3:148+NameLen+4])[0]
  199.                 Domain = Data[148+NameLen+4:148+NameLen+4+DomainLen]
  200.                 BuildHash = "$krb5pa$23$"+Name+"$"+Domain+"$dummy$"+SwitchHash.encode('hex')
  201.                 return 'MSKerb hash found: %s\n'%(BuildHash),"$krb5pa$23$"+Name+"$"+Domain+"$dummy$"
  202.             if HashLen == 54:
  203.                 Hash = Data[53:105]
  204.                 SwitchHash = Hash[16:]+Hash[0:16]
  205.                 NameLen = struct.unpack('<b',Data[148:149])[0]
  206.                 Name = Data[149:149+NameLen]
  207.                 DomainLen = struct.unpack('<b',Data[149+NameLen+3:149+NameLen+4])[0]
  208.                 Domain = Data[149+NameLen+4:149+NameLen+4+DomainLen]
  209.                 BuildHash = "$krb5pa$23$"+Name+"$"+Domain+"$dummy$"+SwitchHash.encode('hex')
  210.                 return 'MSKerb hash found: %s\n'%(BuildHash),"$krb5pa$23$"+Name+"$"+Domain+"$dummy$"
  211.  
  212.         else:
  213.             Hash = Data[48:100]
  214.             SwitchHash = Hash[16:]+Hash[0:16]
  215.             NameLen = struct.unpack('<b',Data[148:149])[0]
  216.             Name = Data[149:149+NameLen]
  217.             DomainLen = struct.unpack('<b',Data[149+NameLen+3:149+NameLen+4])[0]
  218.             Domain = Data[149+NameLen+4:149+NameLen+4+DomainLen]
  219.             BuildHash = "$krb5pa$23$"+Name+"$"+Domain+"$dummy$"+SwitchHash.encode('hex')
  220.             return 'MSKerb hash found: %s\n'%(BuildHash),"$krb5pa$23$"+Name+"$"+Domain+"$dummy$"
  221.     else:
  222.         return False
  223.  
  224. def ParseMSKerbv5UDP(Data):
  225.     MsgType = Data[17:18]
  226.     EncType = Data[39:40]
  227.     if MsgType == "\x0a" and EncType == "\x17":
  228.         if Data[40:44] == "\xa2\x36\x04\x34" or Data[40:44] == "\xa2\x35\x04\x33":
  229.             HashLen = struct.unpack('<b',Data[41:42])[0]
  230.             if HashLen == 54:
  231.                 Hash = Data[44:96]
  232.                 SwitchHash = Hash[16:]+Hash[0:16]
  233.                 NameLen = struct.unpack('<b',Data[144:145])[0]
  234.                 Name = Data[145:145+NameLen]
  235.                 DomainLen = struct.unpack('<b',Data[145+NameLen+3:145+NameLen+4])[0]
  236.                 Domain = Data[145+NameLen+4:145+NameLen+4+DomainLen]
  237.                 BuildHash = "$krb5pa$23$"+Name+"$"+Domain+"$dummy$"+SwitchHash.encode('hex')
  238.                 return 'MSKerb hash found: %s\n'%(BuildHash),"$krb5pa$23$"+Name+"$"+Domain+"$dummy$"
  239.             if HashLen == 53:
  240.                 Hash = Data[44:95]
  241.                 SwitchHash = Hash[16:]+Hash[0:16]
  242.                 NameLen = struct.unpack('<b',Data[143:144])[0]
  243.                 Name = Data[144:144+NameLen]
  244.                 DomainLen = struct.unpack('<b',Data[144+NameLen+3:144+NameLen+4])[0]
  245.                 Domain = Data[144+NameLen+4:144+NameLen+4+DomainLen]
  246.                 BuildHash = "$krb5pa$23$"+Name+"$"+Domain+"$dummy$"+SwitchHash.encode('hex')
  247.                 return 'MSKerb hash found: %s\n'%(BuildHash),"$krb5pa$23$"+Name+"$"+Domain+"$dummy$"
  248.         else:
  249.             Hash = Data[49:101]
  250.             SwitchHash = Hash[16:]+Hash[0:16]
  251.             NameLen = struct.unpack('<b',Data[149:150])[0]
  252.             Name = Data[150:150+NameLen]
  253.             DomainLen = struct.unpack('<b',Data[150+NameLen+3:150+NameLen+4])[0]
  254.             Domain = Data[150+NameLen+4:150+NameLen+4+DomainLen]
  255.             BuildHash = "$krb5pa$23$"+Name+"$"+Domain+"$dummy$"+SwitchHash.encode('hex')
  256.             return 'MSKerb hash found: %s\n'%(BuildHash),"$krb5pa$23$"+Name+"$"+Domain+"$dummy$"
  257.     else:
  258.         return False
  259.  
  260. def ParseSNMP(data):
  261.     SNMPVersion = data[4:5]
  262.     if SNMPVersion == "\x00":
  263.         StrLen = struct.unpack('<b',data[6:7])[0]
  264.         return 'Found SNMPv1 Community string: %s\n'%(data[7:7+StrLen])
  265.     if data[3:5] == "\x01\x01":
  266.         StrLen = struct.unpack('<b',data[6:7])[0]
  267.         return 'Found SNMPv2 Community string: %s\n'%(data[7:7+StrLen])
  268.  
  269.  
  270. def ParseSMTP(data):
  271.     basic = data[0:len(data)-2]
  272.     OpCode  = ['HELO','EHLO','MAIL','RCPT','SIZE','DATA','QUIT','VRFY','EXPN','RSET']
  273.     if data[0:4] not in OpCode:
  274.         try:
  275.             Basestr = b64decode(basic)
  276.             if len(Basestr)>1:
  277.                 if Basestr.decode('ascii'):
  278.                     return 'SMTP decoded Base64 string: %s\n'%(Basestr)
  279.         except:
  280.             pass
  281.  
  282. def Decode_Ip_Packet(s):
  283.     d={}
  284.     d['version']=(ord(s[0]) & 0xf0) >> 4
  285.     d['header_len']=ord(s[0]) & 0x0f
  286.     d['tos']=ord(s[1])
  287.     d['total_len']=socket.ntohs(struct.unpack('H',s[2:4])[0])
  288.     d['id']=socket.ntohs(struct.unpack('H',s[4:6])[0])
  289.     d['flags']=(ord(s[6]) & 0xe0) >> 5
  290.     d['fragment_offset']=socket.ntohs(struct.unpack('H',s[6:8])[0] & 0x1f)
  291.     d['ttl']=ord(s[8])
  292.     d['protocol']=ord(s[9])
  293.     d['checksum']=socket.ntohs(struct.unpack('H',s[10:12])[0])
  294.     d['source_address']=pcap.ntoa(struct.unpack('i',s[12:16])[0])
  295.     d['destination_address']=pcap.ntoa(struct.unpack('i',s[16:20])[0])
  296.     if d['header_len']>5:
  297.         d['options']=s[20:4*(d['header_len']-5)]
  298.     else:
  299.         d['options']=None
  300.     d['data']=s[4*d['header_len']:]
  301.     return d
  302.  
  303. def Print_Packet_Details(decoded,SrcPort,DstPort):
  304.     if timestamp:
  305.         ts = '[%f] ' % time.time()
  306.     else:
  307.         ts = ''
  308.     try:
  309.         return '%sprotocol: %s %s:%s > %s:%s' % (ts, protocols[decoded['protocol']],decoded['source_address'],SrcPort,
  310.                                            decoded['destination_address'], DstPort)
  311.     except:
  312.         return '%s%s:%s > %s:%s' % (ts,decoded['source_address'],SrcPort,
  313.                                            decoded['destination_address'], DstPort)
  314.  
  315.  
  316. def ParseDataRegex(decoded, SrcPort, DstPort):
  317.     SMTPAuth = re.search('AUTH LOGIN|AUTH PLAIN', decoded['data'])
  318.     Basic64 = re.findall('(?<=Authorization: Basic )[^\n]*', decoded['data'])
  319.     FTPUser = re.findall('(?<=USER )[^\r]*', decoded['data'])
  320.     FTPPass = re.findall('(?<=PASS )[^\r]*', decoded['data'])
  321.     HTTPNTLM2 = re.findall('(?<=WWW-Authenticate: NTLM )[^\\r]*', decoded['data'])
  322.     HTTPNTLM3 = re.findall('(?<=Authorization: NTLM )[^\\r]*', decoded['data'])
  323.     NTLMSSP2 = re.findall('NTLMSSP\x00\x02\x00\x00\x00.*[^EOF]*', decoded['data'])
  324.     NTLMSSP3 = re.findall('NTLMSSP\x00\x03\x00\x00\x00.*[^EOF]*', decoded['data'],re.DOTALL)
  325.     if activate_cc:
  326.         CCMatch = re.findall('.{30}[^\d][3456][0-9]{3}[\s-]*[0-9]{4}[\s-]*[0-9]{4}[\s-]*[0-9]{4}[^\d]', decoded['data'],re.DOTALL)
  327.         CC = re.findall('[^\d][456][0-9]{3}[\s-]*[0-9]{4}[\s-]*[0-9]{4}[\s-]*[0-9]{4}[^\d]', decoded['data'])
  328.     else:
  329.         CCMatch = False
  330.         CC = False
  331.     if Basic64:
  332.         basic = ''.join(Basic64)
  333.         HeadMessage = Print_Packet_Details(decoded,SrcPort,DstPort)
  334.         try:
  335.             Message = 'Found  HTTP Basic authentication: %s\n'%(b64decode(basic))
  336.             if PrintPacket(Filename,Message):
  337.                 l.warning(HeadMessage)
  338.                 l.warning(Message)
  339.                 print HeadMessage+'\n'+Message
  340.         except:
  341.             pass
  342.  
  343.     if DstPort == 88 and protocols.has_key(decoded['protocol']) and protocols[decoded['protocol']] == 'tcp':
  344.         Message = ParseMSKerbv5TCP(decoded['data'][20:])
  345.         if Message:
  346.             HeadMessage = Print_Packet_Details(decoded,SrcPort,DstPort)
  347.             if PrintPacket(Filename,Message[1]):
  348.                 l.warning(HeadMessage)
  349.                 l.warning(Message[0])
  350.                 print HeadMessage+'\n'+Message[0]
  351.  
  352.     if DstPort == 88 and protocols.has_key(decoded['protocol']) and protocols[decoded['protocol']] == 'udp':
  353.         Message = ParseMSKerbv5UDP(decoded['data'][8:])
  354.         if Message:
  355.             HeadMessage = Print_Packet_Details(decoded,SrcPort,DstPort)
  356.             if PrintPacket(Filename,Message[1]):
  357.                 l.warning(HeadMessage)
  358.                 l.warning(Message[0])
  359.                 print HeadMessage+'\n'+Message[0]
  360.  
  361.     if DstPort == 161:
  362.         Message = ParseSNMP(decoded['data'][8:])
  363.         if Message:
  364.             HeadMessage = Print_Packet_Details(decoded,SrcPort,DstPort)
  365.             if PrintPacket(Filename,Message):
  366.                 l.warning(HeadMessage)
  367.                 l.warning(Message)
  368.                 print HeadMessage+'\n'+Message
  369.  
  370.     if DstPort == 143:
  371.         IMAPAuth = re.findall('(?<=LOGIN \")[^\r]*', decoded['data'])
  372.         if IMAPAuth:
  373.             HeadMessage = Print_Packet_Details(decoded,SrcPort,DstPort)
  374.             Message = 'Found IMAP login: "%s\n'%(''.join(IMAPAuth))
  375.             if PrintPacket(Filename,Message):
  376.                 l.warning(HeadMessage)
  377.                 l.warning(Message)
  378.                 print HeadMessage+'\n'+Message
  379.  
  380.     if DstPort == 110:
  381.         if FTPUser:
  382.             global POPUser
  383.             POPUser = ''.join(FTPUser)
  384.         if FTPPass:
  385.             try:
  386.                 POPUser
  387.                 HeadMessage = Print_Packet_Details(decoded,SrcPort,DstPort)
  388.                 Message = 'Found POP credentials %s:%s\n'%(POPUser,''.join(FTPPass))
  389.                 del POPUser
  390.                 if PrintPacket(Filename,Message):
  391.                     l.warning(HeadMessage)
  392.                     l.warning(Message)
  393.                     print HeadMessage+'\n'+Message
  394.             except NameError:
  395.                 pass
  396.  
  397.     if DstPort == 25 and SMTPAuth or DstPort == 587 and SMTPAuth:
  398.         global SMTPAuthentication
  399.         SMTPAuthentication = '1'
  400.  
  401.     if DstPort == 25 or DstPort == 587:
  402.         try:
  403.             SMTPAuthentication
  404.             Message = ParseSMTP(decoded['data'][20:])
  405.             if Message:
  406.                 HeadMessage = Print_Packet_Details(decoded,SrcPort,DstPort)
  407.                 del SMTPAuthentication
  408.                 if PrintPacket(Filename,Message):
  409.                     l.warning(HeadMessage)
  410.                     l.warning(Message)
  411.                     print HeadMessage+'\n'+Message
  412.         except NameError:
  413.             pass
  414.  
  415.     if FTPUser:
  416.         global UserID
  417.         UserID = ''.join(FTPUser)
  418.  
  419.     if FTPPass and DstPort == 21:
  420.         try:
  421.             HeadMessage = Print_Packet_Details(decoded,SrcPort,DstPort)
  422.             Message = 'FTP User: %s\n'%(UserID)
  423.             Message+= 'FTP Pass: %s\n'%(''.join(FTPPass))
  424.             del UserID
  425.             if PrintPacket(Filename,Message):
  426.                 l.warning(HeadMessage)
  427.                 l.warning(Message)
  428.                 print HeadMessage+'\n'+Message
  429.         except:
  430.             pass
  431.  
  432.     if NTLMSSP2:
  433.         global Chall
  434.         Chall = ''.join(NTLMSSP2)[24:32].encode('hex')
  435.  
  436.     if NTLMSSP3:
  437.         try:
  438.             NTLMPacket = ''.join(NTLMSSP3)
  439.             if Is_Anonymous(NTLMPacket):
  440.                 try:
  441.                     Chall
  442.                 except NameError:
  443.                     pass
  444.                 else:
  445.                     HeadMessage = Print_Packet_Details(decoded,SrcPort,DstPort)
  446.                     Message = ParseNTLMHash(NTLMPacket,Chall)
  447.                     del Chall
  448.                     if PrintPacket(Filename,Message[1]):
  449.                         l.warning(HeadMessage)
  450.                         l.warning(Message[0])
  451.                         print HeadMessage+'\n'+Message[0]
  452.         except:
  453.             pass
  454.  
  455.     if HTTPNTLM2:
  456.         try:
  457.             Packet = b64decode(''.join(HTTPNTLM2))
  458.             global HTTPChall
  459.             if re.findall('NTLMSSP\x00\x02\x00\x00\x00.*[^EOF]*', Packet,re.DOTALL):
  460.                 HTTPChall = ''.join(Packet)[24:32].encode('hex')
  461.         except:
  462.             pass
  463.  
  464.     if HTTPNTLM3:
  465.         try:
  466.             Packet = b64decode(''.join(HTTPNTLM3))
  467.             if re.findall('NTLMSSP\x00\x03\x00\x00\x00.*[^EOF]*', Packet,re.DOTALL):
  468.                 if Is_Anonymous(Packet):
  469.                     try:
  470.                         HTTPChall
  471.                     except NameError:
  472.                         pass
  473.                     else:
  474.                         HeadMessage = Print_Packet_Details(decoded,SrcPort,DstPort)
  475.                         Message = ParseNTLMHash(Packet,HTTPChall)
  476.                         del HTTPChall
  477.                         if PrintPacket(Filename,Message[1]):
  478.                             l.warning(HeadMessage)
  479.                             l.warning(Message[0])
  480.                             print HeadMessage+'\n'+Message
  481.         except:
  482.             pass
  483.  
  484.     if CC:
  485.         CreditCard = re.sub("\D", "", ''.join(CC).strip())
  486.         CMatch = ''.join(CCMatch).strip()
  487.         if len(CreditCard)<=16:
  488.             if luhn(CreditCard):
  489.                 HeadMessage = Print_Packet_Details(decoded,SrcPort,DstPort)
  490.                 MessageCC = 'Possible valid CC (Luhn check OK): %s\n'%(CreditCard)
  491.                 MessageMatch= 'Please verify this match ( %s )\n'%('\033[1m\033[31m'+CMatch+'\033[0m')
  492.                 if PrintPacket(Filename,MessageCC):
  493.                     l.warning(HeadMessage)
  494.                     l.warning(MessageCC+MessageMatch)
  495.                     print HeadMessage+'\n'+MessageCC+'\n'+MessageMatch
  496.     else:
  497.         pass
  498.  
  499. def Print_Packet_Cooked(pktlen, data, timestamp):
  500.     if not data:
  501.         return
  502.     if data[14:16]=='\x08\x00':
  503.         decoded=Decode_Ip_Packet(data[16:])
  504.         SrcPort =  struct.unpack('>H',decoded['data'][0:2])[0]
  505.         DstPort =  struct.unpack('>H',decoded['data'][2:4])[0]
  506.         ParseDataRegex(decoded, SrcPort, DstPort)
  507.  
  508. def Print_Packet_800dot11(pktlen, data, timestamp):
  509.     if not data:
  510.         return
  511.     if data[32:34]=='\x08\x00':
  512.         decoded=Decode_Ip_Packet(data[34:])
  513.         SrcPort =  struct.unpack('>H',decoded['data'][0:2])[0]
  514.         DstPort =  struct.unpack('>H',decoded['data'][2:4])[0]
  515.         ParseDataRegex(decoded, SrcPort, DstPort)
  516.  
  517. def Print_Packet_Tcpdump(pktlen, data, timestamp):
  518.     if not data:
  519.         return
  520.     if data[12:14]=='\x08\x00':
  521.         decoded= Decode_Ip_Packet(data[14:])
  522.         if len(decoded['data']) >= 2:
  523.             SrcPort= struct.unpack('>H',decoded['data'][0:2])[0]
  524.         else:
  525.             SrcPort = 0
  526.         if len(decoded['data']) > 2:
  527.             DstPort = struct.unpack('>H',decoded['data'][2:4])[0]
  528.         else:
  529.             DstPort = 0
  530.         ParseDataRegex(decoded, SrcPort, DstPort)
  531.  
  532. def decode_file(fname,res):
  533.     if interface != None:
  534.         try:
  535.             p = pcap.pcapObject()
  536.             net, mask = pcap.lookupnet(interface)
  537.             p.open_live(interface, 1600, 0, 100)
  538.             Message = "Pcredz live capture started, using:%s\nStarting timestamp (%s) corresponds to %s"%(interface, time.time(), time.strftime('%x %X'))
  539.             print Message
  540.             l.warning(Message)
  541.             while 1:
  542.                 p.dispatch(1, Print_Packet_Tcpdump)
  543.         except (KeyboardInterrupt, SystemExit):
  544.             print '\n\nCRTL-C hit...\nCleaning up...'
  545.             sys.exit()
  546.     else:
  547.         try:
  548.             p = pcap.pcapObject()
  549.             p.open_offline(fname)
  550.             l.warning('\n\nPcredz started, using:%s file'%(fname))
  551.             Version = IsCookedPcap(res)
  552.             if Version == 1:
  553.                 thread = Thread(target = p.dispatch, args = (0, Print_Packet_Cooked))
  554.                 thread.daemon=True
  555.                 thread.start()
  556.                 try:
  557.                     while thread.is_alive():
  558.                         thread.join(timeout=1)
  559.                 except (KeyboardInterrupt, SystemExit):
  560.                     print '\n\nCRTL-C hit..Cleaning up...'
  561.                     threading.Event().set()
  562.             if Version == 2:
  563.                 thread = Thread(target = p.dispatch, args = (0, Print_Packet_Cooked))
  564.                 thread.daemon=True
  565.                 thread.start()
  566.                 try:
  567.                     while thread.is_alive():
  568.                         thread.join(timeout=1)
  569.                 except (KeyboardInterrupt, SystemExit):
  570.                     print '\n\nCRTL-C hit..Cleaning up...'
  571.                     threading.Event().set()
  572.             if Version == 3:
  573.  
  574.                 thread = Thread(target = p.dispatch, args = (0, Print_Packet_Tcpdump))
  575.                 thread.daemon=True
  576.                 thread.start()
  577.                 try:
  578.                     while thread.is_alive():
  579.                         thread.join(timeout=1)
  580.                 except (KeyboardInterrupt, SystemExit):
  581.                     print '\n\nCRTL-C hit..Cleaning up...'
  582.                     threading.Event().set()
  583.  
  584.         except Exception:
  585.             print 'Can\'t parse %s'%(fname)
  586.  
  587. def Run():
  588.     try:
  589.         if dir_path != None:
  590.             for root, dirs, files in os.walk(dir_path, topdown=False):
  591.                 for capfile in files:
  592.                     FilePath = os.path.join(root, capfile)
  593.                     Start_Time = time.time()
  594.                     print '\nParsing: %s'%(FilePath)
  595.                     p = subprocess.Popen(["file", FilePath], stdout=subprocess.PIPE)
  596.                     res, err = p.communicate()
  597.                     decode_file(FilePath,res)
  598.                     Seconds = time.time() - Start_Time
  599.                     FileSize = 'File size %.3g Mo'%(os.stat(FilePath).st_size/(1024*1024.0))
  600.                     if Seconds>60:
  601.                         minutes = Seconds/60
  602.                         Message = '\n%s parsed in: %.3g minutes (%s).\n'%(FilePath, minutes, FileSize)
  603.                         print Message
  604.                         l.warning(Message)
  605.                     if Seconds<60:
  606.                         Message = '\n%s parsed in: %.3g seconds (%s).\n'%(FilePath, Seconds, FileSize)
  607.                         print Message
  608.                         l.warning(Message)
  609.  
  610.         if fname != None:
  611.             p = subprocess.Popen(["file", fname], stdout=subprocess.PIPE)
  612.             res, err = p.communicate()
  613.             decode_file(fname,res)
  614.             Seconds = time.time() - start_time
  615.             FileSize = 'File size %.3g Mo'%(os.stat(fname).st_size/(1024*1024.0))
  616.             if Seconds>60:
  617.                 minutes = Seconds/60
  618.                 Message = '\n%s parsed in: %.3g minutes (%s).\n'%(fname, minutes, FileSize)
  619.                 print Message
  620.                 l.warning(Message)
  621.             if Seconds<60:
  622.                 Message = '\n%s parsed in: %.3g seconds (%s).\n'%(fname, Seconds, FileSize)
  623.                 print Message
  624.                 l.warning(Message)
  625.  
  626.         if interface != None:
  627.             decode_file(fname,'')
  628.  
  629.     except:
  630.         raise
  631.  
  632. Run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement