2

I would like to loop through all the registry keys and subkeys in a hive, find the value containing a specified string and replace it by a new one (I am adapting this code using winreg)

So far my code works on the keys whose ownership is Administrator and for which Administrator has full control but not on the other keys.

I could set the permissions of all my keys so that Administrator has full control but I would like to avoid that. Instead, I would like to only change the permissions of the keys that match the specified string. After the value is modified the permissions should be set back to what they were.

I have seen this answer from 2012 but I would like to avoid installing a software for that.

Community
  • 1
  • 1
MagTun
  • 5,619
  • 5
  • 63
  • 104

1 Answers1

1

Since nobody answered this question I thought I should share my solution for setting permissions on given keys using the pywin32 library:

import win32con as con
import win32api
import ntsecuritycon as ntc
import pywintypes
import win32security

key = win32api.RegOpenKey(con.HKEY_LOCAL_MACHINE, 'Software\\MyKey', 0, con.KEY_ALL_ACCESS)
ksd = win32api.RegGetKeySecurity(key, con.DACL_SECURITY_INFORMATION)

acl = pywintypes.ACL()
acl.AddAccessAllowedAce(ntc.GENERIC_ALL, win32security.ConvertStringSidToSid('S-1-5-18'))
acl.AddAccessAllowedAce(ntc.GENERIC_ALL, win32security.ConvertStringSidToSid('S-1-5-32-544'))

ksd.SetDacl(True, acl, False)

win32api.RegSetKeySecurity(key, con.DACL_SECURITY_INFORMATION, ksd)

This will set the HKLM\SOFTWARE\MyKey key permission to FULL CONTROL for SYSTEM and Administrators but no other group will have read or write access. Note that the ksd variable has the original ACL in it until we run .SetDacl() on it, so if you want to write back the original permissions after the operation, just back that up to another variable like ksd_bac first, and then run win32api.RegSetKeySecurity(key, con.DACL_SECURITY_INFORMATION, ksd_bac) after the operation.

Grintor
  • 66
  • 3