Skip to content

Commit

Permalink
Code cleanup homework
Browse files Browse the repository at this point in the history
- Optimizing imports
- Removing unused variables
- Still a lot to do.
- Test cases passing OK
  • Loading branch information
asolino committed Dec 4, 2018
1 parent f154b9c commit ec77ea3
Show file tree
Hide file tree
Showing 86 changed files with 366 additions and 474 deletions.
8 changes: 4 additions & 4 deletions examples/GetADUsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,10 +167,10 @@ def run(self):
try:
logging.debug('Search Filter=%s' % searchFilter)
sc = ldap.SimplePagedResultsControl(size=100)
resp = ldapConnection.search(searchFilter=searchFilter,
attributes=['sAMAccountName', 'pwdLastSet', 'mail', 'lastLogon'],
sizeLimit=0, searchControls = [sc], perRecordCallback=self.processRecord)
except ldap.LDAPSearchError as e:
ldapConnection.search(searchFilter=searchFilter,
attributes=['sAMAccountName', 'pwdLastSet', 'mail', 'lastLogon'],
sizeLimit=0, searchControls = [sc], perRecordCallback=self.processRecord)
except ldap.LDAPSearchError:
raise

ldapConnection.close()
Expand Down
4 changes: 2 additions & 2 deletions examples/dpapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@
from impacket.examples import logger
from impacket.examples.secretsdump import LocalOperations, LSASecrets
from impacket.structure import hexdump
from impacket.dpapi import DPAPI_SYSTEM, MasterKeyFile, MasterKey, CredHist, DomainKey, CredentialFile, DPAPI_BLOB, \
CREDENTIAL_BLOB, VAULT_VCRD, VAULT_VPOL, VAULT_KNOWN_SCHEMAS, VAULT_VPOL_KEYS
from impacket.dpapi import MasterKeyFile, MasterKey, CredHist, DomainKey, CredentialFile, DPAPI_BLOB, CREDENTIAL_BLOB, \
VAULT_VCRD, VAULT_VPOL, VAULT_KNOWN_SCHEMAS, VAULT_VPOL_KEYS

class DPAPI:
def __init__(self, options):
Expand Down
2 changes: 1 addition & 1 deletion examples/getTGT.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import argparse
import logging
import sys
from binascii import hexlify, unhexlify
from binascii import unhexlify

from impacket import version
from impacket.examples import logger
Expand Down
12 changes: 6 additions & 6 deletions examples/goldenPac.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def run(self, addr):
self.__command = os.path.basename(self.__copyFile) + ' ' + self.__command

tid = s.connectTree('IPC$')
fid_main = self.openPipe(s,tid,'\RemCom_communicaton',0x12019f)
fid_main = self.openPipe(s,tid,r'\RemCom_communicaton',0x12019f)

packet = RemComMessage()
pid = os.getpid()
Expand All @@ -159,16 +159,16 @@ def run(self, addr):

# Create the pipes threads
stdin_pipe = RemoteStdInPipe(rpctransport,
'\%s%s%d' % (RemComSTDIN, packet['Machine'], packet['ProcessID']),
r'\%s%s%d' % (RemComSTDIN, packet['Machine'], packet['ProcessID']),
smb.FILE_WRITE_DATA | smb.FILE_APPEND_DATA, self.__TGS,
installService.getShare())
stdin_pipe.start()
stdout_pipe = RemoteStdOutPipe(rpctransport,
'\%s%s%d' % (RemComSTDOUT, packet['Machine'], packet['ProcessID']),
r'\%s%s%d' % (RemComSTDOUT, packet['Machine'], packet['ProcessID']),
smb.FILE_READ_DATA)
stdout_pipe.start()
stderr_pipe = RemoteStdErrPipe(rpctransport,
'\%s%s%d' % (RemComSTDERR, packet['Machine'], packet['ProcessID']),
r'\%s%s%d' % (RemComSTDERR, packet['Machine'], packet['ProcessID']),
smb.FILE_READ_DATA)
stderr_pipe.start()

Expand Down Expand Up @@ -337,7 +337,7 @@ def do_get(self, src_path):
import ntpath
filename = ntpath.basename(src_path)
fh = open(filename,'wb')
logging.info("Downloading %s\%s" % (self.share, src_path))
logging.info("Downloading %s\\%s" % (self.share, src_path))
self.transferClient.getFile(self.share, src_path, fh.write)
fh.close()
except Exception as e:
Expand All @@ -362,7 +362,7 @@ def do_put(self, s):
fh = open(src_path, 'rb')
f = dst_path + '/' + src_file
pathname = f.replace('/','\\')
logging.info("Uploading %s to %s\%s" % (src_file, self.share, dst_path))
logging.info("Uploading %s to %s\\%s" % (src_file, self.share, dst_path))
if PY3:
self.transferClient.putFile(self.share, pathname, fh.read)
else:
Expand Down
9 changes: 1 addition & 8 deletions examples/mqtt_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#

from __future__ import print_function

import argparse
import logging
import re
Expand All @@ -26,14 +27,6 @@
from impacket.examples import logger
from impacket.mqtt import CONNECT_ACK_ERROR_MSGS, MQTTConnection

try:
import OpenSSL
from OpenSSL import SSL, crypto
except:
logging.critical("pyOpenSSL is not installed, can't continue")
raise


class MQTT_LOGIN:
def __init__(self, username, password, target, options):
self._options = options
Expand Down
40 changes: 16 additions & 24 deletions examples/nmapAnswerMachine.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#!/usr/bin/env python
import random

import uncrc32

try: import pcap as pcapy
except: import pcapy
try:
import pcap as pcapy
except ImportError:
import pcapy

from impacket import ImpactPacket
from impacket import ImpactDecoder
Expand Down Expand Up @@ -79,7 +79,7 @@ def initTemplate(self):
probe = self.templateClass(0, ['0.0.0.0',self.getIP()])
self.template_onion = [probe.get_packet()]
try:
while 1: self.template_onion.append(self.template_onion[-1].child())
while 1: self.template_onion.append (self.template_onion[-1].child ())
except: pass

# print("Template: %s" % self.template_onion[O_ETH])
Expand Down Expand Up @@ -210,21 +210,19 @@ def isMine(self, in_onion):
if not IPResponder.isMine(self, in_onion): return False
if len(in_onion) < 3: return False

return (
(in_onion[O_ICMP].protocol == ImpactPacket.ICMP.protocol) and
self.sameICMPTemplate(in_onion))
return (in_onion[O_ICMP].protocol == ImpactPacket.ICMP.protocol) and self.sameICMPTemplate(in_onion)

def sameICMPTemplate(self, in_onion):
t_ip = self.template_onion[O_IP]
t_icmp = self.template_onion[O_ICMP]
t_icmp_datalen = self.template_onion[O_ICMP_DATA].get_size()

return (
(t_ip.get_ip_tos() == in_onion[O_IP].get_ip_tos()) and
(t_ip.get_ip_df() == in_onion[O_IP].get_ip_df()) and
(t_icmp.get_icmp_type() == in_onion[O_ICMP].get_icmp_type()) and
(t_icmp.get_icmp_code() == in_onion[O_ICMP].get_icmp_code()) and
(t_icmp_datalen == in_onion[O_ICMP_DATA].get_size())
(t_ip.get_ip_tos () == in_onion[O_IP].get_ip_tos ()) and (
t_ip.get_ip_df () == in_onion[O_IP].get_ip_df ()) and (
t_icmp.get_icmp_type () == in_onion[O_ICMP].get_icmp_type ()) and (
t_icmp.get_icmp_code () == in_onion[O_ICMP].get_icmp_code ()) and (
t_icmp_datalen == in_onion[O_ICMP_DATA].get_size ())
)

class UDPResponder(IPResponder):
Expand Down Expand Up @@ -305,18 +303,13 @@ def isMine(self, in_onion):
if not IPResponder.isMine(self, in_onion): return False
if len(in_onion) < 3: return False

return (
in_onion[O_TCP].protocol == ImpactPacket.TCP.protocol and
self.sameTCPFlags(in_onion) and
self.sameTCPOptions(in_onion)
)
return (in_onion[O_TCP].protocol == ImpactPacket.TCP.protocol and self.sameTCPFlags (in_onion) and self.sameTCPOptions (
in_onion))

class OpenTCPResponder(TCPResponder):
def isMine(self, in_onion):
return (
TCPResponder.isMine(self, in_onion) and
in_onion[O_TCP].get_SYN() and
self.machine.isTCPPortOpen(in_onion[O_TCP].get_th_dport()))
return (TCPResponder.isMine (self, in_onion) and in_onion[O_TCP].get_SYN () and self.machine.isTCPPortOpen (
in_onion[O_TCP].get_th_dport ()))

def buildAnswer(self, in_onion):
out_onion = TCPResponder.buildAnswer(self, in_onion)
Expand Down Expand Up @@ -357,8 +350,7 @@ def set_port(self, port):
return self

def isMine(self, in_onion):
return (
OpenUDPResponder.isMine(self, in_onion))# and
return ( OpenUDPResponder.isMine(self, in_onion))# and
#in_onion[O_UDP].get_uh_dport() == self.port)

def buildAnswer(self, in_onion):
Expand Down
2 changes: 1 addition & 1 deletion examples/ntfs-read.py
Original file line number Diff line number Diff line change
Expand Up @@ -1199,7 +1199,7 @@ def main():
logger.init()
parser = argparse.ArgumentParser(add_help = True, description = "NTFS explorer (read-only)")
parser.add_argument('volume', action='store', help='NTFS volume to open (e.g. \\\\.\\C: or /dev/disk1s1)')
parser.add_argument('-extract', action='store', help='extracts pathname (e.g. \windows\system32\config\sam)')
parser.add_argument('-extract', action='store', help='extracts pathname (e.g. \\windows\\system32\\config\\sam)')
parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')

if len(sys.argv)==1:
Expand Down
2 changes: 1 addition & 1 deletion examples/ping6.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
import time
import sys

from impacket import ImpactDecoder, ImpactPacket, IP6, ICMP6, version
from impacket import ImpactDecoder, IP6, ICMP6, version

print(version.BANNER)

Expand Down
12 changes: 6 additions & 6 deletions examples/psexec.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def doStuff(self, rpctransport):
self.__command = os.path.basename(self.__copyFile) + ' ' + self.__command

tid = s.connectTree('IPC$')
fid_main = self.openPipe(s,tid,'\RemCom_communicaton',0x12019f)
fid_main = self.openPipe(s,tid,r'\RemCom_communicaton',0x12019f)

packet = RemComMessage()
pid = os.getpid()
Expand All @@ -173,15 +173,15 @@ def doStuff(self, rpctransport):

# Create the pipes threads
stdin_pipe = RemoteStdInPipe(rpctransport,
'\%s%s%d' % (RemComSTDIN, packet['Machine'], packet['ProcessID']),
r'\%s%s%d' % (RemComSTDIN, packet['Machine'], packet['ProcessID']),
smb.FILE_WRITE_DATA | smb.FILE_APPEND_DATA, installService.getShare())
stdin_pipe.start()
stdout_pipe = RemoteStdOutPipe(rpctransport,
'\%s%s%d' % (RemComSTDOUT, packet['Machine'], packet['ProcessID']),
r'\%s%s%d' % (RemComSTDOUT, packet['Machine'], packet['ProcessID']),
smb.FILE_READ_DATA)
stdout_pipe.start()
stderr_pipe = RemoteStdErrPipe(rpctransport,
'\%s%s%d' % (RemComSTDERR, packet['Machine'], packet['ProcessID']),
r'\%s%s%d' % (RemComSTDERR, packet['Machine'], packet['ProcessID']),
smb.FILE_READ_DATA)
stderr_pipe.start()

Expand Down Expand Up @@ -344,7 +344,7 @@ def do_get(self, src_path):
import ntpath
filename = ntpath.basename(src_path)
fh = open(filename,'wb')
logging.info("Downloading %s\%s" % (self.share, src_path))
logging.info("Downloading %s\\%s" % (self.share, src_path))
self.transferClient.getFile(self.share, src_path, fh.write)
fh.close()
except Exception as e:
Expand All @@ -369,7 +369,7 @@ def do_put(self, s):
fh = open(src_path, 'rb')
f = dst_path + '/' + src_file
pathname = f.replace('/','\\')
logging.info("Uploading %s to %s\%s" % (src_file, self.share, dst_path))
logging.info("Uploading %s to %s\\%s" % (src_file, self.share, dst_path))
if PY3:
self.transferClient.putFile(self.share, pathname, fh.read)
else:
Expand Down
12 changes: 6 additions & 6 deletions examples/raiseChild.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ def run(self, addr):
self.__command = os.path.basename(self.__copyFile) + ' ' + self.__command

tid = s.connectTree('IPC$')
fid_main = self.openPipe(s,tid,'\RemCom_communicaton',0x12019f)
fid_main = self.openPipe(s,tid,r'\RemCom_communicaton',0x12019f)

packet = RemComMessage()
pid = os.getpid()
Expand All @@ -196,16 +196,16 @@ def run(self, addr):

# Create the pipes threads
stdin_pipe = RemoteStdInPipe(rpctransport,
'\%s%s%d' % (RemComSTDIN, packet['Machine'], packet['ProcessID']),
r'\%s%s%d' % (RemComSTDIN, packet['Machine'], packet['ProcessID']),
smb.FILE_WRITE_DATA | smb.FILE_APPEND_DATA, self.__TGS,
installService.getShare())
stdin_pipe.start()
stdout_pipe = RemoteStdOutPipe(rpctransport,
'\%s%s%d' % (RemComSTDOUT, packet['Machine'], packet['ProcessID']),
r'\%s%s%d' % (RemComSTDOUT, packet['Machine'], packet['ProcessID']),
smb.FILE_READ_DATA)
stdout_pipe.start()
stderr_pipe = RemoteStdErrPipe(rpctransport,
'\%s%s%d' % (RemComSTDERR, packet['Machine'], packet['ProcessID']),
r'\%s%s%d' % (RemComSTDERR, packet['Machine'], packet['ProcessID']),
smb.FILE_READ_DATA)
stderr_pipe.start()

Expand Down Expand Up @@ -372,7 +372,7 @@ def do_get(self, src_path):
import ntpath
filename = ntpath.basename(src_path)
fh = open(filename,'wb')
logging.info("Downloading %s\%s" % (self.share, src_path))
logging.info("Downloading %s\\%s" % (self.share, src_path))
self.transferClient.getFile(self.share, src_path, fh.write)
fh.close()
except Exception as e:
Expand All @@ -397,7 +397,7 @@ def do_put(self, s):
fh = open(src_path, 'rb')
f = dst_path + '/' + src_file
pathname = f.replace('/','\\')
logging.info("Uploading %s to %s\%s" % (src_file, self.share, dst_path))
logging.info("Uploading %s to %s\\%s" % (src_file, self.share, dst_path))
if PY3:
self.transferClient.putFile(self.share, pathname, fh.read)
else:
Expand Down
1 change: 0 additions & 1 deletion examples/registry-read.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import argparse
import ntpath
from binascii import unhexlify, hexlify
from six import b

from impacket.examples import logger
from impacket import version
Expand Down
2 changes: 1 addition & 1 deletion examples/samrdump.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def dump(self, remoteName, remoteHost):

logging.info('Retrieving endpoint list from %s' % remoteName)

stringbinding = 'ncacn_np:%s[\pipe\samr]' % remoteName
stringbinding = r'ncacn_np:%s[\pipe\samr]' % remoteName
logging.debug('StringBinding %s'%stringbinding)
rpctransport = transport.DCERPCTransportFactory(stringbinding)
rpctransport.set_dport(self.__port)
Expand Down
4 changes: 2 additions & 2 deletions examples/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from impacket import version
from impacket.dcerpc.v5 import transport, scmr
from impacket.dcerpc.v5.ndr import NULL
from impacket.crypto import *
from impacket.crypto import encryptSecret


class SVCCTL:
Expand All @@ -48,7 +48,7 @@ def __init__(self, username, password, domain, options, port=445):

def run(self, remoteName, remoteHost):

stringbinding = 'ncacn_np:%s[\pipe\svcctl]' % remoteName
stringbinding = r'ncacn_np:%s[\pipe\svcctl]' % remoteName
logging.debug('StringBinding %s'%stringbinding)
rpctransport = transport.DCERPCTransportFactory(stringbinding)
rpctransport.set_dport(self.__port)
Expand Down
8 changes: 4 additions & 4 deletions examples/smbexec.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@

from impacket.examples import logger
from impacket import version, smbserver
from impacket.smbconnection import *
from impacket.smbconnection import SMB_DIALECT
from impacket.dcerpc.v5 import transport, scmr

OUTPUT_FILENAME = '__output'
Expand All @@ -59,7 +59,7 @@ def cleanup_server(self):
logging.info('Cleaning up..')
try:
os.unlink(SMBSERVER_DIR + '/smb.log')
except:
except OSError:
pass
os.rmdir(SMBSERVER_DIR)

Expand Down Expand Up @@ -129,7 +129,7 @@ def __init__(self, username='', password='', domain='', hashes=None, aesKey=None
self.__lmhash, self.__nthash = hashes.split(':')

def run(self, remoteName, remoteHost):
stringbinding = 'ncacn_np:%s[\pipe\svcctl]' % remoteName
stringbinding = r'ncacn_np:%s[\pipe\svcctl]' % remoteName
logging.debug('StringBinding %s'%stringbinding)
rpctransport = transport.DCERPCTransportFactory(stringbinding)
rpctransport.set_dport(self.__port)
Expand Down Expand Up @@ -210,7 +210,7 @@ def finish(self):
scmr.hRDeleteService(self.__scmr, service)
scmr.hRControlService(self.__scmr, service, scmr.SERVICE_CONTROL_STOP)
scmr.hRCloseServiceHandle(self.__scmr, service)
except:
except scmr.DCERPCException:
pass

def do_shell(self, s):
Expand Down
Loading

0 comments on commit ec77ea3

Please sign in to comment.