def indexedFiles(): summary = printSubheader("INDEXED FILES") pattern = [ r"%secret%", r"%creds%", r"%credential%", r"%.vmdk", r"%confidential%", r"%proprietary%", r"%pass%", r"%credentials%", r"web.config", r"KeePass.config%", r"%.kdbx", r"%.key", r"tnsnames.ora", r"ntds.dit", r"%.dll.config", r"%.exe.config" ] con = Activator.CreateInstance(Type.GetTypeFromProgID("ADODB.Connection")) rs = Activator.CreateInstance(Type.GetTypeFromProgID("ADODB.Recordset")) try: con.Open( "Provider=Search.CollatorDSO;Extended Properties='Application=Windows';" ) except: print summary + "Indexed file search provider not available\n" for p in pattern: try: rs.Open( "SELECT System.ItemPathDisplay FROM SYSTEMINDEX WHERE System.FileName LIKE '" + p + "' ", con) while not rs.EOF: summary += rs.Fields.Item("System.ItemPathDisplay").Value rs.MoveNext() except EnvironmentError: pass print summary
def test__1_registered_nopia(): # Check to see that namespace 'spwLib' isn't accessible Assert('spwLib' not in dir(), "spwLib is already registered") run_register_com_component(scriptpw_path) pwcType = Type.GetTypeFromProgID('ScriptPW.Password.1') pwcInst = Activator.CreateInstance(pwcType) AreEqual('System.__ComObject', pwcInst.ToString()) try: del pwcInst.GetPassword except AttributeError: pass else: Fail("'__ComObject' object has no attribute 'GetPassword'") _test_common_on_object(pwcInst) # looks like: "<System.__ComObject (TypeInfo : IPassword)>" types = ['__ComObject', 'IPassword'] for x in types: Assert(x in repr(pwcInst), x + " not in repr(pwcInst)")
def test_load_typelib(): for x in [ dlrcomlib_guid, Activator.CreateInstance( Type.GetTypeFromProgID("DlrComLibrary.ParamsInRetval")) ]: lib = clr.LoadTypeLibrary(x) #ComTypeLibInfo Members AreEqual(lib.Guid, dlrcomlib_guid) AreEqual(lib.Name, "DlrComLibraryLib") AreEqual(lib.VersionMajor, 1) AreEqual(lib.VersionMinor, 0) Assert("DlrComLibraryLib" in dir(lib)) #ComTypeLibDesc Members dlrComLib = lib.DlrComLibraryLib Assert("DlrComServer" in dir(lib.DlrComLibraryLib)) Assert("IDlrComServer" not in dir(lib.DlrComLibraryLib)) #ComTypeClassDesc Members dlrComServer = lib.DlrComLibraryLib.DlrComServer AreEqual(dlrComServer.TypeLib, lib.DlrComLibraryLib) AreEqual(dlrComServer.TypeName, "DlrComServer") AreEqual(str(dlrComServer.Kind), "Class") #Create an instance of the class and access members. obj = dlrComServer.CreateInstance() Assert("__ComObject" in str(obj.__class__)) AreEqual(12345, obj.SumArgs(1, 2, 3, 4, 5)) #Complete the circle back to the lib AreEqual(clr.LoadTypeLibrary(obj).Guid, lib.Guid)
def test_import_typelib(): for x in [ dlrcomlib_guid, Activator.CreateInstance( Type.GetTypeFromProgID("DlrComLibrary.ParamsInRetval")) ]: clr.AddReferenceToTypeLibrary(x) try: DlrComLibrary.__class__ except NameError: pass else: Fail("Namespace already exists") import DlrComLibraryLib from DlrComLibraryLib import DlrComServer Assert("DlrComServer" in dir(DlrComLibraryLib)) #Create an instance of the class and access members. obj = DlrComServer.CreateInstance() Assert("__ComObject" in str(obj.__class__)) AreEqual(12345, obj.SumArgs(1, 2, 3, 4, 5)) del DlrComServer del DlrComLibraryLib
def kill_excel_processes(cls, times=10): print('ExcelFileReader| Killing excel 10 times...') oShell = Activator.CreateInstance( Type.GetTypeFromProgID("WScript.Shell")) for _ in range(10): oShell.Run("taskkill /im EXCEL.EXE", 0, True) print('ExcelFileReader| Done killing...')
def browserEnum(): summary = printHeader("BROWSER ENUM") regex = Regex('(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?') #Active IE Urls summary += printSubheader("ACTIVE EXPLORER URLS") app = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application")) summary += "\n".join([w.LocationUrl() for w in app.Windows()]) #Chrome History summary += printSubheader("\n\nChrome History") try: cHistPath = "{0}\Users\{1}\AppData\Local\Google\Chrome\User Data\Default\History".format(Env.GetEnvironmentVariable("systemdrive"), Env.UserName) cHist = open(cHistPath, "r").read() summary += "\n".join(["[*] {0}\n".format(m.Value) for m in regex.Matches(cHist)][-10:]) except: pass summary += printSubheader("\nChrome Bookmarks") #Chrome Bookmarks try: cBMPath = "{0}\Users\{1}\AppData\Local\Google\Chrome\User Data\Default\Bookmarks".format(Env.GetEnvironmentVariable("systemdrive"), Env.UserName) js = JavaScriptSerializer() cBM = js.DeserializeObject(open(cBMPath, "r").read()) urls = cBM["roots"]["bookmark_bar"]["children"] for url in urls: u = url['url'] d = url['name'] summary += "[*] {0}\n{1}\n\n".format(d, u) except: pass summary += printSubheader("Firefox History") #Firefox History try: regex = Regex('(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?') fHistPath = "{0}\Users\{1}\AppData\Roaming\Mozilla\Firefox\Profiles".format(Env.GetEnvironmentVariable("systemdrive"), Env.UserName) for path in DirectoryInfo(fHistPath).EnumerateDirectories("*.default"): places = open(path.FullName + "\places.sqlite", "r").read() summary += "\n".join(["[*] {0}\n".format(m.Value) for m in regex.Matches(places)][:10]) except: pass summary += printSubheader("IE History") typedUrlPath = "\Software\Microsoft\Internet Explorer\TypedURLs" for sid in Registry.Users.GetSubKeyNames(): if sid != ".DEFAULT" and not sid.endswith("Classes"): try: typedUrlsKey = Registry.Users.OpenSubKey(sid + typedUrlPath) if typedUrlsKey != None: summary += "[{0}][{1}]\n".format(sid, SecurityIdentifier(sid.ToString()).Translate(NTAccount)) for value in typedUrlsKey.GetValueNames(): summary += "\t{0}\n".format(typedUrlsKey.GetValue(value)) summary += "\n" except SystemError: pass return summary
def makemdb(testfolder, mdb_name): # following setup code borrowed from pywin32 odbc test suite # kindly contributed by Frank Millman. import os _accessdatasource = os.path.join(testfolder, mdb_name) if os.path.isfile(_accessdatasource): print("using JET database=", _accessdatasource) else: try: from win32com.client.gencache import EnsureDispatch from win32com.client import constants win32 = True except ImportError: # perhaps we are running IronPython win32 = False # iron Python try: from System import Activator, Type except: pass # Create a brand-new database - what is the story with these? dbe = None for suffix in (".36", ".35", ".30"): try: if win32: dbe = EnsureDispatch("DAO.DBEngine" + suffix) else: type = Type.GetTypeFromProgID("DAO.DBEngine" + suffix) dbe = Activator.CreateInstance(type) break except: pass if dbe: print(" ...Creating ACCESS db at " + _accessdatasource) if win32: workspace = dbe.Workspaces(0) newdb = workspace.CreateDatabase( _accessdatasource, constants.dbLangGeneral, constants.dbVersion40 ) else: newdb = dbe.CreateDatabase( _accessdatasource, ";LANGID=0x0409;CP=1252;COUNTRY=0" ) newdb.Close() else: print(" ...copying test ACCESS db to " + _accessdatasource) mdbName = os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "examples", "test.mdb") ) import shutil shutil.copy(mdbName, _accessdatasource) return _accessdatasource
def test__2_unregistered_nopia(): # Check to see that namespace 'spwLib' isn't accessible Assert('spwLib' not in dir(), "spwLib is already registered") run_unregister_com_component(scriptpw_path) pwcType = Type.GetTypeFromProgID('ScriptPW.Password.1') AreEqual(pwcType, None) # Registration-free COM activation import IronPythonTest password = IronPythonTest.ScriptPW.CreatePassword() AreEqual('System.__ComObject', password.ToString())
def makemdb(testfolder): # following setup code borrowed from pywin32 odbc test suite # kindly contributed by Frank Millman. import tempfile import os _accessdatasource = tempfile.mktemp(suffix='.mdb', prefix='ado_test_', dir=testfolder) if os.path.isfile(_accessdatasource): os.unlink(_accessdatasource) try: from win32com.client.gencache import EnsureDispatch from win32com.client import constants win32 = True except ImportError: #perhaps we are running IronPython win32 = False #iron Python from System import Activator, Type # Create a brand-new database - what is the story with these? dbe = None for suffix in (".36", ".35", ".30"): try: if win32: dbe = EnsureDispatch("DAO.DBEngine" + suffix) else: type = Type.GetTypeFromProgID("DAO.DBEngine" + suffix) dbe = Activator.CreateInstance(type) break except: pass if dbe: print((' ...Creating ACCESS db at ' + _accessdatasource)) if win32: workspace = dbe.Workspaces(0) newdb = workspace.CreateDatabase(_accessdatasource, constants.dbLangGeneral, constants.dbEncrypt) else: newdb = dbe.CreateDatabase(_accessdatasource, ';LANGID=0x0409;CP=1252;COUNTRY=0') newdb.Close() else: print((' ...copying test ACCESS db to ' + _accessdatasource)) mdbName = os.path.normpath(os.getcwd() + '/../examples/test.mdb') import shutil shutil.copy(mdbName, _accessdatasource) return _accessdatasource
def get_type(local_assembly, type_name): """Gets the type's class via reflection The type is looked for in the local assembly first, if not found, it will be looked in the system assembly. :param Assembly local_assembly: Assembly object to look for. :param str type_name: The full name of the type. :return: A C# Type object. :rtype: Type """ local_type = local_assembly.GetType(type_name) if local_type is None: return Type.GetType(type_name) return local_type
def listaddins(): pptType = "PowerPoint.Application" from System import Type, Activator tppt = Type.GetTypeFromProgID(pptType) pptApp = Activator.CreateInstance(tppt) ComAddins = pptApp.COMAddIns for i in range(1, ComAddins.Count + 1): ComAddin = pptApp.COMAddIns(i) print("Addin Status for Addin {0}".format(ComAddin.Guid)) for attr in ["Description", "Guid", "ProgId"]: try: print "\t" + attr + "=" + getattr(ComAddin, attr) except: pass if (ComAddin.ProgId == "Slides.Addin"): if (ComAddin.Connect != 0): print "slides addin connected"
def __init__(self, fileName): scriptEnv = Python.CreateRuntime() self.fileName = fileName self.engine = scriptEnv.GetEngine("python") self.context = HostingHelpers.GetLanguageContext(self.engine) scriptEnv.LoadAssembly(Type.GetType("System.String").Assembly) #mscorlib.dll scriptEnv.LoadAssembly(UriBuilder().GetType().Assembly) #System.dll self.InitializePath() executable = Assembly.GetEntryAssembly().Location prefix = Path.GetDirectoryName(executable) self.context.SystemState.executable = executable self.context.SystemState.exec_prefix = self.context.SystemState.prefix = prefix import imp mod = imp.new_module('__main__') mod.__file__ = fileName mod.__builtins__ = sys.modules['__builtin__'] self.context.SystemState.modules['__main__'] = mod self.mainScope = scriptEnv.CreateScope(mod.__dict__)
def get_accepted_property_types(self): #Geo.Vector2.__clrtype__() return [Type.GetType("System.Single")]
def getTypeFromProgID(prog_id): ''' Returns the Type object for prog_id. ''' return Type.GetTypeFromProgID(prog_id)
def get_clr_dir(): import clr from System import Type from System.IO import Path return Path.GetDirectoryName( Type.GetType('System.Int32').Assembly.Location)
win32 = True except ImportError: #perhaps we are running IronPython win32 = False if not win32: #iron Python from System import Activator, Type _accessdatasource = os.path.join(tempfile.gettempdir(), "test_odbc.mdb") if os.path.isfile(_accessdatasource): os.unlink(_accessdatasource) # Create a brand-new database - what is the story with these? for suffix in (".36", ".35", ".30"): try: if win32: dbe = EnsureDispatch("DAO.DBEngine" + suffix) else: type = Type.GetTypeFromProgID("DAO.DBEngine" + suffix) dbe = Activator.CreateInstance(type) break except: pass else: raise RuntimeError("Can't find a DB engine") print ' ...Creating ACCESS db at', _accessdatasource if win32: workspace = dbe.Workspaces(0) newdb = workspace.CreateDatabase(_accessdatasource, constants.dbLangGeneral, constants.dbEncrypt) else: newdb = dbe.CreateDatabase(_accessdatasource, ';LANGID=0x0409;CP=1252;COUNTRY=0')
def sendGameCommandShell(inputString): shell = Activator.CreateInstance(Type.GetTypeFromProgID("WScript.Shell")) shell.SendKeys(inputString) return
def Dispatch(dispatch): type = Type.GetTypeFromProgID(dispatch) return Activator.CreateInstance(type)
def __init__(self, obj): self.obj = obj self.type = Type.MakeByRefType(obj.type) self.value = obj.value
# [email protected]. By using this source code in any fashion, you are agreeing to be bound # by the terms of the Apache License, Version 2.0. # # You must not remove this notice, or any other, from this software. # # ##################################################################################### ''' For the time being this is a minimal sanity check designed to ensure IP can access COM servers implemented in pywin32. ''' import sys from interop.com.compat.hw import hw_progid, hw_retval from iptest.cominterop_util import * if sys.platform == "cli": from System import Type, Activator type = Type.GetTypeFromProgID(hw_progid) com_obj = Activator.CreateInstance(type) else: import win32com.client com_obj = win32com.client.Dispatch(hw_progid) print "dir(obj):", dir(com_obj) print print "comMethod():", com_obj.comMethod(None) AreEqual(com_obj.comMethod(None), hw_retval)
def get_clr_type(obj): full_name = obj.__module__ + "." + obj.__name__ + ", GameHook" return Type.GetType(full_name)