diff --git a/Modules/IPy.py b/Modules/IPy.py index 415c8c7..3681364 100644 --- a/Modules/IPy.py +++ b/Modules/IPy.py @@ -184,11 +184,11 @@ def __init__(self, data, ipversion=0, make_net=0): ipversion = 6 if ipversion == 4: if self.ip > MAX_IPV4_ADDRESS: - raise ValueError("IPv4 Address can't be larger than %x: %x" % (MAX_IPV4_ADDRESS, self.ip)) + raise ValueError("IPv4 Address can't be larger than {0:x}: {1:x}".format(MAX_IPV4_ADDRESS, self.ip)) prefixlen = 32 elif ipversion == 6: if self.ip > MAX_IPV6_ADDRESS: - raise ValueError("IPv6 Address can't be larger than %x: %x" % (MAX_IPV6_ADDRESS, self.ip)) + raise ValueError("IPv6 Address can't be larger than {0:x}: {1:x}".format(MAX_IPV6_ADDRESS, self.ip)) prefixlen = 128 else: raise ValueError("only IPv4 and IPv6 supported") @@ -219,8 +219,8 @@ def __init__(self, data, ipversion=0, make_net=0): # make sure the broadcast is the same as the last ip # otherwise it will return /16 for something like: # 192.168.0.0-192.168.191.255 - if IP('%s/%s' % (ip, 32-netbits)).broadcast().int() != last: - raise ValueError("the range %s is not on a network boundary." % data) + if IP('{0!s}/{1!s}'.format(ip, 32-netbits)).broadcast().int() != last: + raise ValueError("the range {0!s} is not on a network boundary.".format(data)) elif len(x) == 1: x = data.split('/') # if no prefix is given use defaults @@ -257,9 +257,9 @@ def __init__(self, data, ipversion=0, make_net=0): if not _checkNetaddrWorksWithPrefixlen(self.ip, self._prefixlen, self._ipversion): - raise ValueError("%s has invalid prefix length (%s)" % (repr(self), self._prefixlen)) + raise ValueError("{0!s} has invalid prefix length ({1!s})".format(repr(self), self._prefixlen)) else: - raise TypeError("Unsupported data type: %s" % type(data)) + raise TypeError("Unsupported data type: {0!s}".format(type(data))) def int(self): """Return the first / base / network addess as an (long) integer. @@ -328,12 +328,12 @@ def _printPrefix(self, want): netmask = self.netmask() if not isinstance(netmask, INT_TYPES): netmask = netmask.int() - return "/%s" % (intToIp(netmask, self._ipversion)) + return "/{0!s}".format((intToIp(netmask, self._ipversion))) elif want == 3: - return "-%s" % (intToIp(self.ip + self.len() - 1, self._ipversion)) + return "-{0!s}".format((intToIp(self.ip + self.len() - 1, self._ipversion))) else: # default - return "/%d" % (self._prefixlen) + return "/{0:d}".format((self._prefixlen)) else: return '' @@ -419,7 +419,7 @@ def strNormal(self, wantprefixlen = None): if self._ipversion == 4: ret = self.strFullsize(0) elif self._ipversion == 6: - ret = ':'.join(["%x" % x for x in [int(x, 16) for x in self.strFullsize(0).split(':')]]) + ret = ':'.join(["{0:x}".format(x) for x in [int(x, 16) for x in self.strFullsize(0).split(':')]]) else: raise ValueError("only IPv4 and IPv6 supported") @@ -453,7 +453,7 @@ def strHex(self, wantprefixlen = None): if self.WantPrefixLen == None and wantprefixlen == None: wantprefixlen = 0 - x = '0x%x' % self.ip + x = '0x{0:x}'.format(self.ip) return x + self._printPrefix(wantprefixlen) def strDec(self, wantprefixlen = None): @@ -468,7 +468,7 @@ def strDec(self, wantprefixlen = None): if self.WantPrefixLen == None and wantprefixlen == None: wantprefixlen = 0 - x = '%d' % self.ip + x = '{0:d}'.format(self.ip) return x + self._printPrefix(wantprefixlen) def iptype(self): @@ -534,7 +534,7 @@ def strNetmask(self): locallen = bits - self._prefixlen return intToIp(((2 ** self._prefixlen) - 1) << locallen, 4) elif self._ipversion == 6: - return "/%d" % self._prefixlen + return "/{0:d}".format(self._prefixlen) def len(self): """Return the length of a subnet. @@ -586,8 +586,7 @@ def __add__(self, other): ret._prefixlen = self.prefixlen() - 1 if not _checkNetaddrWorksWithPrefixlen(ret.ip, ret._prefixlen, ret._ipversion): - raise ValueError("The resulting %s has invalid prefix length (%s)" - % (repr(ret), ret._prefixlen)) + raise ValueError("The resulting {0!s} has invalid prefix length ({1!s})".format(repr(ret), ret._prefixlen)) return ret def __sub__(self, other): @@ -700,7 +699,7 @@ def __repr__(self): IP('10.0.0.0/24') """ - return("IPint('%s')" % (self.strCompressed(1))) + return("IPint('{0!s}')".format((self.strCompressed(1)))) def __cmp__(self, other): @@ -827,7 +826,7 @@ def _getIPv4Map(self): return None ipv4 = self.ip & MAX_IPV4_ADDRESS if self._prefixlen != 128: - ipv4 = '%s/%s' % (ipv4, 32-(128-self._prefixlen)) + ipv4 = '{0!s}/{1!s}'.format(ipv4, 32-(128-self._prefixlen)) return IP(ipv4, ipversion=4) def reverseNames(self): @@ -873,14 +872,14 @@ def reverseNames(self): ipv4 = self._getIPv4Map() if ipv4 is not None: return ipv4.reverseNames() - s = "%x" % self.ip + s = "{0:x}".format(self.ip) if self._prefixlen % 4 != 0: raise NotImplementedError("can't create IPv6 reverse names at sub nibble level") s = list(s) s.reverse() s = '.'.join(s) first_nibble_index = int(32 - (self._prefixlen // 4)) * 2 - return ["%s.ip6.arpa." % s[first_nibble_index:]] + return ["{0!s}.ip6.arpa.".format(s[first_nibble_index:])] else: raise ValueError("only IPv4 and IPv6 supported") @@ -907,21 +906,21 @@ def reverseName(self): s.reverse() first_byte_index = int(4 - (self._prefixlen // 8)) if self._prefixlen % 8 != 0: - nibblepart = "%s-%s" % (s[3-(self._prefixlen // 8)], intToIp(self.ip + self.len() - 1, 4).split('.')[-1]) + nibblepart = "{0!s}-{1!s}".format(s[3-(self._prefixlen // 8)], intToIp(self.ip + self.len() - 1, 4).split('.')[-1]) nibblepart += '.' else: nibblepart = "" s = '.'.join(s[first_byte_index:]) - return "%s%s.in-addr.arpa." % (nibblepart, s) + return "{0!s}{1!s}.in-addr.arpa.".format(nibblepart, s) elif self._ipversion == 6: ipv4 = self._getIPv4Map() if ipv4 is not None: return ipv4.reverseName() - s = '%032x' % self.ip + s = '{0:032x}'.format(self.ip) if self._prefixlen % 4 != 0: - nibblepart = "%s-%x" % (s[self._prefixlen:], self.ip + self.len() - 1) + nibblepart = "{0!s}-{1:x}".format(s[self._prefixlen:], self.ip + self.len() - 1) nibblepart += '.' else: nibblepart = "" @@ -929,7 +928,7 @@ def reverseName(self): s.reverse() s = '.'.join(s) first_nibble_index = int(32 - (self._prefixlen // 4)) * 2 - return "%s%s.ip6.arpa." % (nibblepart, s[first_nibble_index:]) + return "{0!s}{1!s}.ip6.arpa.".format(nibblepart, s[first_nibble_index:]) else: raise ValueError("only IPv4 and IPv6 supported") @@ -943,8 +942,8 @@ def make_net(self, netmask): 127.0.0.0/8 """ if '/' in str(netmask): - raise ValueError("invalid netmask (%s)" % netmask) - return IP('%s/%s' % (self, netmask), make_net=True) + raise ValueError("invalid netmask ({0!s})".format(netmask)) + return IP('{0!s}/{1!s}'.format(self, netmask), make_net=True) def __getitem__(self, key): """Called to implement evaluation of self[key]. @@ -973,7 +972,7 @@ def __repr__(self): IP('10.0.0.0/8') """ - return("IP('%s')" % (self.strCompressed(1))) + return("IP('{0!s}')".format((self.strCompressed(1)))) def get_mac(self): """ @@ -987,13 +986,13 @@ def get_mac(self): return None if (self.ip & 0x20000ffff000000) != 0x20000fffe000000: return None - return '%02x:%02x:%02x:%02x:%02x:%02x' % ( + return '{0:02x}:{1:02x}:{2:02x}:{3:02x}:{4:02x}:{5:02x}'.format( (((self.ip >> 56) & 0xff) & 0xfd), (self.ip >> 48) & 0xff, (self.ip >> 40) & 0xff, (self.ip >> 16) & 0xff, (self.ip >> 8) & 0xff, - self.ip & 0xff, + self.ip & 0xff ) def v46map(self): @@ -1009,19 +1008,18 @@ def v46map(self): """ if self._ipversion == 4: return IP(str(IPV6_MAP_MASK + self.ip) + - "/%s" % (self._prefixlen + 96)) + "/{0!s}".format((self._prefixlen + 96))) else: if self.ip & IPV6_TEST_MAP == IPV6_MAP_MASK: return IP(str(self.ip - IPV6_MAP_MASK) + - "/%s" % (self._prefixlen - 96)) - raise ValueError("%s cannot be converted to an IPv4 address." - % repr(self)) + "/{0!s}".format((self._prefixlen - 96))) + raise ValueError("{0!s} cannot be converted to an IPv4 address.".format(repr(self))) class IPSet(collections.MutableSet): def __init__(self, iterable=[]): # Make sure it's iterable, otherwise wrap if not isinstance(iterable, collections.Iterable): - raise TypeError("'%s' object is not iterable" % type(iterable).__name__) + raise TypeError("'{0!s}' object is not iterable".format(type(iterable).__name__)) # Make sure we only accept IP objects for prefix in iterable: @@ -1087,7 +1085,7 @@ def __and__(self, other): return IPSet(result) def __repr__(self): - return '%s([' % self.__class__.__name__ + ', '.join(map(repr, self.prefixes)) + '])' + return '{0!s}(['.format(self.__class__.__name__) + ', '.join(map(repr, self.prefixes)) + '])' def len(self): return sum(prefix.len() for prefix in self.prefixes) @@ -1278,14 +1276,14 @@ def _parseAddressIPv6(ipstr): if text.startswith("::"): if fill_pos is not None: # Invalid IPv6, eg. '1::2::' - raise ValueError("%r: Invalid IPv6 address: more than one '::'" % ipstr) + raise ValueError("{0!r}: Invalid IPv6 address: more than one '::'".format(ipstr)) fill_pos = len(items) index += 2 continue pos = text.find(':') if pos == 0: # Invalid IPv6, eg. '1::2:' - raise ValueError("%r: Invalid IPv6 address" % ipstr) + raise ValueError("{0!r}: Invalid IPv6 address".format(ipstr)) if pos != -1: items.append(text[:pos]) if text[pos:pos+2] == "::": @@ -1295,7 +1293,7 @@ def _parseAddressIPv6(ipstr): if index == len(ipstr): # Invalid IPv6, eg. '1::2:' - raise ValueError("%r: Invalid IPv6 address" % ipstr) + raise ValueError("{0!r}: Invalid IPv6 address".format(ipstr)) else: items.append(text) break @@ -1304,22 +1302,22 @@ def _parseAddressIPv6(ipstr): # IPv6 ending with IPv4 like '::ffff:192.168.0.1' if (fill_pos is not None) and not (fill_pos <= len(items)-1): # Invalid IPv6: 'ffff:192.168.0.1::' - raise ValueError("%r: Invalid IPv6 address: '::' after IPv4" % ipstr) + raise ValueError("{0!r}: Invalid IPv6 address: '::' after IPv4".format(ipstr)) value = parseAddress(items[-1])[0] - items = items[:-1] + ["%04x" % (value >> 16), "%04x" % (value & 0xffff)] + items = items[:-1] + ["{0:04x}".format((value >> 16)), "{0:04x}".format((value & 0xffff))] # Expand fill_pos to fill with '0' # ['1','2'] with fill_pos=1 => ['1', '0', '0', '0', '0', '0', '0', '2'] if fill_pos is not None: diff = 8 - len(items) if diff <= 0: - raise ValueError("%r: Invalid IPv6 address: '::' is not needed" % ipstr) + raise ValueError("{0!r}: Invalid IPv6 address: '::' is not needed".format(ipstr)) items = items[:fill_pos] + ['0']*diff + items[fill_pos:] # Here we have a list of 8 strings if len(items) != 8: # Invalid IPv6, eg. '1:2:3' - raise ValueError("%r: Invalid IPv6 address: should have 8 hextets" % ipstr) + raise ValueError("{0!r}: Invalid IPv6 address: should have 8 hextets".format(ipstr)) # Convert strings to long integer value = 0 @@ -1331,7 +1329,7 @@ def _parseAddressIPv6(ipstr): except ValueError: error = True if error: - raise ValueError("%r: Invalid IPv6 address: invalid hexlet %r" % (ipstr, item)) + raise ValueError("{0!r}: Invalid IPv6 address: invalid hexlet {1!r}".format(ipstr, item)) value = (value << 16) + item index += 1 return value @@ -1392,7 +1390,7 @@ def parseAddress(ipstr): if ipstr.startswith('0x') and hexval is not None: if hexval > MAX_IPV6_ADDRESS: - raise ValueError("IP Address can't be larger than %x: %x" % (MAX_IPV6_ADDRESS, hexval)) + raise ValueError("IP Address can't be larger than {0:x}: {1:x}".format(MAX_IPV6_ADDRESS, hexval)) if hexval <= MAX_IPV4_ADDRESS: return (hexval, 4) else: @@ -1414,7 +1412,7 @@ def parseAddress(ipstr): bytes = [int(x) for x in bytes] for x in bytes: if x > 255 or x < 0: - raise ValueError("%r: single byte must be 0 <= byte < 256" % (ipstr)) + raise ValueError("{0!r}: single byte must be 0 <= byte < 256".format((ipstr))) return ((bytes[0] << 24) + (bytes[1] << 16) + (bytes[2] << 8) + bytes[3], 4) elif intval is not None: @@ -1422,13 +1420,13 @@ def parseAddress(ipstr): # this ony works for numbers > 255 ... others # will be interpreted as IPv4 first byte if intval > MAX_IPV6_ADDRESS: - raise ValueError("IP Address can't be larger than %x: %x" % (MAX_IPV6_ADDRESS, intval)) + raise ValueError("IP Address can't be larger than {0:x}: {1:x}".format(MAX_IPV6_ADDRESS, intval)) if intval <= MAX_IPV4_ADDRESS: return (intval, 4) else: return (intval, 6) - raise ValueError("IP Address format was invalid: %s" % ipstr) + raise ValueError("IP Address format was invalid: {0!s}".format(ipstr)) def intToIp(ip, version): @@ -1438,20 +1436,20 @@ def intToIp(ip, version): ip = int(ip) if ip < 0: - raise ValueError("IPs can't be negative: %d" % (ip)) + raise ValueError("IPs can't be negative: {0:d}".format((ip))) ret = '' if version == 4: if ip > MAX_IPV4_ADDRESS: - raise ValueError("IPv4 Address can't be larger than %x: %x" % (MAX_IPV4_ADDRESS, ip)) + raise ValueError("IPv4 Address can't be larger than {0:x}: {1:x}".format(MAX_IPV4_ADDRESS, ip)) for l in xrange(4): ret = str(ip & 0xff) + '.' + ret ip = ip >> 8 ret = ret[:-1] elif version == 6: if ip > MAX_IPV6_ADDRESS: - raise ValueError("IPv6 Address can't be larger than %x: %x" % (MAX_IPV6_ADDRESS, ip)) - l = "%032x" % ip + raise ValueError("IPv6 Address can't be larger than {0:x}: {1:x}".format(MAX_IPV6_ADDRESS, ip)) + l = "{0:032x}".format(ip) for x in xrange(1, 33): ret = l[-x] + ret if x % 4 == 0: @@ -1505,7 +1503,7 @@ def _intToBin(val): if val < 0: raise ValueError("Only positive values allowed") - s = "%x" % val + s = "{0:x}".format(val) ret = '' for x in s: ret += _BitTable[x] @@ -1528,7 +1526,7 @@ def _count0Bits(num): # this could be so easy if _count1Bits(~int(num)) would work as excepted num = int(num) if num < 0: - raise ValueError("Only positive Numbers please: %s" % (num)) + raise ValueError("Only positive Numbers please: {0!s}".format((num))) ret = 0 while num > 0: if num & 1 == 1: @@ -1585,7 +1583,7 @@ def _checkNetmask(netmask, masklen): # now check if the rest consists only of ones while bits > 0: if (num & 1) == 0: - raise ValueError("Netmask 0x%x can't be expressed as an prefix." % netmask) + raise ValueError("Netmask 0x{0:x} can't be expressed as an prefix.".format(netmask)) num = num >> 1 bits -= 1 @@ -1635,8 +1633,8 @@ def _remove_subprefix(prefix, subprefix): # Start cutting in half, recursively prefixes = [ - IP('%s/%d' % (prefix[0], prefix._prefixlen + 1)), - IP('%s/%d' % (prefix[int(prefix.len() / 2)], prefix._prefixlen + 1)), + IP('{0!s}/{1:d}'.format(prefix[0], prefix._prefixlen + 1)), + IP('{0!s}/{1:d}'.format(prefix[int(prefix.len() / 2)], prefix._prefixlen + 1)), ] if subprefix in prefixes[0]: return _remove_subprefix(prefixes[0], subprefix) + IPSet([prefixes[1]]) diff --git a/Modules/dirbust.py b/Modules/dirbust.py index df3955a..a26d23f 100644 --- a/Modules/dirbust.py +++ b/Modules/dirbust.py @@ -20,7 +20,7 @@ print "\033[1;37m[-] ----------------------------------------------------------------------------- \033[1;m" for filename in os.listdir(folder): outfile = " -o " + "./results/" + name + "/" + name + "_dirb_" + filename + "_" + port - DIRBSCAN = "dirb %s %s/%s %s -S -r" % (url, folder, filename, outfile) + DIRBSCAN = "dirb {0!s} {1!s}/{2!s} {3!s} -S -r".format(url, folder, filename, outfile) try: results = subprocess.check_output(DIRBSCAN, shell=True) resultarr = results.split("\n") diff --git a/Modules/dnsrecon.py b/Modules/dnsrecon.py index b7da59a..695d1d5 100644 --- a/Modules/dnsrecon.py +++ b/Modules/dnsrecon.py @@ -10,8 +10,8 @@ try: ip_address = sys.argv[1] - HOSTNAME = "host %s | cut -d ' ' -f5 | cut -d '.' -f1,2,3" % (ip_address) - DOMAINNAME = "host %s | cut -d ' ' -f5 | cut -d '.' -f2,3" % (ip_address) + HOSTNAME = "host {0!s} | cut -d ' ' -f5 | cut -d '.' -f1,2,3".format((ip_address)) + DOMAINNAME = "host {0!s} | cut -d ' ' -f5 | cut -d '.' -f2,3".format((ip_address)) port = 53 print "\033[1;37m[-] ----------------------------------------------------------------------------- \033[1;m" diff --git a/Modules/recon.py b/Modules/recon.py index 5a2693e..5d574a8 100644 --- a/Modules/recon.py +++ b/Modules/recon.py @@ -131,7 +131,7 @@ def getIp(): def dnsEnum(ip_address, port): #print('\033[1;34m[*] Detected DNS on {0} : {1}\033[1;m'.format(ip_address, port)) if port.strip() == "53": - SCRIPT = "./Modules/dnsrecon.py %s" % (ip_address) # execute the python script + SCRIPT = "./Modules/dnsrecon.py {0!s}".format((ip_address)) # execute the python script subprocess.call(SCRIPT, shell=True) return @@ -140,7 +140,7 @@ def httpEnum(ip_address, port): #print('\033[1;34m[*] Detected HTTP on {0} : {1}\033[1;m'.format(ip_address, port)) checkpath("./results/") try: - SCRIPT = "./Modules/httprecon.py %s %s" % (ip_address, port) # execute the python script + SCRIPT = "./Modules/httprecon.py {0!s} {1!s}".format(ip_address, port) # execute the python script subprocess.call(SCRIPT, shell=True) except: pass @@ -162,19 +162,19 @@ def mssqlEnum(ip_address, port): def sshEnum(ip_address, port): #print('\033[1;34m[*] Detected SSH on {0} : {1}\033[1;m'.format(ip_address, port)) - SCRIPT = "./Modules/sshrecon.py %s %s" % (ip_address, port) + SCRIPT = "./Modules/sshrecon.py {0!s} {1!s}".format(ip_address, port) subprocess.call(SCRIPT, shell=True) return def telnetEnum(ip_address, port): #print('\033[1;34m[*] Detected TELNET on {0} : {1}\033[1;m'.format(ip_address, port)) - SCRIPT = "./Modules/telnetrecon.py %s %s" % (ip_address, port) + SCRIPT = "./Modules/telnetrecon.py {0!s} {1!s}".format(ip_address, port) subprocess.call(SCRIPT, shell=True) return def snmpEnum(ip_address, port): #print('\033[1;34m[*] Detected SNMP on {0} : {1}\033[1;m'.format(ip_address, port)) - SCRIPT = "./Modules/snmprecon.py %s" % (ip_address) + SCRIPT = "./Modules/snmprecon.py {0!s}".format((ip_address)) subprocess.call(SCRIPT, shell=True) return @@ -182,7 +182,7 @@ def snmpEnum(ip_address, port): def smtpEnum(ip_address, port): #print('\033[1;34m[*] Detected SMTP on {0} : {1}\033[1;m'.format(ip_address, port)) if port.strip() == "25": - SCRIPT = "./Modules/smtprecon.py %s" % (ip_address) + SCRIPT = "./Modules/smtprecon.py {0!s}".format((ip_address)) subprocess.call(SCRIPT, shell=True) else: print '\033[1;33mWARNING: SMTP detected on non-standard port, smtprecon skipped (must run manually)\033[1;m' @@ -192,14 +192,14 @@ def smtpEnum(ip_address, port): def smbEnum(ip_address, port): #print('\033[1;34m[*] Detected SMB on {0} : {1}\033[1;m'.format(ip_address, port)) if port.strip() == "445": - SCRIPT = "./Modules/smbrecon.py %s 2>/dev/null" % (ip_address) + SCRIPT = "./Modules/smbrecon.py {0!s} 2>/dev/null".format((ip_address)) subprocess.call(SCRIPT, shell=True) return def ftpEnum(ip_address, port): #print('\033[1;34m[*] Detected FTP on {0} : {1}\033[1;m'.format(ip_address, port)) - SCRIPT = "./Modules/ftprecon.py %s %s" % (ip_address, port) + SCRIPT = "./Modules/ftprecon.py {0!s} {1!s}".format(ip_address, port) subprocess.call(SCRIPT, shell=True) return diff --git a/Modules/samrdump.py b/Modules/samrdump.py index a39113a..61c18e2 100644 --- a/Modules/samrdump.py +++ b/Modules/samrdump.py @@ -59,7 +59,7 @@ def dump(self, addr): addr. Addr is a valid host name or IP address. """ - logging.info('Retrieving endpoint list from %s' % addr) + logging.info('Retrieving endpoint list from {0!s}'.format(addr)) # Try all requested protocols until one works. entries = [] @@ -67,7 +67,7 @@ def dump(self, addr): protodef = SAMRDump.KNOWN_PROTOCOLS[protocol] port = protodef[1] - logging.info("Trying protocol %s..." % protocol) + logging.info("Trying protocol {0!s}...".format(protocol)) rpctransport = transport.SMBTransport(addr, port, r'\samr', self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, doKerberos = self.__doKerberos) try: @@ -82,7 +82,7 @@ def dump(self, addr): for entry in entries: (username, uid, user) = entry - base = "%s (%d)" % (username, uid) + base = "{0!s} ({1:d})".format(username, uid) print base + '/FullName:', user['FullName'] print base + '/UserComment:', user['UserComment'] print base + '/PrimaryGroupId:', user['PrimaryGroupId'] @@ -94,7 +94,7 @@ def dump(self, addr): if 1 == num: logging.info('Received one entry.') else: - logging.info('Received %d entries.' % num) + logging.info('Received {0:d} entries.'.format(num)) else: logging.info('No entries received.') @@ -116,9 +116,9 @@ def __fetchList(self, rpctransport): print 'Found domain(s):' for domain in domains: - print " . %s" % domain['Name'] + print " . {0!s}".format(domain['Name']) - logging.info("Looking up users in domain %s" % domains[0]['Name']) + logging.info("Looking up users in domain {0!s}".format(domains[0]['Name'])) resp = samr.hSamrLookupDomainInSamServer(dce, serverHandle,domains[0]['Name'] ) @@ -139,7 +139,7 @@ def __fetchList(self, rpctransport): for user in resp['Buffer']['Buffer']: r = samr.hSamrOpenUser(dce, domainHandle, samr.USER_READ_GENERAL | samr.USER_READ_PREFERENCES | samr.USER_READ_ACCOUNT, user['RelativeId']) - print "Found user: %s, uid = %d" % (user['Name'], user['RelativeId'] ) + print "Found user: {0!s}, uid = {1:d}".format(user['Name'], user['RelativeId'] ) info = samr.hSamrQueryInformationUser2(dce, r['UserHandle'],samr.USER_INFORMATION_CLASS.UserAllInformation) entry = (user['Name'], user['RelativeId'], info['Buffer']['All']) @@ -150,7 +150,7 @@ def __fetchList(self, rpctransport): status = resp['ErrorCode'] except ListUsersException, e: - logging.critical("Error listing users: %s" % e) + logging.critical("Error listing users: {0!s}".format(e)) dce.disconnect() diff --git a/Modules/smbrecon.py b/Modules/smbrecon.py index 6eb7014..30d2cc0 100644 --- a/Modules/smbrecon.py +++ b/Modules/smbrecon.py @@ -18,7 +18,7 @@ scanresults = subprocess.check_output(VULNSCAN, shell=True) recon.logparsertxt(scanresults) - NBTSCAN = "./Modules/samrdump.py %s" % (ip) + NBTSCAN = "./Modules/samrdump.py {0!s}".format((ip)) nbtresults = subprocess.check_output(NBTSCAN, shell=True) if ("Connection refused" not in nbtresults) and ("Connect error" not in nbtresults) and ("Connection reset" not in nbtresults): print('\033[1;33m[+] \033[1;33mSAMRDUMP has connected to {0} if there are results displaying them below\033[1;m'.format(ip)) diff --git a/Modules/snmprecon.py b/Modules/snmprecon.py index 68f795d..3d1ff2b 100644 --- a/Modules/snmprecon.py +++ b/Modules/snmprecon.py @@ -15,7 +15,7 @@ print "\033[1;37m[-] ----------------------------------------------------------------------------- \033[1;m" print('\033[1;37m[-] | Starting SNMP scan for {0}\033[1;m'.format(ip_address)) print "\033[1;37m[-] ----------------------------------------------------------------------------- \033[1;m" - ONESIXONESCAN = "onesixtyone %s" % (ip_address) + ONESIXONESCAN = "onesixtyone {0!s}".format((ip_address)) results = subprocess.check_output(ONESIXONESCAN, shell=True).strip() diff --git a/Modules/telnetrecon.py b/Modules/telnetrecon.py index f6a2882..12405e7 100644 --- a/Modules/telnetrecon.py +++ b/Modules/telnetrecon.py @@ -15,7 +15,7 @@ print "\033[1;37m[-] ----------------------------------------------------------------------------- \033[1;m" print('\033[1;37m[-] | Starting hydra TELNET scan against {0}:{1}\033[1;m'.format(ip_address, port)) print "\033[1;37m[-] ----------------------------------------------------------------------------- \033[1;m" - HYDRA = "hydra -L /usr/share/wordlists/metasploit/unix_users.txt -P /usr/share/wordlists/rockyou.txt -f -o ./results/%s/%s_telnethydra.txt -u %s -s %s telnet" % (ip_address, ip_address, ip_address, port) + HYDRA = "hydra -L /usr/share/wordlists/metasploit/unix_users.txt -P /usr/share/wordlists/rockyou.txt -f -o ./results/{0!s}/{1!s}_telnethydra.txt -u {2!s} -s {3!s} telnet".format(ip_address, ip_address, ip_address, port) try: with open(os.devnull, "w") as f: results = subprocess.check_output(HYDRA, shell=True, stdout=f) @@ -29,7 +29,7 @@ print "\033[1;37m[-] ----------------------------------------------------------------------------- \033[1;m" print('\033[1;37m[-] | Starting TELNET script scan for {0}:{1}\033[1;m'.format(ip_address, port)) print "\033[1;37m[-] ----------------------------------------------------------------------------- \033[1;m" - TELNETSCAN = "nmap -sV -Pn -vv -p %s --script=telnet-* -oN './results/%s/%s_telnet.nmap' %s" % (port, ip_address, ip_address, ip_address) + TELNETSCAN = "nmap -sV -Pn -vv -p {0!s} --script=telnet-* -oN './results/{1!s}/{2!s}_telnet.nmap' {3!s}".format(port, ip_address, ip_address, ip_address) results = subprocess.check_output(TELNETSCAN, shell=True) recon.logparsertxt(results) outfile = "results/{0}/{0}_telnetrecon.txt".format(ip_address) diff --git a/Tools/windowsprivcheck.py b/Tools/windowsprivcheck.py index c5311f1..56b5833 100644 --- a/Tools/windowsprivcheck.py +++ b/Tools/windowsprivcheck.py @@ -1345,7 +1345,7 @@ def check_weak_perms(object_name, object_type_s, perms): object_type_s = 'directory' if object_type == None: - print "ERROR: Unknown object type %s" % object_type_s + print "ERROR: Unknown object type {0!s}".format(object_type_s) exit(1) try: @@ -1405,7 +1405,7 @@ def check_weak_perms_sd(object_name, object_type_s, sd, perms): if principle_is_trusted(owner_name, owner_domain): continue else: - principle = "CREATOR OWNER [%s]" % owner_fq + principle = "CREATOR OWNER [{0!s}]".format(owner_fq) for i in ("ACCESS_ALLOWED_ACE_TYPE", "ACCESS_DENIED_ACE_TYPE", "SYSTEM_AUDIT_ACE_TYPE", "SYSTEM_ALARM_ACE_TYPE"): if getattr(ntsecuritycon, i) == ace[0][0]: @@ -1440,7 +1440,7 @@ def dump_perms(object_name, object_type_s, options={}): object_type_s = 'directory' if object_type == None: - print "ERROR: Unknown object type %s" % object_type_s + print "ERROR: Unknown object type {0!s}".format(object_type_s) exit(1) try: @@ -1528,7 +1528,7 @@ def dump_acl(object_name, object_type_s, sd, options={}): #print "[D] Ignoring trusted principle (creator owner) %s\\%s" % (principle, domain) continue else: - principle = "CREATOR OWNER [%s\%s]" % (domain, principle) + principle = "CREATOR OWNER [{0!s}\{1!s}]".format(domain, principle) for i in ("ACCESS_ALLOWED_ACE_TYPE", "ACCESS_DENIED_ACE_TYPE", "SYSTEM_AUDIT_ACE_TYPE", "SYSTEM_ALARM_ACE_TYPE"): if getattr(ntsecuritycon, i) == ace[0][0]: @@ -1663,7 +1663,7 @@ def audit_processes(): pids = win32process.EnumProcesses() for pid in sorted(pids): print "---------------------------------------------------------" - print "PID: %s" % pid + print "PID: {0!s}".format(pid) # TODO there's a security descriptor for each process accessible via GetSecurityInfo according to http://msdn.microsoft.com/en-us/library/ms684880%28VS.85%29.aspx ph = 0 @@ -1702,7 +1702,7 @@ def audit_processes(): gotexe = 1 except: pass - print "Filename: %s" % exe + print "Filename: {0!s}".format(exe) gottokenh = 0 @@ -1713,17 +1713,17 @@ def audit_processes(): sidObj, intVal = win32security.GetTokenInformation(tokenh, TokenUser) if sidObj: accountName, domainName, accountTypeInt = win32security.LookupAccountSid(remote_server, sidObj) - print "TokenUser: %s\%s (type %s)" % (domainName, accountName, accountTypeInt) + print "TokenUser: {0!s}\{1!s} (type {2!s})".format(domainName, accountName, accountTypeInt) sidObj = win32security.GetTokenInformation(tokenh, TokenOwner) if sidObj: accountName, domainName, accountTypeInt = win32security.LookupAccountSid(remote_server, sidObj) - print "TokenOwner: %s\%s (type %s)" % (domainName, accountName, accountTypeInt) + print "TokenOwner: {0!s}\{1!s} (type {2!s})".format(domainName, accountName, accountTypeInt) sidObj = win32security.GetTokenInformation(tokenh, TokenPrimaryGroup) if sidObj: accountName, domainName, accountTypeInt = win32security.LookupAccountSid(remote_server, sidObj) - print "TokenPrimaryGroup: %s\%s (type %s)" % (domainName, accountName, accountTypeInt) + print "TokenPrimaryGroup: {0!s}\{1!s} (type {2!s})".format(domainName, accountName, accountTypeInt) except: print "OpenProcessToken with TOKEN_QUERY: Failed" print "TokenUser: Unknown" @@ -1760,7 +1760,7 @@ def audit_processes(): # print "EnumProcessModules: Success" if ph: - print "IsWow64 Process: %s" % win32process.IsWow64Process(ph) + print "IsWow64 Process: {0!s}".format(win32process.IsWow64Process(ph)) if gottokenh: vprint("OpenProcessToken with TOKEN_QUERY: Success") @@ -1790,7 +1790,7 @@ def audit_processes(): print "Token Source: Unknown (Access Denied)" try: - print "TokenImpersonationLevel: %s" % win32security.GetTokenInformation(tokenh, TokenImpersonationLevel) # doesn't work on xp + print "TokenImpersonationLevel: {0!s}".format(win32security.GetTokenInformation(tokenh, TokenImpersonationLevel)) # doesn't work on xp except: pass @@ -1799,7 +1799,7 @@ def audit_processes(): if r == 0: print "TokenHasRestrictions: 0 (not filtered)" else: - print "TokenHasRestrictions: %s (token has been filtered)" % r + print "TokenHasRestrictions: {0!s} (token has been filtered)".format(r) except: pass @@ -1812,23 +1812,23 @@ def audit_processes(): elif e == 3: print "TokenElevationType: TokenElevationTypeLimited" else: - print "TokenElevationType: Unknown (%s)" % e + print "TokenElevationType: Unknown ({0!s})".format(e) except: pass try: - print "TokenUIAccess: %s" % win32security.GetTokenInformation(tokenh, TokenUIAccess) # doesn't work on xp + print "TokenUIAccess: {0!s}".format(win32security.GetTokenInformation(tokenh, TokenUIAccess)) # doesn't work on xp except: pass try: - print "TokenLinkedToken: %s" % win32security.GetTokenInformation(tokenh, TokenLinkedToken) # vista + print "TokenLinkedToken: {0!s}".format(win32security.GetTokenInformation(tokenh, TokenLinkedToken)) # vista except: pass try: - print "TokenLogonSid: %s" % win32security.GetTokenInformation(tokenh, TokenLogonSid) # doesn't work on xp - print "TokenElevation: %s" % win32security.GetTokenInformation(tokenh, TokenElevation) # vista + print "TokenLogonSid: {0!s}".format(win32security.GetTokenInformation(tokenh, TokenLogonSid)) # doesn't work on xp + print "TokenElevation: {0!s}".format(win32security.GetTokenInformation(tokenh, TokenElevation)) # vista except: pass @@ -1839,7 +1839,7 @@ def audit_processes(): user = domainName + "\\" + accountName + " (" + win32security.ConvertSidToStringSid(sid) + ")" except: user = win32security.ConvertSidToStringSid(sid) - print "TokenIntegrityLevel: %s %s" % (user, i) + print "TokenIntegrityLevel: {0!s} {1!s}".format(user, i) except: pass @@ -1854,7 +1854,7 @@ def audit_processes(): elif m == 3: print "TokenMandatoryPolicy: POLICY_VALID_MASK" else: - print "TokenMandatoryPolicy: %s" % m + print "TokenMandatoryPolicy: {0!s}".format(m) except: pass @@ -1889,7 +1889,7 @@ def audit_processes(): user = domainName + "\\" + accountName + " (" + win32security.ConvertSidToStringSid(sid) + ")" except: user = win32security.ConvertSidToStringSid(sid) - print "\t%s: %s" % (user, attr_str) + print "\t{0!s}: {1!s}".format(user, attr_str) # Link that explains how privs are added / removed from tokens: # http://support.microsoft.com/kb/326256 print "\nToken Privileges:" @@ -1915,7 +1915,7 @@ def audit_processes(): attr_str_a.append("REMOVED") if attr_str_a: attr_str = ("|").join(attr_str_a) - print "\t%s: %s" % (win32security.LookupPrivilegeName(remote_server, priv_val), attr_str) + print "\t{0!s}: {1!s}".format(win32security.LookupPrivilegeName(remote_server, priv_val), attr_str) #print "\nProcess ACL (buggy - probably wrong):" @@ -1925,14 +1925,14 @@ def audit_processes(): # accountName, domainName, accountTypeInt = win32security.LookupAccountSid(remote_server, sidObj) # print "User: %s\%s (type %s)" % (domainName, accountName, accountTypeInt) if gotexe: - print "\nFile permissions on %s:" % exe + print "\nFile permissions on {0!s}:".format(exe) dump_perms(exe, 'file', {'brief': 1}) print if mhs and ph: for mh in mhs: dll = win32process.GetModuleFileNameEx(ph, mh) - print "Loaded module: %s" % dll + print "Loaded module: {0!s}".format(dll) dump_perms(dll, 'file', {'brief': 1}) print @@ -2123,7 +2123,7 @@ def audit_services(): print("Binary (clean): [Missing Binary/Remote]") print("Run as: " + service_info[7]) - print "\nFile Permissions on executable %s:" % binary + print "\nFile Permissions on executable {0!s}:".format(binary) if binary: dump_perms(binary, 'file', {'brief': 1}) else: @@ -2206,9 +2206,9 @@ def print_weak_perms(type, weak_perms, options={}): slash = "" if brief: - print "\t%s%s%s%s: %s" % (acl_type, domain, slash, principle, perm) + print "\t{0!s}{1!s}{2!s}{3!s}: {4!s}".format(acl_type, domain, slash, principle, perm) else: - print "\t%s%s%s%s has permission %s on %s %s" % (acl_type, domain, slash, principle, perm, type, object_name) + print "\t{0!s}{1!s}{2!s}{3!s} has permission {4!s} on {5!s} {6!s}".format(acl_type, domain, slash, principle, perm, type, object_name) def check_path(path, issue_no): dirs = set(path.split(';')) @@ -2283,11 +2283,11 @@ def check_user_paths(): principle, domain, type = win32security.LookupAccountSid(remote_server, user_sid) user_fq = domain + "\\" + principle except: - print "WARNING: Can't convert sid %s to name. Skipping." % user_sid_s + print "WARNING: Can't convert sid {0!s} to name. Skipping.".format(user_sid_s) continue path = user_path[1] - vprint("Checking path of %s" % user_fq) + vprint("Checking path of {0!s}".format(user_fq)) global tmp_trusted_principles_fq tmp_trusted_principles_fq = (user_fq) check_path(path, "WPC015") @@ -2385,11 +2385,11 @@ def audit_shares(): print "Path: " + share['path'] print "Remark: " + share['remark'] print "Type(s): " + "|".join(types) - print "Reserved: %s" % share['reserved'] - print "Passwd: %s" % share['passwd'] - print "Current Uses: %s" % share['current_uses'] - print "Max Uses: %s" % share['max_uses'] - print "Permissions: %s" % share['permissions'] + print "Reserved: {0!s}".format(share['reserved']) + print "Passwd: {0!s}".format(share['passwd']) + print "Current Uses: {0!s}".format(share['current_uses']) + print "Max Uses: {0!s}".format(share['max_uses']) + print "Permissions: {0!s}".format(share['permissions']) print "Sec. Desc.: " dump_sd(share['netname'], 'share', share['security_descriptor']) except: @@ -2502,24 +2502,24 @@ def audit_passpol(): try: data = win32net.NetUserModalsGet(remote_server, 0) for key in data.keys(): - print "%s: %s" % (key, data[key]) + print "{0!s}: {1!s}".format(key, data[key]) data = win32net.NetUserModalsGet(remote_server, 1) for key in data.keys(): - print "%s: %s" % (key, data[key]) + print "{0!s}: {1!s}".format(key, data[key]) data = win32net.NetUserModalsGet(remote_server, 2) for key in data.keys(): if key == 'domain_id': - print "%s: %s" % (key, win32security.ConvertSidToStringSid(data[key])) + print "{0!s}: {1!s}".format(key, win32security.ConvertSidToStringSid(data[key])) elif key == 'lockout_threshold' and data[key] == '0': - print "%s: %s (accounts aren't locked out)" % (key, data[key]) + print "{0!s}: {1!s} (accounts aren't locked out)".format(key, data[key]) else: - print "%s: %s" % (key, data[key]) + print "{0!s}: {1!s}".format(key, data[key]) data = win32net.NetUserModalsGet(remote_server, 3) for key in data.keys(): if key == 'lockout_threshold' and data[key] == 0: - print "%s: %s (accounts aren't locked out)" % (key, data[key]) + print "{0!s}: {1!s} (accounts aren't locked out)".format(key, data[key]) else: - print "%s: %s" % (key, data[key]) + print "{0!s}: {1!s}".format(key, data[key]) except: print "[E] Couldn't get NetUserModals data" @@ -2593,7 +2593,7 @@ def audit_logged_in(): while True: users, total, resume = win32net.NetWkstaUserEnum(remote_server, 1 , resume , 999999 ) for user in users: - print "User logged in: Logon Server=\"%s\" Logon Domain=\"%s\" Username=\"%s\"" % (user['logon_server'], user['logon_domain'], user['username']) + print "User logged in: Logon Server=\"{0!s}\" Logon Domain=\"{1!s}\" Username=\"{2!s}\"".format(user['logon_server'], user['logon_domain'], user['username']) if resume == 0: break except: @@ -2625,11 +2625,11 @@ def audit_host_info(): #print win32net.NetWkstaGetInfo(remote_server, 100) #print win32net.NetWkstaGetInfo(remote_server, 101) serverinfo = win32net.NetWkstaGetInfo(remote_server, 102) - print "Computer Name: %s" % serverinfo['computername'] - print "Langroup: %s" % serverinfo['langroup'] - print "OS: %s.%s" % (serverinfo['ver_major'], serverinfo['ver_minor']) - print "Logged On Users: %s" % serverinfo['logged_on_users'] - print "Lanroot: %s" % serverinfo['lanroot'] + print "Computer Name: {0!s}".format(serverinfo['computername']) + print "Langroup: {0!s}".format(serverinfo['langroup']) + print "OS: {0!s}.{1!s}".format(serverinfo['ver_major'], serverinfo['ver_minor']) + print "Logged On Users: {0!s}".format(serverinfo['logged_on_users']) + print "Lanroot: {0!s}".format(serverinfo['lanroot']) if serverinfo['platform_id'] & win32netcon.PLATFORM_ID_NT: print "Platform: PLATFORM_ID_NT (means NT family, not NT4)" @@ -2652,11 +2652,11 @@ def audit_host_info(): #print "NetServerGetInfo 100" + str(win32net.NetServerGetInfo(remote_server, 100)) #print "NetServerGetInfo 101" + str(win32net.NetServerGetInfo(remote_server, 101)) serverinfo = win32net.NetServerGetInfo(remote_server, 102) - print "Name: %s" % serverinfo['name'] - print "Comment: %s" % serverinfo['comment'] - print "OS: %s.%s" % (serverinfo['version_major'], serverinfo['version_minor']) - print "Userpath: %s" % serverinfo['userpath'] - print "Hidden: %s" % serverinfo['hidden'] + print "Name: {0!s}".format(serverinfo['name']) + print "Comment: {0!s}".format(serverinfo['comment']) + print "OS: {0!s}.{1!s}".format(serverinfo['version_major'], serverinfo['version_minor']) + print "Userpath: {0!s}".format(serverinfo['userpath']) + print "Hidden: {0!s}".format(serverinfo['hidden']) if serverinfo['platform_id'] & win32netcon.PLATFORM_ID_NT: print "Platform: PLATFORM_ID_NT (means NT family, not NT4)" @@ -2783,16 +2783,16 @@ def audit_user_group(): break sid, s, i = win32security.LookupAccountName(remote_server, group['name']) sid_string = win32security.ConvertSidToStringSid(sid) - print "Group %s has sid %s" % (group['name'], sid_string) + print "Group {0!s} has sid {1!s}".format(group['name'], sid_string) for m in members: - print "Group %s has member: %s" % (group['name'], m) + print "Group {0!s} has member: {1!s}".format(group['name'], m) if verbose: try: privs = win32security.LsaEnumerateAccountRights(ph, sid) for priv in privs: - print "Group %s has privilege: %s" % (group['name'], priv) + print "Group {0!s} has privilege: {1!s}".format(group['name'], priv) except: - print "Group %s: privilege lookup failed " % (group['name']) + print "Group {0!s}: privilege lookup failed ".format((group['name'])) print print "[+] Non-local Groups" @@ -2823,16 +2823,16 @@ def audit_user_group(): break sid, s, i = win32security.LookupAccountName(remote_server, group['name']) sid_string = win32security.ConvertSidToStringSid(sid) - print "Group %s has sid %s" % (group['name'], sid_string) + print "Group {0!s} has sid {1!s}".format(group['name'], sid_string) for m in members: - print "Group %s has member: %s" % (group['name'], m) + print "Group {0!s} has member: {1!s}".format(group['name'], m) if verbose: try: privs = win32security.LsaEnumerateAccountRights(ph, sid) for priv in privs: - print "Group %s has privilege: %s" % (group['name'], priv) + print "Group {0!s} has privilege: {1!s}".format(group['name'], priv) except: - print "Group %s has no privileges" % (group['name']) + print "Group {0!s} has no privileges".format((group['name'])) print print "[+] Users" @@ -2865,7 +2865,7 @@ def audit_user_group(): gprivs = [] sid, s, i = win32security.LookupAccountName(remote_server, user) sid_string = win32security.ConvertSidToStringSid(sid) - print "User %s has sid %s" % (user, sid_string) + print "User {0!s} has sid {1!s}".format(user, sid_string) groups = win32net.NetUserGetLocalGroups(remote_server, user, 0) for group in groups: gsid, s, i = win32security.LookupAccountName(remote_server, group) @@ -2874,13 +2874,13 @@ def audit_user_group(): gprivs = list(list(gprivs) + list(privs)) except: pass - print "User %s is in this local group: %s" % (user, group) + print "User {0!s} is in this local group: {1!s}".format(user, group) group_list = win32net.NetUserGetGroups(remote_server, user) groups = [] for g in group_list: groups.append(g[0]) for group in groups: - print "User %s is in this non-local group: %s" % (user, group) + print "User {0!s} is in this non-local group: {1!s}".format(user, group) if verbose: privs = [] try: @@ -2888,7 +2888,7 @@ def audit_user_group(): except: pass for priv in list(set(list(gprivs) + list(privs))): - print "User %s has privilege %s" % (user, priv) + print "User {0!s} has privilege {1!s}".format(user, priv) if verbose: print @@ -2910,13 +2910,13 @@ def audit_user_group(): type_string = "group" if type == 5: type_string = "user" - print "Privilege %s (%s) is held by %s\%s (%s)" % (priv, priv_desc, domain, name, type_string) + print "Privilege {0!s} ({1!s}) is held by {2!s}\{3!s} ({4!s})".format(priv, priv_desc, domain, name, type_string) # print "Privilege %s is held by %s\%s (%s)" % (priv, domain, name, type_string) except: #print "Skipping %s - doesn't exist for this platform" % priv pass -print "windows-privesc-check v%s (http://pentestmonkey.net/windows-privesc-check)\n" % version +print "windows-privesc-check v{0!s} (http://pentestmonkey.net/windows-privesc-check)\n".format(version) # Process Command Line Options try: