Async search request using DirectoryNotificationControl won't retrieve deleted objects - c#

I'm using this search :
SearchRequest request = new SearchRequest("CN=Users,DC=xx,DC=xxx", "(objectclass=*)", SearchScope.OneLevel, new string[] {"isDeleted", "objectGUID", "uSNChanged"});
request.Controls.Add(new DirectoryNotificationControl());
IAsyncResult result = Connection.BeginSendRequest(
request,
PartialResultProcessing.ReturnPartialResultsAndNotifyCallback,
RunAsyncSearch, // Callback that processes responses
null
);
and it won't notify when user has been deleted. I also tried to add
request.Controls.Add(new ShowDeletedControl());
but it didn't help. I checked for tombstoneLifeTime (which is set to 180) in
CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,DC=xxx,DC=xxx
Weird thing is, that search from this tutorial returned only one result :
ldap_search_ext_s(ld, "<WKGUID=18E2EA80684F11D2B9AA00C04F79F805,DC=xxx,DC=xxx>", 2, "(objectclass=*)"), attrList, 0, svrCtrls, ClntCtrls, 6000, 10000 ,&msg) Getting 1 entries: Dn: CN=Deleted Objects,DC=xxx,DC=xxx
(18E2EA80684F11D2B9AA00C04F79F805 is a well known AD object GUID for CN=Deleted Objects)

I have provided LdapConnection from the example above with credentials of a user, that is a member of Administrators group on the server, where the desired Domain Controller is installed, but that was not enough. The code must be run under elevated rights, so running Visual Studio or the code "as administrator" fixed my isue. I also was able to view deleted objects via running ldp.exe with elevated rights.

Related

AWS Cognito - User pool xxxx does not exist

var client = new AmazonCognitoIdentityProviderClient("MYKEY", "MYSECRET", RegionEndpoint.USEast1);
var request = new AdminGetUserRequest();
request.Username = "USERNAME";
request.UserPoolId = "POOLID";
var user = client.AdminGetUserAsync(request).Result;
The key/secret are authenticating as a user with Administrator Access. For good measure, I've also given it the AmazonCognitoPowerUser policy.
The region endpoint is correct and the same as the one my user pool is in. The user pool Id is correct. The first part of the user pool ID matches the region.
I'm at a loss for where else this could possibly be going wrong. Any ideas?
Update 8/2/19
Manual CLI command:
PM> aws cognito-idp list-user-pools --region us-east-1 --max-results 10
{
"UserPools": []
}
The region is correct, so there must be some issue with permissions. Is there anything I could try tweaking on the pool, or other policies I may need to add to the user?
So, it looks like this is some sort of AWS glitch with the existing IAM user.
Having created a new user with exactly the same permissions, access works as intended both from CLI and the code in the original question.
Actually your configuration can be wrong , you downloaded awsconfiguration.json and it looks like same I know.. but this configuration can be wrong. When you examine the json you will see a field.. "CognitoUserPool": {PoolId, appclient id ..}
You need to open your user pool and create new client or control existing client information. Check your awsconfiguration.json again with this webpage's pool id, appclient id etc. Update your json... it will solve the problem.
I ran into this problem with the AWS CLI and it puzzled me too, but I learned that I needed to provide the profile name in the parameter list to get it to work. So it looked like this:
aws cognito-idp admin-get-user --profile dev-account ....
My profiles are stored on my Mac at cat ~/.aws/config| grep profile
The config file is created by an in-house custom script. This is the contents of what that file looks like.
[profile dev-account]
sso_start_url = https://yourcompanyname.awsapps.com/start#/
sso_region = us-east-1
sso_account_id = 1234567890
sso_role_name = PowerUserAccess
region = us-east-1
output = json
Also, in this folder is a "credentials" file that has some JSON for these variables: profile name, aws_access_key_id, aws_secret_access_key, aws_session_token, aws_expiration

LDAP search fails on server, not in Visual Studio

I'm creating a service to search for users in LDAP. This should be fairly straightforward and probably done a thousand times, but I cannot seem to break through properly. I thought I had it, but then I deployed this to IIS and it all fell apart.
The following is setup as environment variables:
ldapController
ldapPort
adminUsername 🡒 Definitely a different user than the error reports
adminPassword
baseDn
And read in through my Startup.Configure method.
EDIT I know they are available to IIS, because I returned them in a REST endpoint.
This is my code:
// Connect to LDAP
LdapConnection conn = new LdapConnection();
conn.Connect(ldapController, ldapPort);
conn.Bind(adminUsername, adminPassword);
// Run search
LdapSearchResults lsc = conn.Search(
baseDn,
LdapConnection.SCOPE_SUB,
lFilter,
new string[] { /* lots of attributes to fetch */ },
false
);
// List out entries
var entries = new List<UserDto>();
while (lsc.hasMore() && entries.Count < 10) {
LdapEntry ent = lsc.next(); // <--- THIS FAILS!
// ...
}
return entries;
As I said, when debugging this in visual studio, it all works fine. When deployed to IIS, the error is;
Login failed for user 'DOMAIN\IIS_SERVER$'
Why? The user specified in adminUsername should be the user used to login (through conn.Bind(adminUsername, adminPassword);), right? So why does it explode stating that the IIS user is the one doing the login?
EDIT I'm using Novell.Directory.Ldap.NETStandard
EDIT The 'user' specified in the error above, is actually NOT a user at all. It is the AD registered name of the computer running IIS... If that makes any difference at all.
UPDATE After consulting with colleagues, I set up a new application pool on IIS, and tried to run the application as a specified user instead of the default passthrough. Exactly the same error message regardless of which user I set.
Try going via Network credentials that allows you to specify domain:
var networkCredential = new NetworkCredential(userName, password, domain);
conn.Bind(networkCredential);
If that does not work, specify auth type basic (not sure that the default is) before the call to bind.
conn.AuthType = AuthType.Basic;

Unable to get some user account information in UWP app - In-premise active directory (Not Azure AD)

In a UWP app, I have enabled the User Account Information capability.
I need to get the username and the domain name (each of them separately) of the currently logged on user (The users are logged on with an in-premise Active Directory account - Not Azure AD).
For example, the user would log in to the Active Directory domain domain1 using the username user1. i.e. domain1\user1.
I am using the following code to try to get the required details:
IReadOnlyList<User> users = await User.FindAllAsync();
var user = users.FirstOrDefault();
// get domain
var data1 = await user.GetPropertyAsync(KnownUserProperties.DomainName);
string strDomainName = (string)data1;
// get username
var data2 = await user.GetPropertyAsync(KnownUserProperties.AccountName);
string strUserName = (string)data2;
Issues:
strDomainName returns domain1.com\user1. Why does this include the .com part for all our domains? On c# winforms applications we can easily get domain1\user1 without any issue.
strUserName returns an empty string. i.e. "". Why does this not return any value?
I also checked the following:
KnownUserProperties.FirstName returns an empty string. i.e. ""
KnownUserProperties.LastName returns an empty string. i.e. ""
KnownUserProperties.PrincipalName returns an empty string. i.e. ""
KnownUserProperties.ProviderName returns an empty string. i.e. ""
KnownUserProperties.GuestHost returns an empty string. i.e. ""
Is there anything else I need to enable similar to the User Account Information capability? Or are there any other permissions that need to be granted to the app to get this information?
I understand that I can get the value of strDomainName and perform string functions to get what I need. But I want to know if there is any way to get this information directly. Also curious why KnownUserProperties.AccountName and other properties listed above such as FirstName, LastName etc. just returns an empty string.
I am running the following version of Windows:
I have the following set as the Target version and Min Version:
To verify, I also tested with the UserInfo sample project by Microsoft from GitHub and I got the following output:
The following was automatically enabled in Settings > Privacy > Account Info.
TestApp is the app I tried with and User Info C# Sample is the sample app from GitHub:
Update:
After also enabling the Enterprise Authentication capability, KnownUserProperties.PrincipalName does return the expected value. i.e. user1#domain1.com.
However, other properties listed above such as FirstName, LastName etc. just returns an empty string and I am still unable to find any property that returns domain1\user1 (without the .com part)
The Information you are trying to access are not reliable, as they (as you mentioned) do not have to be set and also they can be restricted access to via privacy settings in general.
I had a similar problem and would advise you to use the UWP OneDrive API
using Microsoft.OneDrive.Sdk;
and then request wl.basic scope. This scope contains at least a reliable username.
public static async Task<bool> GetAuthenticatedClient()
{
string oneDriveConsumerBaseUrl = "https://api.onedrive.com/v1.0";
var scopes = new List<string>
{
"wl.signin",
"wl.basic",
};
Task authTask;
var onlineIdAuthProvider = new OnlineIdAuthenticationProvider(scopes.ToArray());
authTask = onlineIdAuthProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync();
oneDriveClient = new OneDriveClient(oneDriveConsumerBaseUrl, onlineIdAuthProvider);
AuthProvider = onlineIdAuthProvider;
try
{
await authTask;
if (!AuthProvider.IsAuthenticated)
{
return false;
}
}
catch (ServiceException exception)
{
// Swallow the auth exception but write message for debugging.
//Debug.WriteLine(exception.Error.Message);
return false;
}
return true;
}
As for the domain, I'm not sure, but you could try to access it via Environment.UserDomainName like described on MSDN or with Windows.Networking.Connectivity.NetworkInformation.GetHostNames() like described here.
I found another possible solution to this. If you are still debugging this locally or the app was already installed on the target machine, I could enable the capabality User Account Information but this was not propagated to the actual installed app:
when your search for your app name in the start menu and then right click the entry and select App settings you get something like this:
As soon as I enabled the highlighted option (basically it says 'Account information') it worked.

Why is my List.GetUserEffectivePermissions() method not working?

I'm developing a process in C# with the SharePoint 2013 Client Side Object Model. I need to retrieve the SharePoint List Permissions of a given user, that will be different than the user that is executing the code.
using SP = Microsoft.SharePoint.Client;
SP.ClientContext SpContext = new SP.ClientContext("SITEURL");
SP.Web SiteWeb = SpContext.Web;
SP.List Lst = SpContext.Web.Lists.GetByTitle("LIST");
var ClientUserEffPerms = Lst.GetUserEffectivePermissions(#"<domain>\<username>");
SpContext.Load(SiteWeb, S => S.EffectiveBasePermissions);
SpContext.Load(Lst, L => L.EffectiveBasePermissions);
SpContext.ExecuteQuery();
After this code executes, the ClientUserEffPerms.Value (BasePermissions) object does not represent the permissions of the given user correctly. The object isn't null, but it represents the user as having no permissions. The user has at minimum view and edit permissions and I can confirm this by viewing/editing List Items using the web browser as this user.
The code executing user has permission to enumerate permissions at both the Web and List level. I've confirmed this with the code below, both booleans resolve to true.
bool SvcUserHasSiteEnumPermsPerm = SiteWeb.EffectiveBasePermissions.Has(SP.PermissionKind.EnumeratePermissions);
bool SvcUserHasListEnumPermsPerm = Lst.EffectiveBasePermissions.Has(SP.PermissionKind.EnumeratePermissions);
Can anyone help me determine what is wrong with my GetUserEffectivePermissions() method?
When you call GetUserEffectivePermissions you need to pass in the full claims token version of the login name, which looks something like this:
i:0#.w|domain\user
You can get this by loading the LoginName property on a user object:
clientContext.Load(clientContext.Web.CurrentUser, i => i.LoginName);
clientContext.ExecuteQuery();
Of course, that's for the current user, so you'll need to acquire the user you actually want first.

Active Directory property "badPwdCount"

Problem:
We've upgraded the AD server from 2003 to 2008 and due to some "bad code", where developer has coded in such a way that, he directly casts "badPwdCount" property value to INT and it blows up because of NULL value conversion - NULL reference exception - NULL cannot be converted to INT.
Bigger problem:
We cannot do a deployment at this point because there are over 100 individual apps that depended on this change and we're looking for a least involved way of dealing with it for now.
Background:
Now the way this "badPwdCount" property works is, that when user logs on to the domain, it will get set to zero, otherwise it's NULL. The problem is that none of these users are ever going to log on interactively because they're external and we authenticate them via API and they cannot log in using the API either..
Question:
Does anyone know if this value is in the registry or somewhere, where I can get to it and set it to zero? Was also thinking of initiating a log in per user via a script, but wanted to gather other ideas too...
MSDN page for badPwdCount:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms675244(v=vs.85).aspx
Normally this would be easy, all you would need to do is update all the users in active directory and set the value to 0 if it is null. There are various ways you could do this, for example a script or code, or a bulk update tool.
In this case, badPwdCount is a special property that is not replicated (i.e. it is different for each domain controller) and so far as I can tell, there is no way to update it manually or by script, however, I think I have a solution for you.
You should be able to easily trigger a single failed login for every user in active directory against each domain controller, causing the value to be incremented.
Since you tagged your post with C#, here is some C# code that will do the trick for you:
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.ActiveDirectory;
...
using (Domain domain = Domain.GetComputerDomain())
{
foreach (DomainController domainController in domain.DomainControllers)
{
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domainController.Name))
using (UserPrincipal userPrincipal = new UserPrincipal(context))
using (PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal))
using (PrincipalSearchResult<Principal> results = searcher.FindAll())
{
foreach (UserPrincipal user in results.OfType<UserPrincipal>())
{
context.ValidateCredentials(user.SamAccountName, "THEREISNOWAYTHISISTHECORRECTPASSWORD");
}
}
}
}
PS. If this screws up your AD I take no responsibility for it!

Categories