Python win32security.ConvertSidToStringSid() Examples

The following are 15 code examples of win32security.ConvertSidToStringSid(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module win32security , or try the search function .
Example #1
Source File: authorizers.py    From oss-ftp with MIT License 7 votes vote down vote up
def get_home_dir(self, username):
            """Return the user's profile directory, the closest thing
            to a user home directory we have on Windows.
            """
            try:
                sid = win32security.ConvertSidToStringSid(
                    win32security.LookupAccountName(None, username)[0])
            except pywintypes.error as err:
                raise AuthorizerError(err)
            path = r"SOFTWARE\Microsoft\Windows NT" \
                   r"\CurrentVersion\ProfileList" + "\\" + sid
            try:
                key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
            except WindowsError:
                raise AuthorizerError(
                    "No profile directory defined for user %s" % username)
            value = winreg.QueryValueEx(key, "ProfileImagePath")[0]
            home = win32api.ExpandEnvironmentStrings(value)
            if not PY3 and not isinstance(home, unicode):
                home = home.decode('utf8')
            return home 
Example #2
Source File: authorizers.py    From oss-ftp with MIT License 6 votes vote down vote up
def get_home_dir(self, username):
            """Return the user's profile directory, the closest thing
            to a user home directory we have on Windows.
            """
            try:
                sid = win32security.ConvertSidToStringSid(
                    win32security.LookupAccountName(None, username)[0])
            except pywintypes.error as err:
                raise AuthorizerError(err)
            path = r"SOFTWARE\Microsoft\Windows NT" \
                   r"\CurrentVersion\ProfileList" + "\\" + sid
            try:
                key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
            except WindowsError:
                raise AuthorizerError(
                    "No profile directory defined for user %s" % username)
            value = winreg.QueryValueEx(key, "ProfileImagePath")[0]
            home = win32api.ExpandEnvironmentStrings(value)
            if not PY3 and not isinstance(home, unicode):
                home = home.decode('utf8')
            return home 
Example #3
Source File: authorizers.py    From script-languages with MIT License 6 votes vote down vote up
def get_home_dir(self, username):
            """Return the user's profile directory, the closest thing
            to a user home directory we have on Windows.
            """
            try:
                sid = win32security.ConvertSidToStringSid(
                    win32security.LookupAccountName(None, username)[0])
            except pywintypes.error as err:
                raise AuthorizerError(err)
            path = r"SOFTWARE\Microsoft\Windows NT" \
                   r"\CurrentVersion\ProfileList" + "\\" + sid
            try:
                key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
            except WindowsError:
                raise AuthorizerError(
                    "No profile directory defined for user %s" % username)
            value = winreg.QueryValueEx(key, "ProfileImagePath")[0]
            home = win32api.ExpandEnvironmentStrings(value)
            if not PY3 and not isinstance(home, unicode):
                home = home.decode('utf8')
            return home 
Example #4
Source File: authorizers.py    From pyftpdlib with MIT License 6 votes vote down vote up
def get_home_dir(self, username):
            """Return the user's profile directory, the closest thing
            to a user home directory we have on Windows.
            """
            try:
                sid = win32security.ConvertSidToStringSid(
                    win32security.LookupAccountName(None, username)[0])
            except pywintypes.error as err:
                raise AuthorizerError(err)
            path = r"SOFTWARE\Microsoft\Windows NT" \
                   r"\CurrentVersion\ProfileList" + "\\" + sid
            try:
                key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
            except WindowsError:
                raise AuthorizerError(
                    "No profile directory defined for user %s" % username)
            value = winreg.QueryValueEx(key, "ProfileImagePath")[0]
            home = win32api.ExpandEnvironmentStrings(value)
            if not PY3 and not isinstance(home, unicode):
                home = home.decode('utf8')
            return home 
Example #5
Source File: windows-privesc-check.py    From WHP with Do What The F*ck You Want To Public License 5 votes vote down vote up
def dump_sd(object_name, object_type_s, sd, options={}):
	perms = all_perms
	if not sd:
		return 
	dacl = sd.GetSecurityDescriptorDacl()
	if dacl == None:
		print "No Discretionary ACL"
		return []

	owner_sid = sd.GetSecurityDescriptorOwner()

	try:
		owner_name, owner_domain, type = win32security.LookupAccountSid(remote_server, owner_sid)
		owner_fq = owner_domain + "\\" + owner_name
	except:
		try:
			owner_fq = owner_name = win32security.ConvertSidToStringSid(owner_sid)
			owner_domain = ""
		except:
			owner_domain = ""
			owner_fq = owner_name = None

	group_sid = sd.GetSecurityDescriptorGroup()
	try:
		group_name, group_domain, type = win32security.LookupAccountSid(remote_server, group_sid)
		group_fq = group_domain + "\\" + group_name
	except:
		try:
			group_fq = group_name = win32security.ConvertSidToStringSid(group_sid)
			group_domain = ""
		except:
			group_domain = ""
			group_fq = group_name = "[none]"

	if owner_info:
		print "\tOwner: " + str(owner_fq)
		print "\tGroup: " + str(group_fq)
		
	weak_perms = []
	dump_acl(object_name, object_type_s, dacl, options)
	return 
Example #6
Source File: windows-privesc-check.py    From WHP with Do What The F*ck You Want To Public License 5 votes vote down vote up
def audit_passpol():
	print 
	print "[+] NetUserModalsGet 0,1,2,3"
	print
	
	try:
		data = win32net.NetUserModalsGet(remote_server, 0)
		for key in data.keys():
			print "%s: %s" % (key, data[key])
		data = win32net.NetUserModalsGet(remote_server, 1)
		for key in data.keys():
			print "%s: %s" % (key, data[key])
		data = win32net.NetUserModalsGet(remote_server, 2)
		for key in data.keys():
			if key == 'domain_id':
				print "%s: %s" % (key, win32security.ConvertSidToStringSid(data[key]))
			elif key == 'lockout_threshold' and data[key] == '0':
				print "%s: %s (accounts aren't locked out)" % (key, data[key])
			else:
				print "%s: %s" % (key, data[key])
		data = win32net.NetUserModalsGet(remote_server, 3)
		for key in data.keys():
			if key == 'lockout_threshold' and data[key] == 0:
				print "%s: %s (accounts aren't locked out)" % (key, data[key])
			else:
				print "%s: %s" % (key, data[key])
	except:
		print "[E] Couldn't get NetUserModals data"

# Recursive function to find group members (and the member of any groups in those groups...) 
Example #7
Source File: windowsprivcheck.py    From LHF with GNU General Public License v3.0 5 votes vote down vote up
def dump_sd(object_name, object_type_s, sd, options={}):
	perms = all_perms
	if not sd:
		return 
	dacl = sd.GetSecurityDescriptorDacl()
	if dacl is None:
		print "No Discretionary ACL"
		return []

	owner_sid = sd.GetSecurityDescriptorOwner()

	try:
		owner_name, owner_domain, type = win32security.LookupAccountSid(remote_server, owner_sid)
		owner_fq = owner_domain + "\\" + owner_name
	except:
		try:
			owner_fq = owner_name = win32security.ConvertSidToStringSid(owner_sid)
			owner_domain = ""
		except:
			owner_domain = ""
			owner_fq = owner_name = None

	group_sid = sd.GetSecurityDescriptorGroup()
	try:
		group_name, group_domain, type = win32security.LookupAccountSid(remote_server, group_sid)
		group_fq = group_domain + "\\" + group_name
	except:
		try:
			group_fq = group_name = win32security.ConvertSidToStringSid(group_sid)
			group_domain = ""
		except:
			group_domain = ""
			group_fq = group_name = "[none]"

	if owner_info:
		print "\tOwner: " + str(owner_fq)
		print "\tGroup: " + str(group_fq)
		
	weak_perms = []
	dump_acl(object_name, object_type_s, dacl, options)
	return 
Example #8
Source File: windowsprivcheck.py    From LHF with GNU General Public License v3.0 5 votes vote down vote up
def audit_passpol():
	print 
	print "[+] NetUserModalsGet 0,1,2,3"
	print
	
	try:
		data = win32net.NetUserModalsGet(remote_server, 0)
		for key in data.keys():
			print "%s: %s" % (key, data[key])
		data = win32net.NetUserModalsGet(remote_server, 1)
		for key in data.keys():
			print "%s: %s" % (key, data[key])
		data = win32net.NetUserModalsGet(remote_server, 2)
		for key in data.keys():
			if key == 'domain_id':
				print "%s: %s" % (key, win32security.ConvertSidToStringSid(data[key]))
			elif key == 'lockout_threshold' and data[key] == '0':
				print "%s: %s (accounts aren't locked out)" % (key, data[key])
			else:
				print "%s: %s" % (key, data[key])
		data = win32net.NetUserModalsGet(remote_server, 3)
		for key in data.keys():
			if key == 'lockout_threshold' and data[key] == 0:
				print "%s: %s (accounts aren't locked out)" % (key, data[key])
			else:
				print "%s: %s" % (key, data[key])
	except:
		print "[E] Couldn't get NetUserModals data"

# Recursive function to find group members (and the member of any groups in those groups...) 
Example #9
Source File: win32-identd.py    From code with MIT License 5 votes vote down vote up
def reply_userid(self, fd, pid, owner):
        """Send a success reply and log owner information."""

        try:
            local, remote = self.requests[fd]
        except KeyError:
            local, remote = 0, 0

        sid, username, domain = owner

        username = username.replace(":", "_").replace("\r", "").replace("\n", " ")

        code = "USERID"

        info = "%s,%s:%s" % (self.os_name, "UTF-8", username)

        self.logEx("notice",
            "Successful query from %s." % format_addr(*fd.getpeername()),
            ("local",   format_addr(*local)),
            ("remote",  format_addr(*remote)),
            None,
            ("pid",     pid),
            ("owner",   win32security.ConvertSidToStringSid(sid)),
            ("user",    username),
            ("domain",  domain),
            None,
            ("reply",   code),
            ("info",    info),)

        return self.send_reply(fd, local[1], remote[1], code, info) 
Example #10
Source File: windows-privesc-check.py    From WHP with Do What The F*ck You Want To Public License 4 votes vote down vote up
def principle_is_trusted(principle, domain):
	
	if domain + "\\" + principle in trusted_principles_fq:
		return 1
	
	if principle in trusted_principles:
		return 1
	
	global tmp_trusted_principles_fq
	if domain + "\\" + principle in tmp_trusted_principles_fq:
		return 1

	# Consider groups with zero members to be trusted too
	try:
		memberdict, total, rh = win32net.NetLocalGroupGetMembers(remote_server, principle , 1 , 0 , 100000 )
		if len(memberdict) == 0:
			return 1
	except:
		# If a user is a member of a trusted group (like administrators), then they are trusted
		try:
			group_attrs = win32net.NetUserGetLocalGroups(remote_server, principle)
			if set(group_attrs).intersection(set(trusted_principles)):
				return 1
		except:
			pass
			
	return 0

#	for memberinfo in memberdict:
#		print "\t" + memberinfo['name'] + " (" + win32security.ConvertSidToStringSid(memberinfo['sid']) + ")"
# TODO ignore groups that only contain administrators
	
# There are all possible objects.  SE_OBJECT_TYPE (http://msdn.microsoft.com/en-us/library/aa379593(VS.85).aspx):
#  win32security.SE_UNKNOWN_OBJECT_TYPE
#  win32security.SE_FILE_OBJECT
#  win32security.SE_SERVICE
#  win32security.SE_PRINTER
#  win32security.SE_REGISTRY_KEY
#  win32security.SE_LMSHARE
#  win32security.SE_KERNEL_OBJECT
#  win32security.SE_WINDOW_OBJECT
#  win32security.SE_DS_OBJECT
#  win32security.SE_DS_OBJECT_ALL
#  win32security.SE_PROVIDER_DEFINED_OBJECT
#  win32security.SE_WMIGUID_OBJECT
#  win32security.SE_REGISTRY_WOW64_32KEY
# object_type_s is one of
#  service
#  file
#  dir 
Example #11
Source File: windows-privesc-check.py    From WHP with Do What The F*ck You Want To Public License 4 votes vote down vote up
def check_weak_perms_sd(object_name, object_type_s, sd, perms):
	dacl= sd.GetSecurityDescriptorDacl()
	if dacl == None:
		print "No Discretionary ACL"
		return []

	owner_sid = sd.GetSecurityDescriptorOwner()
	try:
		owner_name, owner_domain, type = win32security.LookupAccountSid(remote_server, owner_sid)
		owner_fq = owner_domain + "\\" + owner_name
	except:
		try:
			owner_fq = owner_name = win32security.ConvertSidToStringSid(owner_sid)
			owner_domain = ""
		except:
			owner_domain = ""
			owner_fq = owner_name = "INVALIDSID!"

	weak_perms = []
	for ace_no in range(0, dacl.GetAceCount()):
		#print "[D] ACE #%d" % ace_no
		ace = dacl.GetAce(ace_no)
		flags = ace[0][1]
		
		try:
			principle, domain, type = win32security.LookupAccountSid(remote_server, ace[2])
		except:
			principle = win32security.ConvertSidToStringSid(ace[2])
			domain = ""
		
		#print "[D] ACE is for %s\\%s" % (principle, domain)
		#print "[D] ACE Perm mask: " + int2bin(ace[1])
		#print "[D] ace_type: " + str(ace[0][0])
		#print "[D] DACL: " + win32security.ConvertSecurityDescriptorToStringSecurityDescriptor(sd, win32security.SDDL_REVISION_1, win32security.DACL_SECURITY_INFORMATION)
		if principle_is_trusted(principle, domain):
			#print "[D] Ignoring trusted principle %s\\%s" % (principle, domain)
			continue
		
		if principle == "CREATOR OWNER":
			if principle_is_trusted(owner_name, owner_domain):
				continue
			else:
				principle = "CREATOR OWNER [%s]" % owner_fq
		
		for i in ("ACCESS_ALLOWED_ACE_TYPE", "ACCESS_DENIED_ACE_TYPE", "SYSTEM_AUDIT_ACE_TYPE", "SYSTEM_ALARM_ACE_TYPE"):
			if getattr(ntsecuritycon, i) == ace[0][0]:
				ace_type_s = i
		
		if not ace_type_s == "ACCESS_ALLOWED_ACE_TYPE":
			vprint("WARNING: Unimplmented ACE type encountered: " + ace_type_s + ".  skipping.")
			continue

		for mod, perms_tuple in perms[object_type_s].iteritems():
			for perm in perms_tuple:
				if getattr(mod, perm) & ace[1] == getattr(mod, perm):
					weak_perms.append([object_name, domain, principle, perm])
	return weak_perms 
Example #12
Source File: windows-privesc-check.py    From WHP with Do What The F*ck You Want To Public License 4 votes vote down vote up
def dump_acl(object_name, object_type_s, sd, options={}):
	dacl = sd
	if dacl == None:
		print "No Discretionary ACL"
		return []

	weak_perms = []
	for ace_no in range(0, dacl.GetAceCount()):
		# print "[D] ACE #%d" % ace_no
		ace = dacl.GetAce(ace_no)
		flags = ace[0][1]
		
		try:
			principle, domain, type = win32security.LookupAccountSid(remote_server, ace[2])
		except:
			principle = win32security.ConvertSidToStringSid(ace[2])
			domain = ""
		
		mask = ace[1]
		if ace[1] < 0:
			mask = ace[1] + 2**32

		if ignore_trusted and principle_is_trusted(principle, domain):
			# print "[D] Ignoring trusted principle %s\\%s" % (principle, domain)
			continue
		
		if principle == "CREATOR OWNER":
			if ignore_trusted and principle_is_trusted(owner_name, owner_domain):
				#print "[D] Ignoring trusted principle (creator owner) %s\\%s" % (principle, domain)
				continue
			else:
				principle = "CREATOR OWNER [%s\%s]" % (domain, principle)
		
		for i in ("ACCESS_ALLOWED_ACE_TYPE", "ACCESS_DENIED_ACE_TYPE", "SYSTEM_AUDIT_ACE_TYPE", "SYSTEM_ALARM_ACE_TYPE"):
			if getattr(ntsecuritycon, i) == ace[0][0]:
				ace_type_s = i
		
		ace_type_short = ace_type_s
		
		if ace_type_s == "ACCESS_DENIED_ACE_TYPE":
			ace_type_short = "DENY"
		
		if ace_type_s == "ACCESS_ALLOWED_ACE_TYPE":
			ace_type_short = "ALLOW"

		if weak_perms_only:
			perms = dangerous_perms_write
		else:
			perms = all_perms
			
		for mod, perms_tuple in perms[object_type_s].iteritems():
			for perm in perms_tuple:
				#print "Checking for perm %s in ACE %s" % (perm, mask)
				if getattr(mod, perm) & mask == getattr(mod, perm):
					weak_perms.append([object_name, domain, principle, perm, ace_type_short])
	print_weak_perms(object_type_s, weak_perms, options) 
Example #13
Source File: windowsprivcheck.py    From LHF with GNU General Public License v3.0 4 votes vote down vote up
def principle_is_trusted(principle, domain):
	
	if domain + "\\" + principle in trusted_principles_fq:
		return 1
	
	if principle in trusted_principles:
		return 1
	
	global tmp_trusted_principles_fq
	if domain + "\\" + principle in tmp_trusted_principles_fq:
		return 1

	# Consider groups with zero members to be trusted too
	try:
		memberdict, total, rh = win32net.NetLocalGroupGetMembers(remote_server, principle , 1 , 0 , 100000 )
		if len(memberdict) == 0:
			return 1
	except:
		# If a user is a member of a trusted group (like administrators), then they are trusted
		try:
			group_attrs = win32net.NetUserGetLocalGroups(remote_server, principle)
			if set(group_attrs).intersection(set(trusted_principles)):
				return 1
		except:
			pass
			
	return 0

#	for memberinfo in memberdict:
#		print "\t" + memberinfo['name'] + " (" + win32security.ConvertSidToStringSid(memberinfo['sid']) + ")"
# TODO ignore groups that only contain administrators
	
# There are all possible objects.  SE_OBJECT_TYPE (http://msdn.microsoft.com/en-us/library/aa379593(VS.85).aspx):
#  win32security.SE_UNKNOWN_OBJECT_TYPE
#  win32security.SE_FILE_OBJECT
#  win32security.SE_SERVICE
#  win32security.SE_PRINTER
#  win32security.SE_REGISTRY_KEY
#  win32security.SE_LMSHARE
#  win32security.SE_KERNEL_OBJECT
#  win32security.SE_WINDOW_OBJECT
#  win32security.SE_DS_OBJECT
#  win32security.SE_DS_OBJECT_ALL
#  win32security.SE_PROVIDER_DEFINED_OBJECT
#  win32security.SE_WMIGUID_OBJECT
#  win32security.SE_REGISTRY_WOW64_32KEY
# object_type_s is one of
#  service
#  file
#  dir 
Example #14
Source File: windowsprivcheck.py    From LHF with GNU General Public License v3.0 4 votes vote down vote up
def check_weak_perms_sd(object_name, object_type_s, sd, perms):
	dacl= sd.GetSecurityDescriptorDacl()
	if dacl is None:
		print "No Discretionary ACL"
		return []

	owner_sid = sd.GetSecurityDescriptorOwner()
	try:
		owner_name, owner_domain, type = win32security.LookupAccountSid(remote_server, owner_sid)
		owner_fq = owner_domain + "\\" + owner_name
	except:
		try:
			owner_fq = owner_name = win32security.ConvertSidToStringSid(owner_sid)
			owner_domain = ""
		except:
			owner_domain = ""
			owner_fq = owner_name = "INVALIDSID!"

	weak_perms = []
	for ace_no in range(0, dacl.GetAceCount()):
		#print "[D] ACE #%d" % ace_no
		ace = dacl.GetAce(ace_no)
		flags = ace[0][1]
		
		try:
			principle, domain, type = win32security.LookupAccountSid(remote_server, ace[2])
		except:
			principle = win32security.ConvertSidToStringSid(ace[2])
			domain = ""
		
		#print "[D] ACE is for %s\\%s" % (principle, domain)
		#print "[D] ACE Perm mask: " + int2bin(ace[1])
		#print "[D] ace_type: " + str(ace[0][0])
		#print "[D] DACL: " + win32security.ConvertSecurityDescriptorToStringSecurityDescriptor(sd, win32security.SDDL_REVISION_1, win32security.DACL_SECURITY_INFORMATION)
		if principle_is_trusted(principle, domain):
			#print "[D] Ignoring trusted principle %s\\%s" % (principle, domain)
			continue
		
		if principle == "CREATOR OWNER":
			if principle_is_trusted(owner_name, owner_domain):
				continue
			else:
				principle = "CREATOR OWNER [%s]" % owner_fq
		
		for i in ("ACCESS_ALLOWED_ACE_TYPE", "ACCESS_DENIED_ACE_TYPE", "SYSTEM_AUDIT_ACE_TYPE", "SYSTEM_ALARM_ACE_TYPE"):
			if getattr(ntsecuritycon, i) == ace[0][0]:
				ace_type_s = i
		
		if not ace_type_s == "ACCESS_ALLOWED_ACE_TYPE":
			vprint("WARNING: Unimplmented ACE type encountered: " + ace_type_s + ".  skipping.")
			continue

		for mod, perms_tuple in perms[object_type_s].iteritems():
			for perm in perms_tuple:
				if getattr(mod, perm) & ace[1] == getattr(mod, perm):
					weak_perms.append([object_name, domain, principle, perm])
	return weak_perms 
Example #15
Source File: windowsprivcheck.py    From LHF with GNU General Public License v3.0 4 votes vote down vote up
def dump_acl(object_name, object_type_s, sd, options={}):
	dacl = sd
	if dacl is None:
		print "No Discretionary ACL"
		return []

	weak_perms = []
	for ace_no in range(0, dacl.GetAceCount()):
		# print "[D] ACE #%d" % ace_no
		ace = dacl.GetAce(ace_no)
		flags = ace[0][1]
		
		try:
			principle, domain, type = win32security.LookupAccountSid(remote_server, ace[2])
		except:
			principle = win32security.ConvertSidToStringSid(ace[2])
			domain = ""
		
		mask = ace[1]
		if ace[1] < 0:
			mask = ace[1] + 2**32

		if ignore_trusted and principle_is_trusted(principle, domain):
			# print "[D] Ignoring trusted principle %s\\%s" % (principle, domain)
			continue
		
		if principle == "CREATOR OWNER":
			if ignore_trusted and principle_is_trusted(owner_name, owner_domain):
				#print "[D] Ignoring trusted principle (creator owner) %s\\%s" % (principle, domain)
				continue
			else:
				principle = "CREATOR OWNER [%s\%s]" % (domain, principle)
		
		for i in ("ACCESS_ALLOWED_ACE_TYPE", "ACCESS_DENIED_ACE_TYPE", "SYSTEM_AUDIT_ACE_TYPE", "SYSTEM_ALARM_ACE_TYPE"):
			if getattr(ntsecuritycon, i) == ace[0][0]:
				ace_type_s = i
		
		ace_type_short = ace_type_s
		
		if ace_type_s == "ACCESS_DENIED_ACE_TYPE":
			ace_type_short = "DENY"
		
		if ace_type_s == "ACCESS_ALLOWED_ACE_TYPE":
			ace_type_short = "ALLOW"

		if weak_perms_only:
			perms = dangerous_perms_write
		else:
			perms = all_perms
			
		for mod, perms_tuple in perms[object_type_s].iteritems():
			for perm in perms_tuple:
				#print "Checking for perm %s in ACE %s" % (perm, mask)
				if getattr(mod, perm) & mask == getattr(mod, perm):
					weak_perms.append([object_name, domain, principle, perm, ace_type_short])
	print_weak_perms(object_type_s, weak_perms, options)