def _GetServiceShortName(longName):
# looks up a services name
# from the display name
# Thanks to Andy McKay for this code.
access = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services", 0, access)
num = win32api.RegQueryInfoKey(hkey)[0]
longName = longName.lower()
# loop through number of subkeys
for x in range(0, num):
# find service name, open subkey
svc = win32api.RegEnumKey(hkey, x)
skey = win32api.RegOpenKey(hkey, svc, 0, access)
try:
# find display name
thisName = str(win32api.RegQueryValueEx(skey, "DisplayName")[0])
if thisName.lower() == longName:
return svc
except win32api.error:
# in case there is no key called DisplayName
pass
return None
# Open a service given either it's long or short name.
python类KEY_READ的实例源码
def _GetServiceShortName(longName):
# looks up a services name
# from the display name
# Thanks to Andy McKay for this code.
access = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services", 0, access)
num = win32api.RegQueryInfoKey(hkey)[0]
longName = longName.lower()
# loop through number of subkeys
for x in range(0, num):
# find service name, open subkey
svc = win32api.RegEnumKey(hkey, x)
skey = win32api.RegOpenKey(hkey, svc, 0, access)
try:
# find display name
thisName = str(win32api.RegQueryValueEx(skey, "DisplayName")[0])
if thisName.lower() == longName:
return svc
except win32api.error:
# in case there is no key called DisplayName
pass
return None
# Open a service given either it's long or short name.
def get_regkey(self):
try:
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
keyPath = 'Software\\Skype\\ProtectedStorage'
try:
hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyPath, 0, accessRead)
except Exception, e:
print e
return ''
num = win32api.RegQueryInfoKey(hkey)[1]
k = win32api.RegEnumValue(hkey, 0)
if k:
key = k[1]
return win32crypt.CryptUnprotectData(key, None, None, None, 0)[1]
except Exception, e:
print e
return 'failed'
# get hash from configuration file
def _GetServiceShortName(longName):
# looks up a services name
# from the display name
# Thanks to Andy McKay for this code.
access = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services", 0, access)
num = win32api.RegQueryInfoKey(hkey)[0]
longName = longName.lower()
# loop through number of subkeys
for x in range(0, num):
# find service name, open subkey
svc = win32api.RegEnumKey(hkey, x)
skey = win32api.RegOpenKey(hkey, svc, 0, access)
try:
# find display name
thisName = str(win32api.RegQueryValueEx(skey, "DisplayName")[0])
if thisName.lower() == longName:
return svc
except win32api.error:
# in case there is no key called DisplayName
pass
return None
# Open a service given either it's long or short name.
def check_registry():
for key_string in reg_paths:
parts = key_string.split("\\")
hive = parts[0]
key_string = "\\".join(parts[1:])
try:
keyh = win32api.RegOpenKeyEx(getattr(win32con, hive), key_string, 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ)
except:
#print "Can't open: " + hive + "\\" + key_string
continue
sd = win32api.RegGetKeySecurity(keyh, win32security.DACL_SECURITY_INFORMATION | win32security.OWNER_SECURITY_INFORMATION)
weak_perms = check_weak_write_perms_by_sd(hive + "\\" + key_string, 'reg', sd)
if weak_perms:
vprint(hive + "\\" + key_string)
#print weak_perms
if verbose == 0:
sys.stdout.write(".")
save_issue("WPC003", "writable_reg_paths", weak_perms)
# print_weak_perms("x", weak_perms)
print
# TODO save_issue("WPC009", "writable_eventlog_key", weak_perms) # weak perms on event log reg key
def get_user_paths():
try:
keyh = win32api.RegOpenKeyEx(win32con.HKEY_USERS, None , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ)
except:
return 0
paths = []
subkeys = win32api.RegEnumKeyEx(keyh)
for subkey in subkeys:
try:
subkeyh = win32api.RegOpenKeyEx(keyh, subkey[0] + "\\Environment" , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ)
except:
pass
else:
subkey_count, value_count, mod_time = win32api.RegQueryInfoKey(subkeyh)
try:
path, type = win32api.RegQueryValueEx(subkeyh, "PATH")
paths.append((subkey[0], path))
except:
pass
return paths
def get_system_path():
# HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
key_string = 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
try:
keyh = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, key_string , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ)
except:
return None
try:
path, type = win32api.RegQueryValueEx(keyh, "PATH")
return path
except:
return None
#name=sys.argv[1]
#if not os.path.exists(name):
#print name, "does not exist!"
#sys.exit()
def get_regkey(self):
try:
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
keyPath = 'Software\\Skype\\ProtectedStorage'
try:
hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyPath, 0, accessRead)
except Exception, e:
# print e
return ''
num = win32api.RegQueryInfoKey(hkey)[1]
k = win32api.RegEnumValue(hkey, 0)
if k:
key = k[1]
return win32crypt.CryptUnprotectData(key, None, None, None, 0)[1]
except Exception, e:
# print e
return 'failed'
# get hash from configuration file
def getProgramsMenuPath():
"""Get the path to the Programs menu.
Probably will break on non-US Windows.
@returns: the filesystem location of the common Start Menu->Programs.
"""
if not platform.isWinNT():
return "C:\\Windows\\Start Menu\\Programs"
keyname = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders'
hShellFolders = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE,
keyname, 0, win32con.KEY_READ)
return win32api.RegQueryValueEx(hShellFolders, 'Common Programs')[0]
def getProgramFilesPath():
"""Get the path to the Program Files folder."""
keyname = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
currentV = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE,
keyname, 0, win32con.KEY_READ)
return win32api.RegQueryValueEx(currentV, 'ProgramFilesDir')[0]
def CheckPythonPaths(verbose):
if verbose: print "Python Paths:"
# Check the core path
if verbose: print "\tCore Path:",
try:
appPath = win32api.RegQueryValue(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath")
except win32api.error, exc:
print "** does not exist - ", exc.strerror
problem = CheckPathString(appPath)
if problem:
print problem
else:
if verbose: print appPath
key = win32api.RegOpenKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath", 0, win32con.KEY_READ)
try:
keyNo = 0
while 1:
try:
appName = win32api.RegEnumKey(key, keyNo)
appPath = win32api.RegQueryValue(key, appName)
if verbose: print "\t"+appName+":",
if appPath:
problem = CheckPathString(appPath)
if problem:
print problem
else:
if verbose: print appPath
else:
if verbose: print "(empty)"
keyNo = keyNo + 1
except win32api.error:
break
finally:
win32api.RegCloseKey(key)
def CheckHelpFiles(verbose):
if verbose: print "Help Files:"
try:
key = win32api.RegOpenKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ)
except win32api.error, exc:
import winerror
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
raise
return
try:
keyNo = 0
while 1:
try:
helpDesc = win32api.RegEnumKey(key, keyNo)
helpFile = win32api.RegQueryValue(key, helpDesc)
if verbose: print "\t"+helpDesc+":",
# query the os section.
try:
os.stat(helpFile )
if verbose: print helpFile
except os.error:
print "** Help file %s does not exist" % helpFile
keyNo = keyNo + 1
except win32api.error, exc:
import winerror
if exc.winerror!=winerror.ERROR_NO_MORE_ITEMS:
raise
break
finally:
win32api.RegCloseKey(key)
def getProgramsMenuPath():
"""Get the path to the Programs menu.
Probably will break on non-US Windows.
@returns: the filesystem location of the common Start Menu->Programs.
"""
if not platform.isWinNT():
return "C:\\Windows\\Start Menu\\Programs"
keyname = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders'
hShellFolders = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE,
keyname, 0, win32con.KEY_READ)
return win32api.RegQueryValueEx(hShellFolders, 'Common Programs')[0]
def getProgramFilesPath():
"""Get the path to the Program Files folder."""
keyname = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
currentV = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE,
keyname, 0, win32con.KEY_READ)
return win32api.RegQueryValueEx(currentV, 'ProgramFilesDir')[0]
def CheckPythonPaths(verbose):
if verbose: print "Python Paths:"
# Check the core path
if verbose: print "\tCore Path:",
try:
appPath = win32api.RegQueryValue(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath")
except win32api.error, exc:
print "** does not exist - ", exc.strerror
problem = CheckPathString(appPath)
if problem:
print problem
else:
if verbose: print appPath
key = win32api.RegOpenKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath", 0, win32con.KEY_READ)
try:
keyNo = 0
while 1:
try:
appName = win32api.RegEnumKey(key, keyNo)
appPath = win32api.RegQueryValue(key, appName)
if verbose: print "\t"+appName+":",
if appPath:
problem = CheckPathString(appPath)
if problem:
print problem
else:
if verbose: print appPath
else:
if verbose: print "(empty)"
keyNo = keyNo + 1
except win32api.error:
break
finally:
win32api.RegCloseKey(key)
def CheckHelpFiles(verbose):
if verbose: print "Help Files:"
try:
key = win32api.RegOpenKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ)
except win32api.error, exc:
import winerror
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
raise
return
try:
keyNo = 0
while 1:
try:
helpDesc = win32api.RegEnumKey(key, keyNo)
helpFile = win32api.RegQueryValue(key, helpDesc)
if verbose: print "\t"+helpDesc+":",
# query the os section.
try:
os.stat(helpFile )
if verbose: print helpFile
except os.error:
print "** Help file %s does not exist" % helpFile
keyNo = keyNo + 1
except win32api.error, exc:
import winerror
if exc.winerror!=winerror.ERROR_NO_MORE_ITEMS:
raise
break
finally:
win32api.RegCloseKey(key)
def _ListAllHelpFilesInRoot(root):
"""Returns a list of (helpDesc, helpFname) for all registered help files
"""
import regutil
retList = []
try:
key = win32api.RegOpenKey(root, regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ)
except win32api.error, exc:
import winerror
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
raise
return retList
try:
keyNo = 0
while 1:
try:
helpDesc = win32api.RegEnumKey(key, keyNo)
helpFile = win32api.RegQueryValue(key, helpDesc)
retList.append((helpDesc, helpFile))
keyNo = keyNo + 1
except win32api.error, exc:
import winerror
if exc.winerror!=winerror.ERROR_NO_MORE_ITEMS:
raise
break
finally:
win32api.RegCloseKey(key)
return retList
def check_winscp_installed(self):
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
try:
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER,
'Software\Martin Prikryl\WinSCP 2\Configuration\Security', 0, accessRead)
return True
except Exception, e:
return False
def check_masterPassword(self):
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'Software\Martin Prikryl\WinSCP 2\Configuration\Security',
0, accessRead)
thisName = str(win32api.RegQueryValueEx(key, 'UseMasterPassword')[0])
if thisName == '0':
return False
else:
return True
def get_key_info(self):
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
try:
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'Software\\FTPware\\CoreFTP\\Sites', 0, accessRead)
except Exception, e:
return False
num_profiles = win32api.RegQueryInfoKey(key)[0]
pwdFound = []
for n in range(num_profiles):
name_skey = win32api.RegEnumKey(key, n)
skey = win32api.RegOpenKey(key, name_skey, 0, accessRead)
num = win32api.RegQueryInfoKey(skey)[1]
values = {}
for nn in range(num):
k = win32api.RegEnumValue(skey, nn)
if k[0] == 'Host':
values['Host'] = k[1]
if k[0] == 'Port':
values['Port'] = k[1]
if k[0] == 'User':
values['User'] = k[1]
pwdFound.append(values)
if k[0] == 'PW':
try:
values['Password'] = self.decrypt(k[1])
except Exception, e:
values['Password'] = 'N/A'
# print the results
return pwdFound
def run(self):
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
keyPath = 'Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows Messaging Subsystem\\Profiles\\Outlook'
try:
hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyPath, 0, accessRead)
except Exception, e:
return
num = win32api.RegQueryInfoKey(hkey)[0]
pwdFound = []
for x in range(0, num):
name = win32api.RegEnumKey(hkey, x)
skey = win32api.RegOpenKey(hkey, name, 0, accessRead)
num_skey = win32api.RegQueryInfoKey(skey)[0]
if num_skey != 0:
for y in range(0, num_skey):
name_skey = win32api.RegEnumKey(skey, y)
sskey = win32api.RegOpenKey(skey, name_skey, 0, accessRead)
num_sskey = win32api.RegQueryInfoKey(sskey)[1]
for z in range(0, num_sskey):
k = win32api.RegEnumValue(sskey, z)
if 'password' in k[0].lower():
values = self.retrieve_info(sskey, name_skey)
# write credentials into a text file
if len(values) != 0:
pwdFound.append(values)
# print the results
return pwdFound
def _ListAllHelpFilesInRoot(root):
"""Returns a list of (helpDesc, helpFname) for all registered help files
"""
import regutil
retList = []
try:
key = win32api.RegOpenKey(root, regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ)
except win32api.error as exc:
import winerror
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
raise
return retList
try:
keyNo = 0
while 1:
try:
helpDesc = win32api.RegEnumKey(key, keyNo)
helpFile = win32api.RegQueryValue(key, helpDesc)
retList.append((helpDesc, helpFile))
keyNo = keyNo + 1
except win32api.error as exc:
import winerror
if exc.winerror!=winerror.ERROR_NO_MORE_ITEMS:
raise
break
finally:
win32api.RegCloseKey(key)
return retList
def CheckPythonPaths(verbose):
if verbose: print("Python Paths:")
# Check the core path
if verbose: print("\tCore Path:", end=' ')
try:
appPath = win32api.RegQueryValue(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath")
except win32api.error as exc:
print("** does not exist - ", exc.strerror)
problem = CheckPathString(appPath)
if problem:
print(problem)
else:
if verbose: print(appPath)
key = win32api.RegOpenKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath", 0, win32con.KEY_READ)
try:
keyNo = 0
while 1:
try:
appName = win32api.RegEnumKey(key, keyNo)
appPath = win32api.RegQueryValue(key, appName)
if verbose: print("\t"+appName+":", end=' ')
if appPath:
problem = CheckPathString(appPath)
if problem:
print(problem)
else:
if verbose: print(appPath)
else:
if verbose: print("(empty)")
keyNo = keyNo + 1
except win32api.error:
break
finally:
win32api.RegCloseKey(key)
def CheckHelpFiles(verbose):
if verbose: print("Help Files:")
try:
key = win32api.RegOpenKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ)
except win32api.error as exc:
import winerror
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
raise
return
try:
keyNo = 0
while 1:
try:
helpDesc = win32api.RegEnumKey(key, keyNo)
helpFile = win32api.RegQueryValue(key, helpDesc)
if verbose: print("\t"+helpDesc+":", end=' ')
# query the os section.
try:
os.stat(helpFile )
if verbose: print(helpFile)
except os.error:
print("** Help file %s does not exist" % helpFile)
keyNo = keyNo + 1
except win32api.error as exc:
import winerror
if exc.winerror!=winerror.ERROR_NO_MORE_ITEMS:
raise
break
finally:
win32api.RegCloseKey(key)
def getProgramsMenuPath():
"""
Get the path to the Programs menu.
Probably will break on non-US Windows.
@return: the filesystem location of the common Start Menu->Programs.
@rtype: L{str}
"""
if not platform.isWindows():
return "C:\\Windows\\Start Menu\\Programs"
keyname = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders'
hShellFolders = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE,
keyname, 0, win32con.KEY_READ)
return win32api.RegQueryValueEx(hShellFolders, 'Common Programs')[0]
def getProgramFilesPath():
"""Get the path to the Program Files folder."""
keyname = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
currentV = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE,
keyname, 0, win32con.KEY_READ)
return win32api.RegQueryValueEx(currentV, 'ProgramFilesDir')[0]
def check_winscp_installed(self):
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
try:
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER,
'Software\Martin Prikryl\WinSCP 2\Configuration\Security', 0, accessRead)
return True
except Exception, e:
return False
def check_masterPassword(self):
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'Software\Martin Prikryl\WinSCP 2\Configuration\Security',
0, accessRead)
thisName = str(win32api.RegQueryValueEx(key, 'UseMasterPassword')[0])
if thisName == '0':
return False
else:
return True
def get_logins_info(self):
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
try:
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'Software\Martin Prikryl\WinSCP 2\Sessions', 0,
accessRead)
except Exception, e:
return False
num_profiles = win32api.RegQueryInfoKey(key)[0]
pwdFound = []
for n in range(num_profiles):
name_skey = win32api.RegEnumKey(key, n)
skey = win32api.RegOpenKey(key, name_skey, 0, accessRead)
num = win32api.RegQueryInfoKey(skey)[1]
port = ''
values = {}
for nn in range(num):
k = win32api.RegEnumValue(skey, nn)
if k[0] == 'HostName':
self.set_hostname(k[1])
if k[0] == 'UserName':
self.set_username(k[1])
if k[0] == 'Password':
self.set_hash(k[1])
if k[0] == 'PortNumber':
port = str(k[1])
if num != 0:
if port == '':
port = '22'
try:
password = self.decrypt_password()
values['Password'] = password
except Exception, e:
pass
values['Hostname'] = self.get_hostname()
values['Port'] = port
values['Username'] = self.get_username()
pwdFound.append(values)
# print the results
return pwdFound
def get_key_info(self):
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
try:
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'Software\\FTPware\\CoreFTP\\Sites', 0, accessRead)
except Exception, e:
return False
num_profiles = win32api.RegQueryInfoKey(key)[0]
pwdFound = []
for n in range(num_profiles):
name_skey = win32api.RegEnumKey(key, n)
skey = win32api.RegOpenKey(key, name_skey, 0, accessRead)
num = win32api.RegQueryInfoKey(skey)[1]
values = {}
for nn in range(num):
k = win32api.RegEnumValue(skey, nn)
if k[0] == 'Host':
values['Host'] = k[1]
if k[0] == 'Port':
values['Port'] = k[1]
if k[0] == 'User':
values['User'] = k[1]
pwdFound.append(values)
if k[0] == 'PW':
try:
values['Password'] = self.decrypt(k[1])
except Exception, e:
values['Password'] = 'N/A'
# print the results
return pwdFound