Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion examples/atexec.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
RPC_C_AUTHN_LEVEL_PKT_PRIVACY
from impacket.examples.utils import parse_target
from impacket.krb5.keytab import Keytab
from six import PY2

CODEC = sys.stdout.encoding
AUTHOR_OVERFLOW_LEN = 4000
Expand Down
16 changes: 3 additions & 13 deletions examples/dcomexec.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@
import time
from base64 import b64encode

from six import PY2, PY3
from impacket import version
from impacket.dcerpc.v5.dcom.oaut import IID_IDispatch, string_to_bin, IDispatch, DISPPARAMS, DISPATCH_PROPERTYGET, \
VARIANT, VARENUM, DISPATCH_METHOD
Expand Down Expand Up @@ -310,10 +309,7 @@ def do_cd(self, s):
print(self.__outputBuffer)
self.__outputBuffer = ''
else:
if PY2:
self._pwd = ntpath.normpath(ntpath.join(self._pwd, s.decode(sys.stdin.encoding)))
else:
self._pwd = ntpath.normpath(ntpath.join(self._pwd, s))
self._pwd = ntpath.normpath(ntpath.join(self._pwd, s))
self.execute_remote('cd ')
self._pwd = self.__outputBuffer.strip('\r\n')
self.prompt = (self._pwd + '>')
Expand Down Expand Up @@ -402,10 +398,7 @@ def execute_remote(self, data, shell_type='cmd'):
arg1['clSize'] = 5
arg1['vt'] = VARENUM.VT_BSTR
arg1['_varUnion']['tag'] = VARENUM.VT_BSTR
if PY3:
arg1['_varUnion']['bstrVal']['asData'] = command
else:
arg1['_varUnion']['bstrVal']['asData'] = command.decode(sys.stdin.encoding)
arg1['_varUnion']['bstrVal']['asData'] = command

arg2 = VARIANT(None, False)
arg2['clSize'] = 5
Expand Down Expand Up @@ -475,10 +468,7 @@ def execute_remote(self, data, shell_type='cmd'):
arg2['clSize'] = 5
arg2['vt'] = VARENUM.VT_BSTR
arg2['_varUnion']['tag'] = VARENUM.VT_BSTR
if PY3:
arg2['_varUnion']['bstrVal']['asData'] = command
else:
arg2['_varUnion']['bstrVal']['asData'] = command.decode(sys.stdin.encoding)
arg2['_varUnion']['bstrVal']['asData'] = command

arg3 = VARIANT(None, False)
arg3['clSize'] = 5
Expand Down
19 changes: 3 additions & 16 deletions examples/exchanger.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,21 +111,16 @@ def set_output_file(self, filename):

def print(self, text):
if self.__outputFd != None:
if PY3:
self.__outputFd.write(text + '\n')
else:
self.__outputFd.write((text + '\n').encode('utf-8'))
self.__outputFd.write(text + '\n')
print(text)

def _encode_binary(self, bytestr):
if PY3 and self._output_type == "hex":
return "0x%s" % str(binascii.hexlify(bytestr), 'ascii')
elif self._output_type == "hex":
return "0x%s" % binascii.hexlify(bytestr)
elif PY3:
return str(base64.b64encode(bytestr), 'ascii')
else:
return base64.b64encode(bytestr)
return str(base64.b64encode(bytestr), 'ascii')

def __del__(self):
if self.__outputFd != None:
Expand Down Expand Up @@ -890,10 +885,6 @@ def _split_lines(self, text, width):
else:
return argparse.HelpFormatter._split_lines(self, text, width)

def localized_arg(bytestring):
unicode_string = bytestring.decode(sys.getfilesystemencoding())
return unicode_string

parser = argparse.ArgumentParser(add_help=True, description="A tool to abuse Exchange services")
parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')
parser.add_argument('-debug', action='store_true', help='Turn DEBUG and EXTENDED output ON')
Expand Down Expand Up @@ -934,11 +925,7 @@ def localized_arg(bytestring):
dump_tables.add_argument('-rows-per-request', action='store', type=int, metavar="50", default=50,
help='Limit the number of rows per request')

if PY3:
dump_tables.add_argument('-name', action='store', help='Dump table with the specified name (inc. GAL)')
else:
dump_tables.add_argument('-name', action='store', help='Dump table with the specified name (inc. GAL)',
type=localized_arg)
dump_tables.add_argument('-name', action='store', help='Dump table with the specified name (inc. GAL)')

dump_tables.add_argument('-guid', action='store', help='Dump table with the specified GUID')
dump_tables.add_argument('-output-type', choices=['hex', 'base64'], nargs='?', default='hex',
Expand Down
11 changes: 2 additions & 9 deletions examples/goldenPac.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
import time
from binascii import unhexlify
from threading import Thread, Lock
from six import PY3

from impacket.dcerpc.v5 import epm
from impacket.dcerpc.v5.drsuapi import MSRPC_UUID_DRSUAPI, hDRSDomainControllerInfo, DRSBind, NTDSAPI_CLIENT_GUID, \
Expand Down Expand Up @@ -363,10 +362,7 @@ def do_put(self, s):
f = dst_path + '/' + src_file
pathname = f.replace('/','\\')
logging.info("Uploading %s to %s\\%s" % (src_file, self.share, dst_path))
if PY3:
self.transferClient.putFile(self.share, pathname, fh.read)
else:
self.transferClient.putFile(self.share, pathname.decode(sys.stdin.encoding), fh.read)
self.transferClient.putFile(self.share, pathname, fh.read)
fh.close()
except Exception as e:
logging.error(str(e))
Expand All @@ -390,10 +386,7 @@ def emptyline(self):
return

def default(self, line):
if PY3:
self.send_data(line.encode('cp437')+b'\r\n')
else:
self.send_data(line.decode(sys.stdin.encoding).encode('cp437')+'\r\n')
self.send_data(line.encode('cp437')+b'\r\n')

def send_data(self, data, hideOutput = True):
if hideOutput is True:
Expand Down
7 changes: 2 additions & 5 deletions examples/ntfs-read.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
import argparse
import cmd
import ntpath
from six import PY2, text_type
from six import text_type
from datetime import datetime
from impacket.examples import logger
from impacket import version
Expand Down Expand Up @@ -990,10 +990,7 @@ def PerformFixUp(self, record, buf, numSectors):
dataList[index+1] = sequenceArray[i+1]
index += 2

if PY2:
return "".join(dataList)
else:
return bytes(dataList)
return bytes(dataList)

def parseIndexBlocks(self, vcn):
IndexEntries = []
Expand Down
10 changes: 2 additions & 8 deletions examples/psexec.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,10 +541,7 @@ def do_lput(self, s):
f = dst_path + '/' + src_file
pathname = f.replace('/','\\')
logging.info("Uploading %s to %s\\%s" % (src_file, self.share, dst_path))
if PY3:
self.transferClient.putFile(self.share, pathname, fh.read)
else:
self.transferClient.putFile(self.share, pathname.decode(sys.stdin.encoding), fh.read)
self.transferClient.putFile(self.share, pathname, fh.read)
fh.close()
except Exception as e:
logging.error(str(e))
Expand All @@ -564,10 +561,7 @@ def emptyline(self):
return

def default(self, line):
if PY3:
self.send_data(line.encode(CODEC)+b'\r\n')
else:
self.send_data(line.decode(sys.stdin.encoding).encode(CODEC)+'\r\n')
self.send_data(line.encode(CODEC)+b'\r\n')

def send_data(self, data, hideOutput = True):
if hideOutput is True:
Expand Down
11 changes: 2 additions & 9 deletions examples/raiseChild.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@
from binascii import unhexlify, hexlify
from socket import gethostbyname
from struct import unpack
from six import PY3

try:
import pyasn1
Expand Down Expand Up @@ -408,10 +407,7 @@ def do_put(self, s):
f = dst_path + '/' + src_file
pathname = f.replace('/','\\')
logging.info("Uploading %s to %s\\%s" % (src_file, self.share, dst_path))
if PY3:
self.transferClient.putFile(self.share, pathname, fh.read)
else:
self.transferClient.putFile(self.share, pathname.decode(sys.stdin.encoding), fh.read)
self.transferClient.putFile(self.share, pathname, fh.read)
fh.close()
except Exception as e:
logging.error(str(e))
Expand All @@ -435,10 +431,7 @@ def emptyline(self):
return

def default(self, line):
if PY3:
self.send_data(line.encode('cp437')+b'\r\n')
else:
self.send_data(line.decode(sys.stdin.encoding).encode('cp437')+'\r\n')
self.send_data(line.encode('cp437')+b'\r\n')

def send_data(self, data, hideOutput = True):
if hideOutput is True:
Expand Down
6 changes: 3 additions & 3 deletions impacket/dcerpc/v5/ndr.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import random
import inspect
from struct import pack, unpack_from, calcsize
from six import with_metaclass, PY3
from six import with_metaclass
from binascii import hexlify

from impacket import LOG
Expand Down Expand Up @@ -759,7 +759,7 @@ def pack(self, fieldName, fieldTypeOrClass, soFar = 0):
if pad > 0:
answer += b'\xdd' * pad
if dataClass is None:
if item == 'c' and PY3 and isinstance(each, int):
if item == 'c' and isinstance(each, int):
# Special case when dealing with PY3, here we have an integer we need to convert
each = bytes([each])
answer += pack(item, each)
Expand Down Expand Up @@ -966,7 +966,7 @@ def getData(self, soFar = 0):
# If the string element size is one octet, the terminator is a NULL character.
# The terminator for a string of multi-byte characters is the array element zero (0).
if self["Data"][-1:] != b'\x00':
if PY3 and isinstance(self["Data"],list) is False:
if isinstance(self["Data"],list) is False:
self["Data"] = self["Data"] + b'\x00'
else:
self["Data"] = b''.join(self["Data"]) + b'\x00'
Expand Down
15 changes: 3 additions & 12 deletions impacket/dpapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
from Cryptodome.Util.Padding import unpad
from Cryptodome.PublicKey import RSA
from Cryptodome.Util.number import bytes_to_long
from six import PY3

from impacket.ese import getUnixTime
from impacket.structure import Structure, hexdump
Expand Down Expand Up @@ -289,10 +288,7 @@ def deriveKey(self, passphrase, salt, keylen, count, hashFunction):
derived = bytearray(hashFunction(passphrase, U))
for r in range(count - 1):
actual = bytearray(hashFunction(passphrase, derived))
if PY3:
derived = (int.from_bytes(derived, sys.byteorder) ^ int.from_bytes(actual, sys.byteorder)).to_bytes(len(actual), sys.byteorder)
else:
derived = bytearray([ chr((a) ^ (b)) for (a,b) in zip(derived, actual) ])
derived = (int.from_bytes(derived, sys.byteorder) ^ int.from_bytes(actual, sys.byteorder)).to_bytes(len(actual), sys.byteorder)
keyMaterial += derived

return keyMaterial[:keylen]
Expand Down Expand Up @@ -372,10 +368,7 @@ def deriveKey(self, passphrase, salt, keylen, count, hashFunction):
derived = bytearray(hashFunction(passphrase, U))
for r in range(count - 1):
actual = bytearray(hashFunction(passphrase, derived))
if PY3:
derived = (int.from_bytes(derived, sys.byteorder) ^ int.from_bytes(actual, sys.byteorder)).to_bytes(len(actual), sys.byteorder)
else:
derived = bytearray([ chr((a) ^ (b)) for (a,b) in zip(derived, actual) ])
derived = (int.from_bytes(derived, sys.byteorder) ^ int.from_bytes(actual, sys.byteorder)).to_bytes(len(actual), sys.byteorder)
keyMaterial += derived

return keyMaterial[:keylen]
Expand Down Expand Up @@ -1192,9 +1185,7 @@ def privatekeyblob_to_pkcs1(key):
exp2 = bytes_to_long(key['exponent2'][::-1])
coefficient = bytes_to_long(key['coefficient'][::-1])
privateExp = bytes_to_long(key['privateExponent'][::-1]) # d
if PY3:
long = int
pubExp = long(key['rsapubkey']['pubexp']) # e
pubExp = int(key['rsapubkey']['pubexp']) # e
# RSA.Integer(prime2).inverse(prime1) # u

r = RSA.construct((modulus, pubExp, privateExp, prime1, prime2))
Expand Down
7 changes: 2 additions & 5 deletions impacket/krb5/crypto.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
from Cryptodome.Hash import HMAC, MD4, MD5, SHA
from Cryptodome.Protocol.KDF import PBKDF2
from Cryptodome.Util.number import GCD as gcd
from six import b, PY3, indexbytes, binary_type
from six import b, indexbytes, binary_type
from impacket.krb5 import constants
import logging

Expand Down Expand Up @@ -321,10 +321,7 @@ def XOR(l1,l2):
temp56 = list()
#removeMSBits
for byte in block:
if PY3:
temp56.append(byte&0b01111111)
else:
temp56.append(ord(byte)&0b01111111)
temp56.append(byte&0b01111111)

#reverse
if odd is False:
Expand Down
7 changes: 2 additions & 5 deletions impacket/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from struct import pack, unpack, calcsize

import six
from six import b, PY3
from six import b
from binascii import hexlify


Expand Down Expand Up @@ -373,10 +373,7 @@ def unpack(self, format, data, dataClassOrCode = b, field = None):
if format == 'z':
if data[-1:] != self.b('\x00'):
raise Exception("%s 'z' field is not NUL terminated: %r" % (field, data))
if PY3:
return data[:-1].decode('latin-1')
else:
return data[:-1]
return data[:-1].decode('latin-1')

# unicode specifier
if format == 'u':
Expand Down
6 changes: 1 addition & 5 deletions tests/ImpactPacket/test_IP6_Extension_Headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,13 @@
# for more information.
#
import unittest
from six import PY2

from impacket import IP6, ImpactDecoder, IP6_Extension_Headers


class TestIP6(unittest.TestCase):
def string_to_list(self, bytes):
if PY2:
return list(map(ord, list(bytes)))
else:
return list(bytes)
return list(bytes)

def test_create_simple_hop_by_hop(self):
hop_by_hop_binary_packet = [0x3a, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00]
Expand Down
4 changes: 1 addition & 3 deletions tests/SMB_RPC/test_smbserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@
from os import mkdir, rmdir, remove, urandom
from multiprocessing import Process

from six import PY2, StringIO, BytesIO, b, assertRaisesRegex, assertCountEqual
from six import StringIO, BytesIO, b, assertRaisesRegex, assertCountEqual

from impacket import smb
from impacket.smb import SMB_DIALECT
Expand Down Expand Up @@ -417,7 +417,6 @@ def test_smbserver_connect_disconnect_tree(self):

client.close()

@unittest.skipIf(PY2, "Unicode filename expected failing in Python 2.x")
def test_smbserver_list_path(self):
"""Test listing files in a shared folder.
"""
Expand Down Expand Up @@ -534,7 +533,6 @@ def test_smbserver_get_file(self):

client.close()

@unittest.skipIf(PY2, "Unicode filename expected failing in Python 2.x")
def test_smbserver_get_unicode_file(self):
"""Test reading unicode files from a shared folder.
"""
Expand Down
Loading
Loading