def _node_info_windows(_tm_env, runtime): """Generate a node information report for the scheduler. :param _tm_env: Treadmill application environment :type _tm_env: `appenv.AppEnvironment` :param runtime: Treadmill runtime in use :type runtime: `str` """ if runtime != 'docker': # Raising an exception will ensure windows is started with docker # runtime enabled raise NotImplementedError( 'Runtime {0} is not supported on Windows'.format(runtime)) info = _get_docker_node_info({ 'up_since': up_since(), }) dc_name = win32security.DsGetDcName() info.update({ 'nt.dc': dc_name['DomainControllerName'].replace('\\\\', '').lower(), 'nt.domain': dc_name['DomainName'].lower(), 'nt.dn': win32api.GetComputerObjectName(win32con.NameFullyQualifiedDN) }) return info
def __init__(self, tm_env): data = nodedata.get(tm_env.configs_dir) self._config = GMSAConfig(data['nt_group_ou'], data['nt_group_pattern']) dc_name = win32security.DsGetDcName() self._dc = dc_name['DomainControllerName'].replace('\\\\', '').lower() self._dn = win32api.GetComputerObjectName( win32con.NameFullyQualifiedDN).lower()
def __init__(self, tm_env): with io.open(os.path.join(tm_env.configs_dir, 'node.json')) as f: data = json.load(f) self._config = GMSAConfig(data['nt_group_ou'], data['nt_group_pattern']) dc_name = win32security.DsGetDcName() self._dc = dc_name['DomainControllerName'].replace('\\\\', '').lower() self._dn = win32api.GetComputerObjectName( win32con.NameFullyQualifiedDN).lower()
def getLoginDetails(): """ Get current user, domain controller. """ user = win32api.GetUserName() domain = win32api.GetDomainName() hostname = win32api.GetComputerName() if domain == hostname: return (user, None) else: try: d = win32security.DsGetDcName(domainName=domain) return (user, d['DomainControllerName']) except win32security.error: return (user, None)
def dump_misc_checks(self): # Check if host is in a domain in_domain = 0 dc_info = None try: dc_info = win32security.DsGetDcName(None, None, None, None, 0) in_domain = 1 except: pass if in_domain: print "[+] Host is in domain" for k in dc_info.keys(): print "[-] %s => %s" % (k, dc_info[k]) else: print "[+] Host is not in domain"
def generate(proid, name, client=None): """Generates a credential spec file for the given GMSA proid and returns the path to the file. """ credential_specs_path = _get_path(client) dc_name = win32security.DsGetDcName() account_name = win32security.LookupAccountName(None, dc_name['DomainName']) dns_name = dc_name['DomainName'] net_bios_name = account_name[1] sid = win32security.ConvertSidToStringSid(account_name[0]) guid = str(uuid.UUID(str(dc_name['DomainGuid']))) doc = { 'CmsPlugins': ['ActiveDirectory'], 'DomainJoinConfig': { 'Sid': sid, 'MachineAccountName': proid, 'Guid': guid, 'DnsTreeName': dns_name, 'DnsName': dns_name, 'NetBiosName': net_bios_name }, 'ActiveDirectoryConfig': { 'GroupManagedServiceAccounts': [{ 'Name': proid, 'Scope': dns_name }, { 'Name': proid, 'Scope': net_bios_name }] } } path = os.path.join(credential_specs_path, name + '.json') with io.open(path, 'w') as f: f.writelines(utils.json_genencode(doc, indent=4)) return 'file://{}.json'.format(name)
def SpnRegister( serviceAcctDN, # DN of the service's logon account spns, # List of SPNs to register operation, # Add, replace, or delete SPNs ): assert type(spns) not in [str, str] and hasattr(spns, "__iter__"), ( "spns must be a sequence of strings (got %r)" % spns) # Bind to a domain controller. # Get the domain for the current user. samName = win32api.GetUserNameEx(win32api.NameSamCompatible) samName = samName.split("\\", 1)[0] if not serviceAcctDN: # Get the SAM account name of the computer object for the server. serviceAcctDN = win32api.GetComputerObjectName( win32con.NameFullyQualifiedDN) logger.debug("SpnRegister using DN '%s'", serviceAcctDN) # Get the name of a domain controller in that domain. info = win32security.DsGetDcName( domainName=samName, flags=dscon.DS_IS_FLAT_NAME | dscon.DS_RETURN_DNS_NAME | dscon.DS_DIRECTORY_SERVICE_REQUIRED, ) # Bind to the domain controller. handle = win32security.DsBind(info["DomainControllerName"]) # Write the SPNs to the service account or computer account. logger.debug("DsWriteAccountSpn with spns %s") win32security.DsWriteAccountSpn( handle, # handle to the directory operation, # Add or remove SPN from account's existing SPNs serviceAcctDN, # DN of service account or computer account spns, ) # names # Unbind the DS in any case (but Python would do it anyway) handle.Close()
def dumptab_misc_checks(self): # Check if host is in a domain in_domain = 0 dc_info = None try: dc_info = win32security.DsGetDcName(None, None, None, None, 0) in_domain = 1 except: pass # DC information if available if in_domain: print wpc.utils.tab_line("info", "in_domain", "yes") for k in dc_info.keys(): print wpc.utils.tab_line("info", "dc", k, dc_info[k]) else: print wpc.utils.tab_line("info", "in_domain", "no") # misc information that appears in HTML report for i in [ 'hostname', 'datetime', 'version', 'user', 'domain', 'ipaddress', 'os', 'os_version' ]: print wpc.utils.tab_line("info", i, self.report.get_info_item(i))
def testDsGetDcName(self): # Not sure what we can actually test here! At least calling it # does something :) win32security.DsGetDcName()
def GetDomainFull(server): return win32security.DsGetDcName(computerName=server)['DomainName']
def GetDomain(server): return win32security.DsGetDcName( computerName=server)['DomainName'].split('.')[0]
def GetDomainDN(server): dn = '' domain = win32security.DsGetDcName(computerName=server)['DomainName'] for s in domain.split('.'): dn += "DC=%s," % s return dn[:-1]
def collection(): global path, date, sys_os, hostname, ipaddr, aname, dir, sqldir infile = [] outfile = "" sqlfile = "" sqlline = "" info = [] flag = 0 flag2 = 0 flag3 = 0 proc = 0 processor = "" commandline = "" bname = dir + aname sqlname = sqldir + aname logfile = open(dir + "assessment-log.txt", 'w') skip = 0 #Start by getting System Info infile = subprocess.Popen("systeminfo.exe", stdout=PIPE, stderr=PIPE) infile = infile.communicate()[0].split("\n") outfile = open(bname + "-systeminfo.txt", 'w') sqlfile = open(sqlname + "-systeminfo.csv", 'w') sqlfile.write("IP") for line in infile: line = line[:-1] if line != "" and line.startswith("Hotfix") == 0 and flag == 0: info = line.split(":", 1) info[0] = info[0].lstrip() info[1] = info[1].lstrip() if info[0].startswith("Proc") == 1: processor = info[0] proc = 1 elif proc == 1: info[0] = processor outfile.write(info[0] + "," + info[1] + "\n") sqlfile.write("," + info[0]) sqlline += "," + info[1] proc = 0 else: info[1] = info[1].split(",")[0] outfile.write(info[0] + "," + info[1] + "\n") sqlfile.write("," + info[0]) sqlline += "," + info[1] elif line.startswith("Hotfix") == 1: flag = 1 outfile.close sqlfile.write("\n" + ipaddr + sqlline) sqlfile.close logfile.write('Systeminfo module Passed\n') #Get the Software Registry infile = subprocess.Popen( "regedit.exe /E /S " + bname + "-Software-Registry.reg HKEY_LOCAL_MACHINE\\Software") logfile.write('Software Reg Module Passed\n') #get the environment variables CSV and raw file outfile = open(sqlname + "-environment-variables.csv", 'w') rawfile = open(bname + "-env-variables.txt", 'w') header = "key/ip,VarName,Value\n" outfile.write(header) #Get environment variables for key in os.environ: outfile.write(ipaddr + "," + key + "," + os.environ[key] + "\n") rawfile.write(key + ":\t" + os.environ[key] + "\n") rawfile.close outfile.close logfile.write('Environment Var Module Passed\n') #get IP and Interface information with open(bname + '-ipconfig.txt', 'w') as outfile: subprocess.call('ipconfig.exe /all', stdout=outfile) logfile.write('IPConfig Module Passed\n') #get AD DC and domain name information try: dc = win32security.DsGetDcName() if dc: dcfile = open(sqlname + '-wkstation-AD-info.csv', 'w') header = "ip/key,DomainControllerAddress,DnsForestName,DomainName,DomainControllerName" dcfile.write(header + "\n") dcfile.write(ipaddr + "," + dc['DomainControllerAddress'][2:] + "," + dc['DnsForestName'] + "," + dc['DomainName'] + "," + dc['DomainControllerName'][2:] + "\n") dcfile.close logfile.write('AD DC/Name Module Passed\n') except: logfile.write('AD DC/Name Module failed/no domain\n') pass #get IP routing informatino with open(bname + '-Routes.txt', 'w') as outfile: subprocess.call('netstat.exe -nr ', stdout=outfile) logfile.write('IP Route Raw Module Passed\n') #Get Network Listeners Raw with open(bname + '-TCP-NetworkListeners.txt', 'w') as outfile: p1 = subprocess.Popen('netstat.exe -nao', stdout=PIPE) p2 = subprocess.Popen('findstr /c:LISTEN', stdin=p1.stdout, stdout=outfile) logfile.write('TCP Netstat Raw Module Passed\n') with open(bname + '-UDP-NetworkListeners.txt', 'w') as outfile: p1 = subprocess.Popen('netstat.exe -nao', stdout=PIPE) p2 = subprocess.Popen('findstr /c:*:*', stdin=p1.stdout, stdout=outfile) logfile.write('UDP Netstat Raw Module Passed\n') #Get Network Listeners CSV """ Uses a combination of PSUTIL module and Sysinternals and OS utilities to create two tables for TCP and UDP and give src, dst, ports, PIDs, and command line or executable """ netstat_header = [] tcp_listen = open(sqlname + '-netstat-listeners-TCP.csv', 'w') udp_listen = open(sqlname + '-netstat-listeners-UDP.csv', 'w') netstat = subprocess.Popen('netstat.exe -nao', stdout=PIPE, stderr=PIPE) netstat = netstat.communicate()[0].split("\n") for line in netstat: print 'Hit "c" to skip if needed...\n' if msvcrt.kbhit(): if ord(msvcrt.getch()) == 99 or ord(msvcrt.getch()) == 67: skip = 1 break line = line.split() if line and line[0] == "Proto": line.pop(2) line.pop(3) line.append("Executable") line.insert(0, "key/ip") tcp_listen.write(",".join(line) + '\n') line.pop(4) udp_listen.write(",".join(line) + '\n') elif line and line[0] == "TCP" and line[3] == "LISTENING": try: process = Process(int(line[4])) try: cmd = process.exe line.append(cmd) except: process = subprocess.Popen( [path + 'tcpvcon.exe', '-a', '-c', '-n', line[4]], stdout=PIPE) process = process.communicate()[0].split(",") line.append(process[1]) except: cmd = 'orphaned process' line.append(cmd) line.insert(0, ipaddr) tcp_listen.write(','.join(str(line)[1:-1]) + '\n') elif line and line[0] == "UDP" and line[2] == "*:*": process = Process(int(line[3])) try: cmd = process.exe line.append(cmd) except: process = subprocess.Popen( [path + 'tcpvcon.exe', '-a', '-c', '-n', line[3]], stdout=PIPE) process = process.communicate()[0].split(",") line.append(process[1]) line.insert(0, ipaddr) udp_listen.write(','.join(str(line)[1:-1]) + '\n') tcp_listen.close udp_listen.close if skip == 1: logfile.write('Listeners CSV Module SKIPPED\n') skip = 0 else: logfile.write('Listeners CSV Module Passed\n') #get local users and group membership users = NetUserEnum(None, 2) header = "ip/key,name,full_name,password_age,num_logons,acct_expires,last_logon,groups\n" sqlfile = open(sqlname + '-localusers.csv', 'w') sqlfile.write(header) for x in range(len(users[0])): groups = NetUserGetLocalGroups(None, users[0][x]['name']) groups = ",".join(groups) + "\n" if users[0][x]['acct_expires'] == -1: line = ",".join( (ipaddr, users[0][x]['name'], users[0][x]['full_name'], str(users[0][x]['password_age'] / 60 / 60 / 24), str(users[0][x]['num_logons']), 'NEVER', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(users[0][x]['last_logon'])), groups)) else: line = ",".join( (ipaddr, users[0][x]['name'], users[0][x]['full_name'], str(users[0][x]['password_age'] / 60 / 60 / 24), str(users[0][x]['num_logons']), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(users[0][x]['acct_expires'])), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(users[0][x]['last_logon'])), groups)) sqlfile.write(line) logfile.write('Local User and Group Module Passed\n') #get AD Users and membership if DC present try: dc = NetGetDCName() header = 'DC,name,full_name,password_age,num_logons,acct_expires,last_logon,groups\n' sqlfile = open(sqlname + "-AD-Users.csv", "w") sqlfile.write(header) #dc = NetGetDCName() users = NetUserEnum(dc, 2) adgroups = [] if dc: for x in range(len(users[0])): groups = NetUserGetGroups(dc, users[0][x]['name']) for y in range(len(groups)): adgroups.append(str(groups[y][0])) groups = ",".join(adgroups) + "\n" adgroups = [] line = ",".join( (ipaddr, users[0][x]['name'], users[0][x]['full_name'], str(users[0][x]['password_age'] / 60 / 60 / 24), str(users[0][x]['num_logons']), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime( users[0][x]['acct_expires'])), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(users[0][x]['last_logon'])), groups)) sqlfile.write(line) #code logfile.write('AD Users Module Passed\n') except: logfile.write('AD Users Module Failed/No Domain\n') pass #get local groups and group membership groups = [] header = "ip/key,group_name,users\n" sqlfile = open(sqlname + '-localgroups.csv', 'w') sqlfile.write(header) line = subprocess.Popen('net.exe localgroup', stdout=PIPE) line = line.communicate()[0].split("\n") for x in range(len(line)): if line[x].startswith('*'): groups.append(line[x][1:-1]) for x in range(len(groups)): temp = NetLocalGroupGetMembers(socket.gethostname(), groups[x], 1) for y in range(len(temp[0])): groups[x] = ",".join((groups[x], temp[0][y]['name'])) groups[x] = ",".join((ipaddr, groups[x], "\n")) sqlfile.write(groups[x]) logfile.write('Local group Module Passed\n') #get AD groups and membership if DC present try: dc = NetGetDCName() adgroups = [] adgroup = "" users = [] sqlfile = open(sqlname + '-AD-Groups.csv', 'w') header = 'DC,ADGroupName,Users\n' sqlfile.write(header) if dc: groups = NetGroupEnum(dc, 2) for x in range(len(groups[0])): users = NetGroupGetUsers(dc, str(groups[0][x]['name']), 1) for y in range(len(users[0])): adgroups.append(str(users[0][y]['name'])) adgroup = dc + "," + str( groups[0][x]['name']) + "," + ",".join(adgroups) + "\n" sqlfile.write(adgroup) adgroups = [] logfile.write('AD Group Module Passed\n') except: logfile.write('AD Group Module Failed/No Domain\n') pass #Get local shares header = 'ip/key,sharename,path\n' sqlfile = open(sqlname + '-localshares.csv', 'w') sqlfile.write(header) line = NetShareEnum(socket.gethostname(), 2) for x in range(len(line[0])): share = ",".join((ipaddr, str(line[0][x]['netname']), str(line[0][x]['path']), "\n")) sqlfile.write(share) logfile.write("Local Share Module Passed\n") #Get password policy with open(bname + '-password-policy.txt', 'w') as outfile: subprocess.call('net.exe accounts', stdout=outfile) logfile.write('Password Policy Module Passed\n') """ Add post processing """ #NBTSTAT try: with open(bname + '-nbtstat-cachednames.txt', 'w') as outfile: subprocess.call('nbtstat.exe -r', stdout=outfile) with open(bname + '-nbtstat-remotesessions.txt', 'w') as outfile: subprocess.call('nbtstat.exe -S', stdout=outfile) logfile.write('NBTSTAT Module Passed\n') except: logfile.write( 'NBTSTAT Module Failed/64bit System?\n') pass #with open(bname + '-nbtstat-cachednames.txt', 'w') as outfile: # subprocess.call('nbtstat.exe -r', stdout=outfile) #with open(bname + '-nbtstat-remotesessions.txt', 'w') as outfile: # subprocess.call('nbtstat.exe -S', stdout=outfile) #get firewall info with open(bname + '-firewall-config.txt', 'w') as outfile: subprocess.call('netsh.exe firewall show config', stdout=outfile) logfile.write('firewall module Passed\n') """ Add post processing """ #Get task / process list try: with open(bname + '-tasks-tasklist.txt', 'w') as outfile: subprocess.call('tasklist.exe', stdout=outfile) logfile.write('tasklist module Passed\n') except: logfile.write('tasklist module failed\n') try: with open(bname + '-tasks-wmic.txt', 'w') as outfile: subprocess.call('wmic.exe process list', stdout=outfile) logfile.write('wmic tasks module Passed\n') except: logfile.write('wmic tasks module Failed\n') try: with open(bname + '-tasks-pslist-tree.txt', 'w') as outfile: subprocess.call(path + 'pslist.exe -t', stdout=outfile) logfile.write('pslist task tree module Passed\n') except: logfile.write('pslist task tree module Failed\n') try: with open(bname + '-tasks-pslist-detailed.txt', 'w') as outfile: subprocess.call(path + 'pslist.exe -x', stdout=outfile) logfile.write('pslist detailed module Passed\n') except: logfile.write('pslist detailed module Failed\n') """ Add post processing """ #sysinternals try: with open(bname + '-whois-loggedon.txt', 'w') as outfile: subprocess.call(path + 'psloggedon.exe', stdout=outfile) logfile.write('loggedon module Passed\n') except: logfile.write('loggedon Module Failed\n') try: with open(bname + '-local-services.txt', 'w') as outfile: subprocess.call(path + 'psservice.exe', stdout=outfile) logfile.write('PSservices List Module Passed\n') except: logfile.write('PSservices List Module Failed\n') try: with open(bname + '-services-config.txt', 'w') as outfile: subprocess.call(path + 'psservice.exe config', stdout=outfile) logfile.write('PSservices detailed Module Passed\n') except: logfile.write('PSservices detailed Module Failed\n') try: with open(sqlname + '-tcpview.csv', 'w') as outfile: subprocess.call(path + 'tcpvcon.exe -a -c -n', stdout=outfile) logfile.write('tcpview csv module Passed\n') except: logfile.write('tcpview csv module Failed\n') try: with open(sqlname + '-system-event-log.csv', 'w') as outfile: subprocess.call(path + 'psloglist.exe -s system', stdout=outfile) logfile.write('System Event Log Module Passed\n') except: logfile.write('System Event Log Module Failed\n') try: with open(sqlname + '-application-event-log.csv', 'w') as outfile: subprocess.call(path + 'psloglist.exe -s application', stdout=outfile) logfile.write('Application Event Log Module Passed\n') except: logfile.write('Application Event Log Module Failed\n') try: with open(sqlname + '-security-event-log.csv', 'w') as outfile: subprocess.call(path + 'psloglist.exe -s security', stdout=outfile) logfile.write('Security Event Log Module Passed\n') except: logfile.write('Security Event Log Module Failed\n') try: with open(sqlname + '-autoruns.csv', 'w') as outfile: subprocess.call(path + 'autorunsc.exe -a -c -m', stdout=outfile) logfile.write('Autoruns Module Passed\n') except: logfile.write('Autoruns Module Failed\n') try: with open(bname + '-open-handles.txt', 'w') as outfile: subprocess.call(path + 'handle.exe -a', stdout=outfile) logfile.write('Open Handles Module Passed\n') except: logfile.write('Open Handles Module Failed\n') try: with open(bname + '-logonsessions.txt', 'w') as outfile: subprocess.call(path + 'logonsessions.exe', stdout=outfile) logfile.write('logonsessions Module Passed\n') except: logfile.write('logonsessions Module Failed\n') try: with open(bname + '-files-opened-remotely.txt', 'w') as outfile: subprocess.call(path + 'psfile.exe', stdout=outfile) logfile.write('remote open files module Passed\n') except: logfile.write('remote open files module Failed\n') try: with open(sqlname + '-installed-apps-patches.csv', 'w') as outfile: subprocess.call(path + 'psinfo.exe', stdout=outfile) logfile.write('Installed Apps/Patches Module Passed\n') except: logfile.write('Installed Apps/Patches Module Failed\n') try: with open(sqlname + '-RAMMAP.csv', 'w') as outfile: subprocess.call(path + 'RAMMap.exe', stdout=outfile) logfile.write('Memory MAP Module Passed\n') except: logfile.write('Memory MAP Module Failed\n') try: with open(sqlname + '-vmmap.csv', 'w') as outfile: subprocess.call(path + 'vmmap.exe', stdout=outfile) logfile.write('vmmap Module Passed\n') except: logfile.write('vmmap Module Failed\n') try: with open(sqlname + '-streams.csv', 'w') as outfile: subprocess.call(path + 'streams.exe', stdout=outfile) logfile.write('Streams Module Passed\n') except: logfile.write('Streams Failed\n') try: with open(sqlname + '-Loadorder.csv', 'w') as outfile: subprocess.call(path + 'LoadOrd.exe', stdout=outfile) logfile.write('LoadOrder Module Passed\n') except: logfile.write('LoadOrder Failed\n') try: with open(sqlname + '-SysMon.csv', 'w') as outfile: subprocess.call(path + 'Sysmon.exe', stdout=outfile) logfile.write('System Monitor Module Passed\n') except: logfile.write('System Monitor Failed\n') try: with open(sqlname + '-ActiveDirectoryInsight.csv', 'w') as outfile: subprocess.call(path + 'ADInsight.exe', stdout=outfile) logfile.write('ActiveDirectory Insight Module Passed\n') except: logfile.write('ActiveDirectory Insight Failed\n') try: with open(sqlname + '-Registry_usage.csv', 'w') as outfile: subprocess.call(path + 'ru.exe', stdout=outfile) logfile.write('Registry usage Module Passed\n') except: logfile.write('Registry usage Failed\n') try: with open(sqlname + '-Diskmonitoring.csv', 'w') as outfile: subprocess.call(path + 'Diskmon.exe', stdout=outfile) logfile.write('Diskmonitoring Module Passed\n') except: logfile.write('Diskmonitoring Failed\n') """ Add post processing """ logfile.close