[or-cvs] r15658: Code for dumping modified registry contents (in torbrowser/trunk/src: . FindTraces)

sjm217 at seul.org sjm217 at seul.org
Fri Jul 4 21:38:26 UTC 2008


Author: sjm217
Date: 2008-07-04 17:38:25 -0400 (Fri, 04 Jul 2008)
New Revision: 15658

Added:
   torbrowser/trunk/src/FindTraces/
   torbrowser/trunk/src/FindTraces/dumpreg.py
   torbrowser/trunk/src/FindTraces/registrydict.py
Log:
Code for dumping modified registry contents

Added: torbrowser/trunk/src/FindTraces/dumpreg.py
===================================================================
--- torbrowser/trunk/src/FindTraces/dumpreg.py	                        (rev 0)
+++ torbrowser/trunk/src/FindTraces/dumpreg.py	2008-07-04 21:38:25 UTC (rev 15658)
@@ -0,0 +1,78 @@
+###
+### Extract list of registry keys created from a Process Monitor CSV log and
+### dump values. The result can be compared using diff to see if the keys
+### have actually been created or changed.
+### Process Monitor can be downloaded from http://technet.microsoft.com/en-us/sysinternals/
+###
+### Copyright 2007 Steven J. Murdoch <http://www.cl.cam.ac.uk/users/sjm217/>
+### See LICENSE for licensing information
+###
+### $Id$
+###
+
+import win32con
+from registrydict import RegistryDict
+import csv
+import sys
+
+def parse_key(key):
+	'''Take a registry path, in ProcessMonitor format and split.
+	Returns (top, rest) where top is the appropriate win32con HKEY_* variable
+	and rest is a list of path components'''
+	
+	## Separate into components
+	path = key.split("\\")
+	
+	## Split into first element, and the rest
+	top = path[0]
+	rest = path[1:]
+	
+	## The Windows API expects an integer for the first path component,
+	## so convert it
+	if top=='HKLM':
+		top = win32con.HKEY_LOCAL_MACHINE
+	elif top=='HKCU':
+		top = win32con.HKEY_CURRENT_USER
+	elif top=='HKCR':
+		top = win32con.HKEY_CLASSES_ROOT
+	elif top=='HKU':
+		top = win32con.HKEY_USERS
+	else:
+		raise Exception("Unknown top-level registry key", top)
+	
+	return top, rest
+
+def main():
+	## Check usage
+	if len(sys.argv) != 3:
+		print "Usage: dumpreg.py LOGFILE OUTFILE"
+		sys.exit()
+	
+	## Open input and output files
+	ifn = sys.argv[1]
+	ofn = sys.argv[2]
+	
+	logfile = csv.reader(file(ifn, "rb"))
+	fh=file(ofn, "w")
+		
+	## Skip header
+	logfile.next()
+
+	for row in logfile:
+		## Parse the line
+		seq, time, proc, pid, op, key, result, detail = row
+		## We only handle RegCreateKey operations
+		assert(op=='RegCreateKey')
+		## Parse the registry key
+		handle, path = parse_key(key)
+		try:
+			## Get the contents
+			r = RegistryDict(handle, path, win32con.KEY_READ)
+			## Key exists
+			fh.write(str((1, key, proc, r))+"\n")
+		except:
+			## Key doesn't exist
+			fh.write(str((2, key, proc, None))+"\n")
+			
+if __name__=="__main__":
+	main()


Property changes on: torbrowser/trunk/src/FindTraces/dumpreg.py
___________________________________________________________________
Name: svn:keywords
   + id

Added: torbrowser/trunk/src/FindTraces/registrydict.py
===================================================================
--- torbrowser/trunk/src/FindTraces/registrydict.py	                        (rev 0)
+++ torbrowser/trunk/src/FindTraces/registrydict.py	2008-07-04 21:38:25 UTC (rev 15658)
@@ -0,0 +1,232 @@
+### Title: Treat the Win32 Registry like a Python dict -- updated
+### Submitter: Don Dwiggins
+### Last Updated: 2008/03/11
+### Version no: 1.0
+### URL: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/551761
+### $Id$
+###
+### Requires pywin32 (http://python.net/crew/mhammond/win32/Downloads.html)
+
+# From the recipe at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/174627
+# Corrections and additions have been made
+
+"""Slightly magical Win32api Registry -> Dictionary-like-object wrapper"""
+import win32api, win32con, cPickle
+
+class RegistryDict(object):
+    def __init__(self, keyhandle = win32con.HKEY_LOCAL_MACHINE, keypath = [], flags = None):
+        """If flags=None, then it will create the key.. otherwise pass a win32con.KEY_* sam"""
+        self.keyhandle = None
+        self.open(keyhandle, keypath, flags)
+
+    @staticmethod
+    def massageIncomingRegistryValue((obj, objtype)):
+        if objtype == win32con.REG_BINARY and obj[:8]=='PyPickle':
+            obj = obj[8:]
+            return cPickle.loads(obj)
+        elif objtype == win32con.REG_NONE:
+            return None
+        elif objtype in (win32con.REG_SZ, win32con.REG_EXPAND_SZ,
+                         win32con.REG_RESOURCE_LIST, win32con.REG_LINK,
+                         win32con.REG_BINARY, win32con.REG_DWORD,
+                         win32con.REG_DWORD_LITTLE_ENDIAN, win32con.REG_DWORD_BIG_ENDIAN,
+                         win32con.REG_MULTI_SZ):
+            return obj
+        raise NotImplementedError, "Registry type 0x%08X not supported" % (objtype,)
+
+    def __getitem__(self, key):
+        # is it data?
+        try:
+            return self.massageIncomingRegistryValue(win32api.RegQueryValueEx(self.keyhandle, key))
+        except:
+            if key == '':
+                # Special case: this dictionary key means "default value"
+                raise KeyError, key
+            pass
+        # it's probably a registry key then
+        try:
+            return RegistryDict(self.keyhandle, key, win32con.KEY_ALL_ACCESS)
+        except:
+            pass
+        # must not be there
+        raise KeyError, key
+    
+    def has_key(self, key):
+        return self.__contains__(key)
+    
+    def __contains__(self, key):
+        try:
+            self.__getitem__(key)
+            return 1
+        except KeyError:
+            return 0
+
+    def copy(self):
+        return dict(self.iteritems())
+
+    def __repr__(self):
+        return repr(self.copy())
+
+    def __str__(self):
+        return self.__repr__()
+
+    def __cmp__(self, other):
+        # Do the objects have the same state?
+        return self.keyhandle == other.keyhandle
+
+    def __hash__(self):
+        raise TypeError, "RegistryDict objects are unhashable"
+  
+    def clear(self):
+        keylist = list(self.iterkeys())
+        # Two-step to avoid changing the set while iterating over it
+        for k in keylist:
+            del self[k]
+    
+    def iteritems_data(self):
+        i = 0
+        # yield data
+        try:
+            while 1:
+                s, obj, objtype = win32api.RegEnumValue(self.keyhandle, i)
+                yield s, self.massageIncomingRegistryValue((obj, objtype))
+                i += 1
+        except:
+            pass
+
+    def iteritems_children(self, access=win32con.KEY_ALL_ACCESS):
+        i = 0
+        try:
+            while 1:
+                s = win32api.RegEnumKey(self.keyhandle, i)
+                yield s, RegistryDict(self.keyhandle, [s], access)
+                i += 1
+        except:
+            pass
+                
+    def iteritems(self, access=win32con.KEY_ALL_ACCESS):
+       # yield children
+        for item in self.iteritems_data():
+            yield item
+        for item in self.iteritems_children(access):
+            yield item
+            
+    def iterkeys_data(self):
+        for key, value in self.iteritems_data():
+            yield key
+
+    def iterkeys_children(self, access=win32con.KEY_ALL_ACCESS):
+        for key, value in self.iteritems_children(access):
+            yield key
+
+    def iterkeys(self):
+        for key, value in self.iteritems():
+            yield key
+
+    def itervalues_data(self):
+        for key, value in self.iteritems_data():
+            yield value
+
+    def itervalues_children(self, access=win32con.KEY_ALL_ACCESS):
+        for key, value in self.iteritems_children(access):
+            yield value
+
+    def itervalues(self, access=win32con.KEY_ALL_ACCESS):
+        for key, value in self.iteritems(access):
+            yield value
+
+    def items(self, access=win32con.KEY_ALL_ACCESS):
+        return list(self.iteritems())
+              
+    def keys(self):
+        return list(self.iterkeys())
+
+    def values(self, access=win32con.KEY_ALL_ACCESS):
+        return list(self.itervalues(access))
+        
+    def __delitem__(self, key):
+        # Delete a string value or a subkey, depending on the type
+        try:
+            item = self[key]
+        except:
+            return  # Silently ignore bad keys
+        itemtype = type(item)
+        if itemtype is str:
+            win32api.RegDeleteValue(self.keyhandle, key)
+        elif isinstance(item, RegistryDict):
+            # Delete everything in the subkey, then the subkey itself
+            item.clear()
+            win32api.RegDeleteKey(self.keyhandle, key)
+        else:
+            raise ValueError, "Unknown item type in RegistryDict"
+  
+    def __len__(self):
+        return len(self.items())
+
+    def __iter__(self):
+        return self.iterkeys()
+  
+    def popitem(self):
+        try:
+            k, v = self.iteritems().next()
+            del self[k]
+            return k, v
+        except StopIteration:
+            raise KeyError, "RegistryDict is empty"
+            
+    def get(self,key,default=None):
+        try:
+            return self.__getitem__(key)
+        except:
+            return default
+
+    def setdefault(self,key,default=None):
+        try:
+            return self.__getitem__(key)
+        except:
+            self.__setitem__(key)
+            return default
+
+    def update(self,d):
+        for k,v in d.items():
+            self.__setitem__(k, v)
+
+    def __setitem__(self, item, value):
+        item = str(item)
+        pyvalue = type(value)
+        if pyvalue is dict or isinstance(value, RegistryDict):
+            d = RegistryDict(self.keyhandle, item)
+            d.clear()
+            d.update(value)
+            return
+        if pyvalue is str:
+            valuetype = win32con.REG_SZ
+        elif pyvalue is int:
+            valuetype = win32con.REG_DWORD
+        else:
+            valuetype = win32con.REG_BINARY
+            value = 'PyPickle' + cPickle.dumps(value)
+        win32api.RegSetValueEx(self.keyhandle, item, 0, valuetype, value)
+  
+    def open(self, keyhandle, keypath, flags = None):
+        if self.keyhandle:
+            self.close()
+        if type(keypath) is str:
+            keypath = keypath.split('\\')
+        if flags is None:
+            for subkey in keypath:
+                keyhandle = win32api.RegCreateKey(keyhandle, subkey)
+        else:
+            for subkey in keypath:
+                keyhandle = win32api.RegOpenKeyEx(keyhandle, subkey, 0, flags)
+        self.keyhandle = keyhandle
+
+    def close(self):
+        try:
+            win32api.RegCloseKey(self.keyhandle)
+        except:
+            pass
+
+    def __del__(self):
+        self.close()
+


Property changes on: torbrowser/trunk/src/FindTraces/registrydict.py
___________________________________________________________________
Name: svn:keywords
   + id



More information about the tor-commits mailing list