Package Libs :: Module libregisters
[hide private]
[frames] | no frames]

Source Code for Module Libs.libregisters

  1  #!/usr/bin/env python 
  2   
  3  """ 
  4  (c) Immunity, Inc. 2004-2007 
  5   
  6   
  7  U{Immunity Inc.<http://www.immunityinc.com>} 
  8   
  9   
 10  """ 
 11  # 
 12  __version__ = '1.0' 
 13   
 14  import _winreg 
 15   
 16  # Documentation 
 17  #  http://msdn2.microsoft.com/en-us/library/cc265944.aspx 
 18  #  http://msdn2.microsoft.com/en-us/library/cc265944.aspx 
 19   
 20   
 21  #Systemwide settings ("Registry")       HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\GlobalFlag 
 22  #Program-specific settings ("Image file") for all users of the computer.        HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\ImageFileName\GlobalFlag 
 23  #Program-specific settings ("Image file") for a specified user of the computer.         HKEY_USERS\SID\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\ImageFileName\GlobalFlag 
 24  #Page heap options for an image file for all users of the computer      HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\ImageFileName\PageHeapFlags 
 25  #Page heap options for an image file for a specified user of the computer       HKEY_USERS\SID\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\ImageFileName\PageHeapFlags 
 26  #User mode stack trace database size (tracedb)  HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\ImageFileName\StackTraceDatabaseSizeInMbz 
 27   
 28  GFlagsTags = ['ddp', 'kst', 'ust', 'dic', 'dwl', 'dhc', 'dps', 'dpd', 'dse', 'cse', 'vrf', 'bhd', 'ece', 'd32', 'eel', 'hfc', 'hpc', 'htg', 'htd', 'htc', 'hvc', 'ksl', 'eot', 'hpa', 'ptg', 'scb', 'ltd', 'otl', 'sls', 'soe', 'shg'] 
 29   
 30  GFlagsRef = {} 
 31  GFlagsRef['ddp'] = ('Buffer DbgPrint output', 0x08000000, 'FLG_DISABLE_DBGPRINT', ['Systemwide registry entry', 'kernel mode.'], """Suppresses debugger output from DbgPrint(), DbgPrintEx(), KdPrint(), and KdPrintEx() calls. When this output is suppressed, it does not automatically appear in the kernel debugger. However, it can still be accessed by using the !dbgprint debugger extension. """) 
 32  GFlagsRef['kst'] = ('Create kernel mode stack trace database', 0x2000, 'FLG_KERNEL_STACK_TRACE_DB', ['Systemwide registry entry.'], """Creates a run-time stack trace database of kernel operations, such as resource objects and object management operations. This feature works only when using a "checked build," that is, an internal debugging build of the operating system. """) 
 33  GFlagsRef['ust'] = ('Create user mode stack trace database', 0x1000, 'FLG_USER_STACK_TRACE_DB', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """Creates a run-time stack trace database in the address space of a particular process (image file mode) or all processes (systemwide). """) 
 34  GFlagsRef['dic'] = ('Debug initial command', 0x4, 'FLG_DEBUG_INITIAL_COMMAND', ['Systemwide registry entry', 'kernel mode.'], """Runs Winlogon in the Windows Symbolic Debugger (Ntsd.exe) with the -d parameter, which directs its output to the kernel debugger console. """) 
 35  GFlagsRef['dwl'] = ('Debug Winlogon', 0x04000000, 'FLG_DEBUG_INITIAL_COMMAND_EX', ['Systemwide registry entry', 'kernel mode.'], """Runs Winlogon in the Windows Symbolic Debugger (Ntsd.exe) with the following options: """) 
 36  GFlagsRef['dhc'] = ('Disable heap coalesce on free', 0x00200000, 'FLG_HEAP_DISABLE_COALESCING', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """Leaves adjacent blocks of heap memory separate when they are freed. By default, the system combines ("coalesces") newly freed adjacent blocks into a single block. Combining the blocks takes time, but reduces fragmentation that might force the heap to allocate additional memory when it can't find contiguous memory. """) 
 37  GFlagsRef['dps'] = ('Disable paging of kernel stacks', 0x80000, 'FLG_DISABLE_PAGE_KERNEL_STACKS', ['Systemwide registry entry', 'kernel mode.'], """Prevents paging of the kernel mode stacks of inactive threads. Generally, the kernel mode stack cannot be paged; it is guaranteed to be resident in memory. However, the system occasionally pages the kernel stacks of inactive threads. This flag prevents these occurrences. """) 
 38  GFlagsRef['dpd'] = ('Disable protected DLL verification', 0x80000000, 'FLG_DISABLE_PROTDLLS', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """""") 
 39  GFlagsRef['dse'] = ('Disable stack extension', 0x10000, 'FLG_DISABLE_STACK_EXTENSION', ['image file registry entry.'], """Prevents the kernel from extending the stacks of the threads in the process beyond the initial memory committed. This is used to simulate low memory conditions (where stack extensions fail) and to test the strategic system processes that are expected to run well even with low memory. """) 
 40  GFlagsRef['cse'] = ('Early critical section event creation', 0x10000000, 'FLG_CRITSEC_EVENT_CREATION', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """Creates event handles when a critical section is initialized, rather than waiting until the event is needed. When the system cannot create an event, it generates the exception during initialization and the calls to enter and leave the critical section do not fail. """) 
 41  GFlagsRef['vrf'] = ('Enable application verifier', 0x100, 'FLG_APPLICATION_VERIFIER', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """""") 
 42  GFlagsRef['bhd'] = ('Enable bad handles detection', 0x40000000, 'FLG_ENABLE_HANDLE_EXCEPTIONS', ['Systemwide registry entry', 'kernel mode.'], """Raises a user mode exception (STATUS_INVALID_HANDLE) whenever a user mode process passes an invalid handle to the Object Manager. """) 
 43  GFlagsRef['ece'] = ('Enable close exception', 0x00400000, 'FLG_ENABLE_CLOSE_EXCEPTIONS', ['Systemwide registry entry', 'kernel mode.'], """Raises a user mode exception whenever an invalid handle is passed to the CloseHandle() interface or related interfaces, such as SetEvent(), that take handles as arguments. """) 
 44  GFlagsRef['d32'] = ('Enable debugging of Win32 subsystem', 0x20000, 'FLG_ENABLE_CSRDEBUG', ['Systemwide registry entry', 'kernel mode.'], """""") 
 45  GFlagsRef['eel'] = ('Enable exception logging', 0x00800000, 'FLG_ENABLE_EXCEPTION_LOGGING', ['Systemwide registry entry', 'kernel mode.'], """Creates a log of exception records in the kernel run-time library. You can access the log from the kernel debugger. """) 
 46  GFlagsRef['hfc'] = ('Enable heap free checking', 0x20, 'FLG_HEAP_ENABLE_FREE_CHECK', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """Validates the heap when it is freed. """) 
 47  GFlagsRef['hpc'] = ('Enable heap parameter checking', 0x40, 'FLG_HEAP_VALIDATE_PARAMETERS', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """Verifies some aspects of the heap whenever a heap API is called. """) 
 48  GFlagsRef['htg'] = ('Enable heap tagging', 0x800, 'FLG_HEAP_ENABLE_TAGGING', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """Assigns unique tags to heap allocations. You can display the tag by using the !heap debugger extension with the -t parameter. """) 
 49  GFlagsRef['htd'] = ('Enable heap tagging by DLL', 0x8000, 'FLG_HEAP_ENABLE_TAG_BY_DLL', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """Assigns a unique tag to heap allocations created by the same DLL. You can display the tag by using the !heap debugger extension with the -t parameter. """) 
 50  GFlagsRef['htc'] = ('Enable heap tail checking', 0x10, 'FLG_HEAP_ENABLE_TAIL_CHECK', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """Checks for buffer overruns when the heap is freed. This flag adds a short pattern to the end of each allocation. The Windows heap manager detects the pattern when the block is freed and, if the block was modified, the heap manager breaks into the debugger. """) 
 51  GFlagsRef['hvc'] = ('Enable heap validation on call', 0x80, 'FLG_HEAP_VALIDATE_ALL', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """Validates the entire heap each time a heap API is called. """) 
 52  GFlagsRef['ksl'] = ('Enable loading of kernel debugger symbols', 0x40000, 'FLG_ENABLE_KDEBUG_SYMBOL_LOAD', ['Systemwide registry entry', 'kernel mode.'], """Loads kernel symbols into the kernel memory space the next time the system starts. The kernel symbols are used in kernel profiling and by advanced kernel debugging tools. """) 
 53  GFlagsRef['eot'] = ('Enable object handle type tagging', 0x01000000, 'FLG_ENABLE_HANDLE_TYPE_TAGGING', ['Systemwide registry entry', 'kernel mode.'], """This flag appears in Gflags, but it has no effect on the operating system. """) 
 54  GFlagsRef['hpa'] = ('Enable page heap', 0x02000000, 'FLG_HEAP_PAGE_ALLOCS', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """Turns on page heap debugging, which verifies dynamic heap memory operations, including allocations and frees, and causes a debugger break when it detects a heap error. """) 
 55  GFlagsRef['ptg'] = ('Enable pool tagging', 0x400, 'FLG_POOL_ENABLE_TAGGING', ['Systemwide registry entry.'], """Collects data and calculates statistics about pool memory allocations. The data is grouped by pool tag value. Several tools that diagnose memory leaks and other kernel pool errors use the resulting data. """) 
 56  GFlagsRef['scb'] = ('Enable system critical breaks', 0x100000, 'FLG_ENABLE_SYSTEM_CRIT_BREAKS', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """For per-process (image file) only: Forces a system breakpoint into the debugger whenever the specified process stops abnormally. This flag is effective only when the process calls the RtlSetProcessBreakOnExit() and RtlSetThreadBreakOnExit() interfaces. """) 
 57  GFlagsRef['ltd'] = ('Load DLLs top-down', 0x20000000, 'FLG_LDR_TOP_DOWN', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """Loads DLLs at the highest possible address. This flag is used to test 64-bit code for pointer truncation errors, because the most significant 32 bits of the pointers are not zeroes. It is designed for code running on the 64-bit versions of the Windows Server 2003. """) 
 58  GFlagsRef['otl'] = ('Maintain a list of objects for each type', 0x4000, 'FLG_MAINTAIN_OBJECT_TYPELIST', ['Systemwide registry entry', 'kernel mode.'], """Collects and maintains a list of active objects by object type (for example, event, mutex, and semaphore). """) 
 59  GFlagsRef['sls'] = ('Show loader snaps', 0x2, 'FLG_SHOW_LDR_SNAPS', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """Captures detailed information about the loading and unloading of executable images and their supporting library modules. """) 
 60  GFlagsRef['soe'] = ('Stop on exception', 0x1, 'FLG_STOP_ON_EXCEPTION', ['Systemwide registry entry', 'kernel mode', 'image file registry entry.'], """The kernel breaks into the kernel debugger whenever a kernel mode exception occurs. The system passes all first chance exceptions (except for STATUS_PORT_DISCONNECT) with a severity of Warning or Error to the debugger before passing them to a local exception handler. """) 
 61  GFlagsRef['shg'] = ('Stop on hung GUI', 0x8, 'FLG_STOP_ON_HUNG_GUI', ['kernel mode'], """""") 
 62   
 63   
 64  # For a complete usage of this Class, check the Pycommand 'gflags.py' 
65 -class GFlags:
66 - def __init__(self, processname = ""):
67 """ 68 GFlags class enable and disable Windows global flags 69 70 @type processname: STRING 71 @param processname: (Optional) Process name (If is unset, it will use the system global flags) 72 """ 73 self.processname = processname 74 75 if self.processname: 76 self.subkey = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\%s" % self.processname 77 else: 78 self.subkey = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\"
79 80
81 - def _query(self):
82 try: 83 hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.subkey) 84 except WindowsError: 85 raise Exception, "Cannot Openkey for Query (%s)" % self.subkey 86 87 try: 88 return _winreg.QueryValueEx(hkey, "GlobalFlag")[0] 89 except WindowsError: 90 raise Exception, "Cannot Query value (%s\\%s)" % (self.subkey, "GlobalFlag")
91
92 - def GetReferencebyName(self, val):
93 """ 94 Get Flag information by its shorcut name 95 96 @type val: STRING 97 @param val: Shortcut Name 98 99 @rtype: TUPLE 100 @return: A tuple containning all the internal information of a Flag 101 """ 102 val = val.lower() 103 try: 104 r = GFlagsRef[val] 105 except KeyError: 106 raise Exception, "'%s' is not a gflag value" % val 107 if self.processname: 108 if 'image file registry entry.' not in r[3]: 109 raise Exception, "Flag '%s' is not available for Image file (only for: %s)" % (val, str(r[3])) 110 111 return r
112
113 - def SetbyName(self, val):
114 """ 115 Set a Flag by its shorcut name 116 117 @type val: STRING 118 @param val: Shortcut Name 119 """ 120 r = self.GetReferencebyName( val ) 121 return self.Set( r[1] )
122
123 - def Set(self, val):
124 """ 125 Set a Flag 126 127 @type val: DWORD 128 @param val: Value of the flag to set 129 """ 130 131 try: 132 current = self._query() 133 except Exception: 134 # Key is not created, set will automatically do it 135 current = 0L 136 137 self._set( current | val ) 138 139 return current | val
140
141 - def UnSetbyName(self, val):
142 """ 143 Unset a Flag by its shorcut name 144 145 @type val: STRING 146 @param val: Shortcut Name 147 """ 148 r = self.GetReferencebyName( val ) 149 return self.UnSet( r[1] )
150
151 - def UnSet(self, val):
152 """ 153 Set a Flag 154 155 @type val: DWORD 156 @param val: Value of the flag to set 157 """ 158 159 current = self._query() 160 self._set( current &~ val ) 161 162 return current &~ val
163
164 - def isSet(self, val):
165 """ 166 Whether a Flag is set 167 168 @type val: STRING 169 @param val: Shortcut name 170 """ 171 172 r = self.GetReferencebyName( val ) 173 current = self._query() 174 175 return bool( r[1] & current )
176
177 - def Print(self):
178 """ 179 Print all the current setted GFlags 180 181 @rtype: LIST OF TUPLES 182 @return: A list of a tuple with two elements: Shortcut Name and flag information 183 """ 184 current = self._query() 185 ret = [] 186 for a in GFlagsRef.keys(): 187 r = GFlagsRef[a] 188 if r[1] & current: 189 ret.append ( (a, r) ) 190 return ret
191
192 - def Clear(self):
193 """ 194 Clear the Flags 195 """ 196 if self.processname: 197 _winreg.DeleteKey(_winreg.HKEY_LOCAL_MACHINE, self.subkey) 198 else: 199 self._set( 0 )
200
201 - def _set(self, flag):
202 try: 203 hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.subkey, 0, _winreg.KEY_SET_VALUE ) 204 except WindowsError: 205 try: 206 hkey = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, self.subkey) 207 except WindowsError: 208 raise Exception, "Cannot Open/Create key (%s)" % self.subkey 209 210 try: 211 _winreg.SetValueEx(hkey, "GlobalFlag", 0, _winreg.REG_DWORD, int(flag) ) 212 except WindowsError: 213 raise Exception, "Cannot SetValue key (%s\\%s)" % ( self.subkey, "GlobalFlag") 214 except ValueError: 215 raise Exception, "Cannot SetValue key (%s\\%s) %s %s" % ( self.subkey, "GlobalFlag", str(flag), type(flag)) 216 217 try: 218 _winreg.CloseKey(hkey) 219 except WindowsError: 220 raise Exception, "Cannot Close key (%s)" % self.subkey
221 222 if __name__ == "__main__": 223 g = GFlags("notepad.exe") 224 g.Set( 'htc' ) 225 g.Clear() 226