I have an application that relies heavily on authorization of users. Within it, I am using IPrincipal.IsInRole() to check whether users are in the correct groups:
IPrincipal principal = Thread.CurrentPrincipal;
bool inRole = principal.IsInRole("mydomainname\some role with a long name");
This works fine for the most part, but fails (returns an incorrect result) if the principal is an instance of a WindowsPrincipal. I have found that to make it work correctly, I have to truncate the name of the role that I pass in to be 32 characters long (including the domain name and the \):
IPrincipal principal = Thread.CurrentPrincipal; // <- returns a WindowsPrincipal
bool inRole = principal.IsInRole("mydomainname\some role with a lo");
Truncating the role name then works correctly. Why? Is this a bug/feature/documented issue? I have an inkling that it may be related to Win2000 domains, but cannot find any info on it.
Some extra info:
This is a problem because the application can be configured to use either active directory or "custom" for its authorization ("custom" being any authorization provider that supports an interface - could be SQL-based, file-based, etc..). When custom is configured, the roles most likely do not need truncating and so I don't want to have to deal with this special case in my code. Additionally, I have another part of the application that uses classes in the System.DirectoryServices.AccountManagement namespace to look up groups memberships. This requires the full role name and does not work if they are truncated.
After much trial and error, I have figured out what is going on.
When a group is created in Active Directory, it is given two names:
It seems to be that WindowsPrincipal uses the pre-Windows 2000 group name when IsInRole is called.
After searching extensively, this does not seem to be documented anywhere. The closest I got was this speculative answer to a similar question here on SO.
In my case, the groups I was querying against on the domain had a long name, but a truncated pre-Windows 2000 name (truncated to 32 characters for some reason). Passing in the long name does not work as it was checking against the wrong group name.
Related
I am using .NET Framework 4.8 by necessity. I am running into an issue where:
UserPrincipal.FindByIdentity(context, username); is resulting in a System.DirectoryServices.AccountManagement.MultipleMatchesException exception for a specific username. I can retrieve other users just fine.
There are two accounts in my Active Directory that this user utilizes, however, both of them have different UPNs, sAMAccountNames, etc.
I took a look at the IdentityType enum and the FindByIdentity overload that allows for an exact IdentityType look-up. With this information, I used each possible IdentityType and tried the searches:
None of these lines of code result in a System.DirectoryServices.AccountManagement.MultipleMatchesException exception. The Sid and Guid look-ups fail because the username field isn't in the right format, and the other look-ups either pull the user or pull null.
So what am I missing here? Does the overload that leaves out a specific IdentityType do a different look-up than anything that's possible by supplying an IdentityType?
Edit #1: As Alex pointed out, I left out that I tried IdentityType.UserPrincipalName from my screenshot. This was just a cropping mistake. That call also does not throw an exception.
When you don't specify which identifier you're using, it's going to try them all at once. The source code is available now. The code that actually builds the query and executes it is here. Specifically it's line 617 where it starts building the filter. The source for IdentityClaimToFilter is here. Then it puts each condition in an OR.
So if we ignore Guid, Sid, and DistinguishedName, since we know those won't match, this is the relevant LDAP query (assuming the username you're using is "UserName"):
(|(sAMAccountName=UserName)(userPrincipalName=UserName)(name=UserName))
Try making that query in PowerShell and see if you get multiple matches (I'm assuming the computer you run this from is joined to the domain you want to search):
$search = [adsisearcher]"(|(sAMAccountName=UserName)(userPrincipalName=UserName)(name=UserName))"
$search.FindAll()
If the sAMAccountName of one account matches the name of another account, for example, you will get multiple matches.
I'm quite new to the asp.net core identity framework. Many tutorials, articles and guides seem to handle an IdentityError in the same way. They expose the description of the error to the user, i.e. they add the description of the error to the ModelState.
It's been drummed into my head that exposing errors to the user is a terrible idea as it empowers attackers.
So I thought, It must depend on what kind of information is available in the description. For example, if the error is "Your password is too weak" or "You need to enter in a valid e-mail address". That type of information is valuable to the user and should be ok to display. However a "The data source took too long to respond" is already too much information and offers little value. I'd rather catch that type of error and replace it with some generic 500 error.
So my question: Is it safe to show the raw Identity Error to the user? If not how can I filter what I should and Should not show to the user?
I tried looking at the MSDN docs to understand all the possible codes that I could receive. But those docs offer very little information.
I am specifically working with
var userCreationResult = await userManager.CreateAsync(newUser, password);
But it applies to any instance when an IdentityError might appear.
Many software quality and security regulations have audit requirements for this (no error message presented to end users may contain information that is secret or would enable users with malicious intent to compromise the system or access sensitive data), so this is an important question. If there is a documentation or article specifically addressing this, then it is well hidden.
The possible values that the two members of the IdentityError class can assume, are baked into the framework. So it looks like you can be sure that it will always be one of those, unless you obtain an instance of IdentityError from anything else than a UserManager.
The Code field is assigned from nameof of the error method, and the associated Description text is read from core framework resources, so those will be localized.
Source Code
en-us Descriptions
List of errors in current implementation (version 3.0.0):
DefaultError
ConcurrencyFailure
PasswordMismatch
InvalidToken
RecoveryCodeRedemptionFailed
LoginAlreadyAssociated
InvalidUserName
InvalidEmail
DuplicateUserName
DuplicateEmail
InvalidRoleName
DuplicateRoleName
UserAlreadyHasPassword
UserLockoutNotEnabled
UserAlreadyInRole
UserNotInRole
PasswordTooShort
PasswordRequiresUniqueChars
PasswordRequiresNonAlphanumeric
PasswordRequiresNonAlphanumeric
PasswordRequiresLower
PasswordRequiresUpper
Most of these are static strings and do not disclose any variable information.
The following do disclose variable information. This is data previously supplied by the user anyway in the first eight cases, and the value of a server configuration property in the last two cases, minimum required password length and minimum number of unique characters required in a valid password:
InvalidUserName: the user name
InvalidEmail: the email address
DuplicateUserName: the user name
DuplicateEmail: the email address
InvalidRoleName: the name of the role
DuplicateRoleName: the name of the role
UserAlreadyInRole: the name of the role
UserNotInRole: the name of the role
PasswordTooShort: the minimum password length
PasswordRequiresUniqueChars: the number of unique chars required
If that qualifies as "safe" within the constraints and specifications of your project, then the answer is yes.
Regarding your second question on how to do, you could do the following to filter out
a duplicate username as you loop through errors
if (error.Code == _userManager.ErrorDescriber.DuplicateUserName(user.UserName).Code)
{
//Hide info to user by, e.g. redirecting to a page for a registration flow, or display an invalid login attempt for a login flow
}
I have a task to select specific group of computers. Their unique property is that their security list contains permission for specific user. In AD tool - right click on computer, Security tab, Group or user names as seen on screenshot:
I can get the ComputerPrincipal object of relevant host, UserPrincipal of user, and both underlying DirectoryEntry objects, but I struggle to make a "join" and find if user is on the list.
I use C#, .NET3.5.
You will have to loop through every group, and for each group you could do something like this (assuming you have a groupDe, which is a DirectoryEntry for the group):
foreach (var identityReference in groupDe.ObjectSecurity.GetAccessRules(true, false, typeof(System.Security.Principal.SecurityIdentifier)) {
var nt_name = identityReference.Translate(typeof(NTAccount)).Value;
//nt_name.Value is now domain\username of the user this permission is for
//so you can match this against your list of users
}
The false in the call to GetAccessRules makes it not look at inherited permissions (I assumed that's what you want).
I haven't tested this, so it might need some tweaking.
This will probably be a very slow process, depending on how many groups you're looking through. You might be able to make it go faster by omitting the call to Translate. identityReference.Value would have (I believe) a SID, so you could try to match by SID rather than translating to something else before matching.
User will input his wanted login name and I need to create active directory user by given name. So I need to validate it for AD userPrincipalName rules. How can I do it?
You need only query the UPN (Forest wide so do a globalcatalog search). If the DirectorySearcher returns an object, the UPN is in use.
You would also need to check that the planed samAccountName is not in use in the target domain, and that the planed user Name is not in the destination OU or Container. In both searches, as above, if the DirectorySearcher returns results, you must not continue, but chose alternatives.
Look here to find which attributes must be unique, but bear in mind, although the user's Name attribute is not mentioned in the table, it is being refered to in example 1.
I'm having issues with our Domain Administrator changing the name of our domain org units without any warning. I have the AD path listed in my web.config. When he changes the names my reference in the code breaks. Is there another way to reference i.e. some sort of 'OU ID'?
<appSettings>
<add key="adStructure" value="OU=Org Name 2,OU=Org Name 1,dc=test,dc=test2,dc=test3"/>
</appSettings>
I'm trying to get a list of all groups within OU Org Name 2.
Yes, you can take advantage of otherWellKnownObjects. http://msdn.microsoft.com/en-us/library/ms679095(v=vs.85).aspx. You will need to populate a GUID and initial path to each OU in there, and then in the future when the OU is moved or renamed, AD will keep track. You simply bind by GUID instead of DN.
This link explains how - http://msdn.microsoft.com/en-us/library/ms676295(v=vs.85).aspx.
If the user accounts or other bjects you are accessing have an unique property for accessing them you could perform an LDAP/AD search query for getting the list of objects you need - independent of the distinguished name (DN) and therefore independent of the OU the are located in.
For details how to search in the AD see here:
How to get AD User Groups for user in Asp.Net?
http://www.codeproject.com/KB/system/QueryADwithDotNet.aspx
If you are looking for user objects an alternative would be a group containing all user accounts related to your application - as the Active Directory automatically updates/generates the distinguished name of the members.