def unload(self, sid): try: # Unload user reg win32api.RegUnLoadKey(win32con.HKEY_USERS, sid) win32api.RegUnLoadKey(win32con.HKEY_USERS, sid + '_Classes') except Exception, e: Logger.warn("Unable to unload user reg: %s" % (str(e))) return False
def unload(self, sid): try: # Unload user reg win32api.RegUnLoadKey(win32con.HKEY_USERS, sid) win32api.RegUnLoadKey(win32con.HKEY_USERS, sid + '_Classes') except Exception: Logger.exception("Unable to unload user reg") return False return True
def testMe(): import os directory = r"C:\Documents and Settings\tt" registryFile = os.path.join(directory, "NTUSER.DAT") # Get some privileges to load the hive priv_flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY hToken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), priv_flags) backup_privilege_id = win32security.LookupPrivilegeValue( None, "SeBackupPrivilege") restore_privilege_id = win32security.LookupPrivilegeValue( None, "SeRestorePrivilege") win32security.AdjustTokenPrivileges( hToken, 0, [(backup_privilege_id, win32security.SE_PRIVILEGE_ENABLED), (restore_privilege_id, win32security.SE_PRIVILEGE_ENABLED)]) hiveName = "testme" # Load the hive win32api.RegLoadKey(win32con.HKEY_USERS, hiveName, registryFile) disableActiveSetup(hiveName) win32api.RegUnLoadKey(win32con.HKEY_USERS, hiveName)
# Overwrite Active Setup: works partially try: Reg.UpdateActiveSetup(self.user.name, hiveName, r"Software\Microsoft\Active Setup") # On 64 bits architecture, Active Setup is already present in path "Software\Wow6432Node\Microsoft\Active Setup" if "PROGRAMW6432" in os.environ.keys(): Reg.UpdateActiveSetup( self.user.name, hiveName, r"Software\Wow6432Node\Microsoft\Active Setup") except Exception, err: Logger.warn("Unable to reset ActiveSetup") Logger.debug("Unable to reset ActiveSetup: " + str(err)) if self.profile is not None: self.profile.overrideRegistry(hiveName, self.user.name) self.domain.doCustomizeRegistry(hiveName) # Timezone override if self.parameters.has_key("timezone"): tz_name = Langs.getWinTimezone(self.parameters["timezone"]) ret = Reg.setTimezone(hiveName, tz_name) if ret is False: Logger.warn("Unable to set TimeZone (%s, %s)" % (self.parameters["timezone"], tz_name)) # Unload the hive win32api.RegUnLoadKey(win32con.HKEY_USERS, hiveName)
def copySessionStart(self): d = shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_APPDATA, 0, 0) profile_tmp_dir = os.path.join(d, "ulteo", "profile", self.session.user.name) profile_tmp_dir = System.local_encode(profile_tmp_dir) profile_filter = System.local_encode(Config.profile_filters_filename) for f in [self.DesktopDir, self.DocumentsDir]: d = os.path.join(self.mountPoint, "Data", f) trial = 5 while not os.path.exists(d): try: os.makedirs(d) except OSError: trial -= 1 if trial == 0: Logger.exception("Failed to create directory %s" % d) return False time.sleep(random.randint(1, 10) / 100.0) Logger.debug2( "Profile mkdir failed (concurrent access because of more than one ApS)" ) continue d = os.path.join(self.mountPoint, "conf.Windows.%s" % System.getWindowsVersionName()) if os.path.exists(d): # clean temporary file used by windows to load registry dirs = None try: dirs = os.listdir(d) except Exception: Logger.exception("Unable to list content of the directory %s" % d) return for content in dirs: if content.startswith(r"NTUSER.DAT.LOG") or content.startswith( r"NTUSER.DAT{"): try: path = os.path.join(d, content) os.remove(path) except Exception: Logger.exception("Unable to delete %s" % path) # Copy user registry src = os.path.join(d, "NTUSER.DAT") if os.path.exists(src): dst = os.path.join(self.session.windowsProfileDir, "NTUSER.DAT") rand = random.randrange(10000, 50000) hiveName_src = "OVD_%s_%d" % (str(self.session.id), rand) win32api.RegLoadKey(win32con.HKEY_USERS, hiveName_src, src) hiveName_dst = "OVD_%s_%d" % (str(self.session.id), rand + 1) win32api.RegLoadKey(win32con.HKEY_USERS, hiveName_dst, dst) hkey_src = win32api.RegOpenKey(win32con.HKEY_USERS, r"%s" % (hiveName_src), 0, win32con.KEY_ALL_ACCESS) hkey_dst = win32api.RegOpenKey(win32con.HKEY_USERS, r"%s" % (hiveName_dst), 0, win32con.KEY_ALL_ACCESS) Reg.CopyTree(hkey_src, "Software", hkey_dst, self.registry_copy_blacklist) win32api.RegCloseKey(hkey_src) win32api.RegCloseKey(hkey_dst) win32api.RegUnLoadKey(win32con.HKEY_USERS, hiveName_src) win32api.RegUnLoadKey(win32con.HKEY_USERS, hiveName_dst) # Copy configuration File if self.profile['profile_mode'] == 'standard': cmd = self.getRsyncMethod(Profile.toCygPath(d), Profile.toCygPath(profile_tmp_dir), Profile.toCygPath(profile_filter)) Logger.debug("rsync cmd '%s'" % (cmd)) p = System.execute(cmd) if p.returncode is not 0: Logger.error("Unable to copy conf from profile") Logger.debug( "Unable to copy conf from profile, cmd '%s' return %d: %s" % (cmd, p.returncode, p.stdout.read())) if os.path.exists(profile_tmp_dir): System.rchown(profile_tmp_dir, self.session.user.name)
def overwriteDefaultRegistry(self, directory): registryFile = os.path.join(directory, "NTUSER.DAT") hiveName = "OVD_%s_%d" % (str(self.id), random.randrange(10000, 50000)) # Load the hive win32api.RegLoadKey(win32con.HKEY_USERS, hiveName, registryFile) # Set the OVD Environnment path = r"%s\Environment" % (hiveName) try: Reg.CreateKeyR(win32con.HKEY_USERS, path) hkey = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) except: hkey = None if hkey is None: Logger.error("Unable to open key '%s'" % (path)) else: win32api.RegSetValueEx(hkey, "OVD_SESSION_DIR", 0, win32con.REG_SZ, self.user_session_dir) win32api.RegCloseKey(hkey) # Set the language if self.parameters.has_key("locale"): cl = Langs.getLCID(self.parameters["locale"]) wl = Langs.unixLocale2WindowsLocale(self.parameters["locale"]) path = r"%s\Control Panel\Desktop" % (hiveName) try: Reg.CreateKeyR(win32con.HKEY_USERS, path) hkey = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) except: hkey = None if hkey is None: Logger.error("Unable to open key '%s'" % (path)) else: win32api.RegSetValueEx(hkey, "MUILanguagePending", 0, win32con.REG_SZ, "%08X" % (cl)) win32api.RegSetValueEx(hkey, "PreferredUILanguagesPending", 0, win32con.REG_MULTI_SZ, [wl]) win32api.RegCloseKey(hkey) # Policies update path = r"%s\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" % ( hiveName) restrictions = [ "DisableFavoritesDirChange", "DisableLocalMachineRun", "DisableLocalMachineRunOnce", "DisableMachineRunOnce", "DisableMyMusicDirChange", "DisableMyPicturesDirChange", "DisablePersonalDirChange", "EnforceShellExtensionSecurity", #"ForceStartMenuLogOff", "Intellimenus", "NoChangeStartMenu", "NoClose", "NoCommonGroups", "NoControlPanel", "NoDFSTab", "NoFind", "NoFolderOptions", "NoHardwareTab", "NoInstrumentation", "NoIntellimenus", "NoInternetIcon", # remove the IE icon "NoManageMyComputerVerb", "NonEnum", "NoNetworkConnections", "NoResolveSearch", "NoSetFolders", "NoSetTaskbar", #"NoStartMenuSubFolders", # should remove the folders from startmenu but doesn't work + On 2008, start menu is empty if this key is set "NoSMBalloonTip", "NoStartMenuEjectPC", "NoStartMenuNetworkPlaces", "NoTrayContextMenu", "NoWindowsUpdate", #"NoViewContextMenu", # Mouse right clic #"StartMenuLogOff", ] try: Reg.CreateKeyR(win32con.HKEY_USERS, path) key = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) except: key = None if key is None: Logger.error("Unable to open key '%s'" % (path)) else: for item in restrictions: win32api.RegSetValueEx(key, item, 0, win32con.REG_DWORD, 1) win32api.RegCloseKey(key) # Hide local drives value = 0 drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] for drive in drives: t = win32file.GetDriveType(drive) if t not in [ win32con.DRIVE_CDROM, win32con.DRIVE_REMOVABLE, win32con.DRIVE_FIXED ]: continue # Transform the drive letter into a bit value according to # http://technet.microsoft.com/en-us/library/cc959437.aspx value += 1 << (ord(drive.lower()[0]) - 97) path = r"%s\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" % ( hiveName) try: Reg.CreateKeyR(win32con.HKEY_USERS, path) key = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) except: key = None if key is None: Logger.error("Unable to open key '%s'" % (path)) else: win32api.RegSetValueEx(key, "NoDrives", 0, win32con.REG_DWORD, value) # win32api.RegSetValueEx(key, "NoViewOnDrive", 0, win32con.REG_DWORD, value) win32api.RegCloseKey(key) # Enable to use of lnk file from share without popup path = r"%s\Software\Microsoft\Windows\CurrentVersion\Policies\Associations" % ( hiveName) try: Reg.CreateKeyR(win32con.HKEY_USERS, path) key = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) except: key = None if key is None: Logger.error("Unable to open key '%s'" % (path)) else: win32api.RegSetValueEx(key, "ModRiskFileTypes", 0, win32con.REG_SZ, ".exe;.msi;.vbs") win32api.RegCloseKey(key) # start menu customization path = r"%s\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" % ( hiveName) restrictions = [ "Start_ShowRun", "StartMenuAdminTools", "Start_AdminToolsRoot" ] try: Reg.CreateKeyR(win32con.HKEY_USERS, path) key = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) except: key = None if key is None: Logger.error("Unable to open key '%s'" % (path)) else: for item in restrictions: win32api.RegSetValueEx(key, item, 0, win32con.REG_DWORD, 0) win32api.RegCloseKey(key) if self.profile is not None: # http://support.microsoft.com/kb/810869 # Do not show recycle bin path = r"%s\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel" % ( hiveName) restrictions = ["{645FF040-5081-101B-9F08-00AA002F954E}"] try: Reg.CreateKeyR(win32con.HKEY_USERS, path) key = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) except: key = None if key is None: Logger.error("Unable to open key '%s'" % (path)) else: for item in restrictions: win32api.RegSetValueEx(key, item, 0, win32con.REG_DWORD, 1) win32api.RegCloseKey(key) path = r"%s\Software\Microsoft\Windows\CurrentVersion\Policies\System" % ( hiveName) restrictions = [ "DisableRegistryTools", "DisableTaskMgr", "DisableLockWorkstation", "NoDispCPL", ] try: Reg.CreateKeyR(win32con.HKEY_USERS, path) key = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) except: key = None if key is None: Logger.error("Unable to open key '%s'" % (path)) else: for item in restrictions: win32api.RegSetValueEx(key, item, 0, win32con.REG_DWORD, 1) win32api.RegCloseKey(key) # Remove Windows startup sound keys = [ "WindowsLogon", "WindowsLogoff", "SystemStart", # old Windows 2003, not used anymore in 2008 ] for k in keys: path = r"%s\AppEvents\Schemes\Apps\.Default\%s\.Current" % ( hiveName, k) try: Reg.CreateKeyR(win32con.HKEY_USERS, path) key = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) except: key = None if key is None: Logger.error("Unable to open key '%s'" % (path)) else: win32api.RegSetValueEx(key, None, 0, win32con.REG_EXPAND_SZ, "") win32api.RegCloseKey(key) # Desktop customization path = r"%s\Control Panel\Desktop" % (hiveName) items = ["ScreenSaveActive", "ScreenSaverIsSecure"] try: Reg.CreateKeyR(win32con.HKEY_USERS, path) key = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) except: key = None if key is None: Logger.error("Unable to open key '%s'" % (path)) else: for item in items: win32api.RegSetValueEx(key, item, 0, win32con.REG_DWORD, 0) win32api.RegCloseKey(key) # Overwrite Active Setup: works partially try: Reg.UpdateActiveSetup(self.user.name, hiveName, r"Software\Microsoft\Active Setup") # On 64 bits architecture, Active Setup is already present in path "Software\Wow6432Node\Microsoft\Active Setup" if "PROGRAMW6432" in os.environ.keys(): Reg.UpdateActiveSetup( self.user.name, hiveName, r"Software\Wow6432Node\Microsoft\Active Setup") except Exception: Logger.exception("Unable to reset ActiveSetup") if self.profile is not None: self.profile.overrideRegistry(hiveName, self.user.name) self.domain.doCustomizeRegistry(hiveName) # Timezone override if self.parameters.has_key("timezone"): tz_name = Langs.getWinTimezone(self.parameters["timezone"]) ret = Reg.setTimezone(hiveName, tz_name) if ret is False: Logger.warn("Unable to set TimeZone (%s, %s)" % (self.parameters["timezone"], tz_name)) # Hack for Windows 2012R2 relative to StartScreen integration. path = r"%s\Software\Microsoft\Windows\CurrentVersion\Explorer\StartPage" % ( hiveName) try: Reg.CreateKeyR(win32con.HKEY_USERS, path) key = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) except: key = None if key is None: Logger.error("Unable to open key '%s'" % (path)) else: win32api.RegSetValueEx(key, "MakeAllAppsDefault", 0, win32con.REG_DWORD, 1) win32api.RegCloseKey(key) # Unload the hive win32api.RegUnLoadKey(win32con.HKEY_USERS, hiveName)
def remove_account_profile(user_name=None): # Remove the profile/files for the user if user_name is None: user_name = util.get_param(2, None) if user_name is None: p("}}enInvalid User name - not removing account profile!}}xx") return False # Log it out (if it is logged in) UserAccounts.log_out_user(user_name) # Get the SID for the user in question user_sid = "" try: parts = win32security.LookupAccountName(None, user_name) user_sid = win32security.ConvertSidToStringSid(parts[0]) except Exception as ex: # Unable to find this user? p("}}rnError - Invalid User - can't remove profile!}}xx " + str(user_name)) return False if user_sid == "": # User doesn't exist? p("}}rnInvalid User - can't remove profile!}}xx " + str(user_name)) return False # We need more privileges to do this next part UserAccounts.elevate_process_privilege_to_backup_restore() # Make sure the registry hive is unloaded #p("Unloading " + user_sid) try: win32api.RegUnLoadKey(win32con.HKEY_USERS, user_sid) except Exception as ex: p("}}ynUnable to unload user registry - likely not currently loaded, moving on...}}xx", debug_level=4) try: win32profile.DeleteProfile(user_sid) except Exception as ex: p("}}ynUnable to remove profile folder - likely it doesn't exist.}}xx", debug_level=4) return True #See if a profile exists w = wmi.WMI() profiles = w.Win32_UserProfile(SID=user_sid) if len(profiles) < 1: p("}}ynNo profile found for this user, skipping remove!}}xx") return True profile_path = "" profile_loaded = False for profile in profiles: profile_path = profile.LocalPath profile_loaded = profile.Loaded profiles = None # We know it exists # Remove it from the registry list RegistrySettings.remove_key("HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\" + \ "ProfileList\\" + user_sid) # Delete the folder/files try: shutil.rmtree(profile_path) except Exception as ex: p("}}rnError - Unable to remove the profile folder at " + profile_path + "}}xx\n" + \ str(ex)) return False return True
win32api.RegLoadKey(win32con.HKEY_USERS, hiveName_dst, dst) hkey_src = win32api.RegOpenKey(win32con.HKEY_USERS, r"%s" % (hiveName_src), 0, win32con.KEY_ALL_ACCESS) hkey_dst = win32api.RegOpenKey(win32con.HKEY_USERS, r"%s" % (hiveName_dst), 0, win32con.KEY_ALL_ACCESS) Reg.CopyTree(hkey_src, "Software", hkey_dst, self.registry_copy_blacklist) win32api.RegCloseKey(hkey_src) win32api.RegCloseKey(hkey_dst) win32api.RegUnLoadKey(win32con.HKEY_USERS, hiveName_src) win32api.RegUnLoadKey(win32con.HKEY_USERS, hiveName_dst) # Copy AppData src = os.path.join(d, "AppData") if os.path.exists(src): dst = self.session.appDataDir try: Util.copyDirOverride(src, dst, [ "Protect", "Start Menu", "Crypto", "ulteo", "Identities" ]) except Exception, err: Logger.error("Unable to copy appData from profile") Logger.debug("Unable to copy appData from profile: %s" %