Issue with Impersonation in Exchange Server 2010 - exchange-server

I'm trying to use impersonation in my application to connect to user mailboxes and add/remove appointments.
I created an account called "EWSAdmin" and ran the following EMS commands on them:
New-ManagementScope -Name:"MyEWSImpersonation" -RecipientRestrictionFilter
{memberofgroup -eq "cn=My User Container,DC=MyDomain,DC=local"}
New-ManagementRoleAssignment -Name:"MyEWSImpersonation" -Role:ApplicationImpersonation
-User:"EWSAdmin#MyDomain.local" -CustomRecipientWriteScope:"MyEWSImpersonation"
Just to confuse the issue, I called my scope EWSImpersonation, too.
When I try to connect to the user's mailbox to view an appointment (Using a third party DLL), I get the following error:
Throwing GeneralException e=The account does not have permission to
impersonate the requested user.
If anybody could help me diagnose this, I'd appreciate it.
Thanks
Nick

We ran into this issue with a different cause, I want to share it here because when searching for the error message this post and a post on TechNet come up, but not the KB Articles that eventually helped us solve the issue.
It turns out that there is a limit to the amount of requests any windows server can do to Active Directory, at some point the NetLogon service just runs out of Threads and all kinds of things start to happen. The process is explained in this blog post and this KB article and this KB article, the fix is pretty simple, increase the number of threads available through a simple change to a Registry key on every CAS server in the Exchange cluster.
The process is simple:
Start Registry Editor.
Locate the following registry subkey: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Netlogon\Parameters
Create the following registry entry:
Name: MaxConcurrentApi
Type: REG_DWORD
Value: Set the value to the larger number, which you tested (any number greater than the default value).
At a command prompt, run net stop netlogon, and then run net start netlogon.
Notes
The maximum value that can be configured depends on the operating system version and whether a hotfix is available.
The maximum configurable setting in Windows Server 2003 is 10.
The maximum configurable setting in Windows Server 2008 (without the hotfix in this article) is 10. With the hotfix, the maximum is 150.
The maximum configurable setting in Windows Server 2008 R2 (without the hotfix in this article) is 10. With the hotfix, the maximum is 150.
If you decide to increase the MaxConcurrentApivalue to greater than 10, the load and the performance of the desired setting should be tested in a nonproduction environment before you implement in production. This is recommended to make sure that increasing this value does not cause other resource bottlenecks.

I know almost nothing about "admin" side of setting up impersonation for EWS but maybe you can take a look at this article and compare your actions with what this guy did to make it work
http://www.thesoftwaregorilla.com/2010/06/exchange-web-services-example-part-3-exchange-impersonation/
in my company admin setup impersonation according to msdn and it works for me so I presume it can't be so hard and probably you missed some steps or maybe that 3rd party dll needs some additional magic.
link to msdn article in case you didn't know it: http://msdn.microsoft.com/en-us/library/bb204095.aspx

It would be nice to have an example for E2010 as it is not as easy as 2007.
Here is an example to creating EWS impersonation for a group. Any member of the group would be impersonated by the service account. Just add additional members to the group as requirements demand. Two steps...create the New Management scope and then the Role assignment.
New-ManagementScope “Scope Name” -RecipientRestrictionFilter {(MemberOfGroup -eq 'CN=group name,CN=Users,DC=Contoso,DC=com')}
New-ManagementRoleAssignment -Name “EWS ROLE NAME” -Role applicationimpersonation -User Domain\Service Account -CustomRecipientWriteScope “Scope Name”
Where “Scope Name” is the management scope created in step one.

Related

setup AppPool on IIs 10, keySet does not exist

I am running a windows 2016 server, we are running IIs 10 on it and i need to be able to assert if there is an AppPool setup before i deploy a website. If it doesn't exist i need setup the AppPool with a specific user and password.
All of this is done using a release agent through Azure Devops.
The agent is running as a NON-ADMIN, and i all accounts involved are running as NON-ADMIN. I have no intention at all to run any admin accounts, for security reasons i want to give least privildges to all accounts involved.
when i try to set up a AppPool using appcmd.exe i get the error msg:
KeySet does not exist.
When running everything as admin it works (and i have absolutely no intention in running any of this as admin).
What i have tried:
i have added the non-admin account to the IIS_IUSRS group.
Made sure that the user has read permissions to the file: 76944fb33636aeddb9590521c2e8815a_GUID in the %ALLUSERSPROFILE%\Microsoft\Crypto\RSA\MachineKeys folder.
i have tried everything here: Error when you change the identity of an application pool by using IIS Manager from a remote computer
anyone that actually knows the cause of this problem?
UPDATE:
Microsoft clearly recommends that agents should be run using service accounts, which i am doing and i have no interest in giving build agents administrative rights to 1000s of servers when they clearly don't need that kind of powers actually. I want to restrict their powers to only be allowed to do what they need to do. I can't believe that giving everything admin is apparently the norm.
After a lot of googling, and i mean A LOT. I managed to solve this. And let me say, that it baffles me that "least privileged accounts" is not common practice in the Microsoft and windows world.
I found this excellent post by InfoSecMike locking down azure devops pipelines.
And we both have the exact same requirements and opinions on this topic.
You CLEARLY don't need admin rights to update IIs configurations (because that would be insane, right!?). The IIs configuration API does not care what rights you have, what you do need is access to certain files. But this is not documented. Microsoft themselves, just for simplicity, tells you that you need to be admin, and buries all the details really deep in documentation when this should be best practice. Also what amazes me is that no one questions it.
What you need is the following:
full access to C:\Windows\System32\inetsrv\Config
full acccess to C:\inetpub
read access to three keys in C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys\
6de9cb26d2b98c01ec4e9e8b34824aa2_GUID (iisConfigurationKey)
d6d986f09a1ee04e24c949879fdb506c_GUID (NetFrameworkConfigurationKey)
76944fb33636aeddb9590521c2e8815a_GUID (iisWasKey)
The 2 first bullet points can be obtained if you make sure your service account is a member of the group IIS_IUSRS.
This group will not give you access to the keys. You need to manually give read permissions to these 3 keys to the agent user.
If you don't give access to these keys you will get the obscure error message
Keyset does not exist ( exception from HRESULT : 0x8009000D)
Which is an incorrect error if you ask me as it should be an IllegalAccessException with proper reason telling you that you don't have access to read the key because the keys are there, they do exist (nice code microsoft, maybe you should open source this so we can fix).
I'll leave with this quote from infosecmike.
The goal was to lock down the permissions of the Azure Pipeline Agent {...}. I started Googling, pretty sure I would find a way to achieve this goal. I didn’t. It’s surprising to not find an answer about this. It seems like the principle of least privilege does not apply anymore in a devops world.
This is why i prefer Linux over Windows. This is a simple task there.

How to get EVERY user token on a PC for SHGetKnownFolderPath?

I'm working on a System Service project with SYSTEM privilege (cleaning utility)... It does not interactive with any user interface.
My goal is to check files in "Desktop" and "AppData" folders for any user that exists on the PC.
I'm using NetUserEnum() to get the user list on the PC. Then I want to get the path of each user's Desktop and AppData with SHGetKnownFolderPath(), but I can't find a way to get each user's access token for SHGetKnownFolderPath(). Without a token defined in SHGetKnownFolderPath(), it returns the path for SYSTEM and not specific users.
Q1. How can I get the token of each user for SHGetKnownFolderPath()?
Q2. If no answer for Q1, is there any documented way to get the desktop & appdata path of each user in the PC?
I understand this can be achieved with dirty way ---> Registry key with some string replacement. However, the Registry key method is undocumented, which may easily break in future updates to Windows.
Edit Update:
#RaymondChen Thanks for pointing out that some user profiles may not exist. Also,
About Q1 : #Remy Lebeau provides a solution with LogonUser/Ex(),login to each user with their credentials,might be the only answer that fits the need of Q1.
About Q2 : There might have no documented way to achieve this. The only method might have to stick with Windows Registry (Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders) , as #Remy Lebeau and #Olaf Hess said. I tried to dig more information on Microsoft Community Forum and I got Microsoft would never allow access other users' profile with their native API for security reason. They do not provide APIs that can possibly violate the security rules. Each user profile can only access by its credentials.
btw, I totally understand that "Cleaning utility" aka "Windows-breaking tool", especially when the tool is not being well codded(ex. compatibility problem). For the sake of avoiding to make it become a totally Windows-Destroyer, I tried to use more documented API as possible.
For Windows Vista with SP1 / Server 2008 and better you can query the existing user profiles using the WMI class Win32_UserProfile. This allows you to retrieve the profile path and check whether it is a local or roaming profile and to get status information. The rest (retrieving the paths to APPDATA, DESKTOP, etc.) is likely going to involve reading values straight from the registry (HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders or HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders).

Chef::Exceptions::WindowsNotAdmin: can not get the security information due to missing Administrator privileges

We were trying to deliver a solution to manage a Windows 2012 server for a client using Chef, but unfortunately chef-client run failed with Chef::Exceptions::WindowsNotAdmin: can not get the security information for <some_file> due to missing Administrator privileges exception.
This was a bit weird as we have confirmed that the domain account we used to remotely manage the server is a member of the Administrators group. And we were able to use it to manage other servers within the same domain. Besides, when we connected to the server using the domain account via Remote Desktop, started PowerShell as an administrator and initiated a chef-client run, it failed with the same exception.
Running below commands reveals that the domain account is indeed a member of the Administrators group. This can be verified by the SID of the group.
Get-WmiObject -Class Win32_UserAccount
Get-WmiObject -Class Win32_Group
[System.Security.Principal.WindowsIdentity]::GetCurrent().Groups
Not sure what settings on the server could have caused this.
With insights provided by this thread, further digging into the code of Chef reveals that a win32 function GetNamedSecurityInfoW gets called here to determine the security information of an object (file, folder etc.). This occurs during cookbook installation where some resource files or gems need to be created on the endpoint server.
Firstly an empty file will be created, after that the file content will be updated atomically if that is an option. During file content update, the file’s security access control list needs to be checked by the function GetNamedSecurityInfoW. To call this function, the logged-on user needs to have a privilege SE_SECURITY_NAME. Chef itself also tries to handle this by adding this privilege before calling the function and revert it after the function call, but this is not always guaranteed. System settings seem to prevail.
We hacked Chef code a bit to try to print out the output of the function call on GetNamedSecurityInfoW, and it was a status code 1314, indicating a required privilege is not held by the user.
We tried to run whoami /priv on the server and found that SeSecurityPrivilege privilege is not found in the list. Below is just a sample output on a normal Windows server.
Privilege Name Description State
========================================================================
SeLockMemoryPrivilege Lock pages in memory Disabled
SeIncreaseQuotaPrivilege Adjust memory quotas for a process Disabled
SeSecurityPrivilege Manage auditing and security log Disabled
...
Note that the state column only indicates whether a privilege is being used by the user. It's existence indicates whether the user has it or not.
After adding back this privilege to the domain account, i.e. set the security setting of Manage auditing and security log to Administrators group in the Local Securtiy Policy editor, and rebooting the server, chef-client run became successful.
It seems that Chef is heavily using win32 API functions to manage Windows nodes. And these API functions seem to need various privileges to run. It's a bit strange that Chef rescued all win32 API errors and just propagated the Chef::Exceptions::WindowsNotAdmin to chef-client run log, as indicated here. It would be good to actually parse the error a bit and provide some more useful information.

View the active remote desktop connection on a given computer

I am looking for a tool to know if a given computer on the local network is being remotely accessed by a user or not and ideally I'd like to know who that user is. In my company, we share virtual machines and we keep have to ask members in the team if they use any remote computer. I'd like to have some kind of dashboard that can tell me what computer is being used, and what computer is free.
I am happy to use any kind of commercial solution that would require the install of services on each of the machines that need to be monitored or things like that.
The below is made easier if you're querying from a Windows client joined to the same domain as the system you are querying, and may require certain rights above and beyond a standard domain user. If you run into authentication/permission issues, that would be the first thing I'd check.
There is a tool available at least as far back as Windows XP called "qwinsta". Later versions of Windows have both qwinsta and "query session".
qwinsta /server:computer01
SESSIONNAME USERNAME ID STATE TYPE DEVICE
console 0 Conn wdcon
rdp-tcp 65536 Listen rdpwd
administrator 2 Disc rdpwd
That shows user "administrator" logged in but disconnected. Since in this example computer01 is a Windows Server 2003 system with the default "administration" RDP license, there's a second session listening for someone to connect.
Running the same command again after connecting to that previously disconnected session looks like this:
SESSIONNAME USERNAME ID STATE TYPE DEVICE
[unchanged output removed]
rdp-tcp#25 administrator 2 Active rdpwd
This is enough to answer "is someone currently active via RDP", and if you're using individual usernames, it should answer the "who" as well. If you're all using "testuser" or "administrator" or something, you'll probably want to know the answer to "from what client", and that is not given above.
The above gives a quick basic answer without needing additional tools. For more detailed information, you might look at the cassia library or PSTerminalServices (built on cassia). See some of the answers in this question for more detail.
My first thought on this was to use Sysinternals tools such as PsLoggedOn or LogonSessions. I then found reference to the previously-unknown-to-me qwinsta and rwinsta tools in this blog post from 2003.
You can use a PSModule named PSRdSessions, this module provide some simple funtions
sample of use
Get-RdSession -ComputerName Server01.domain.xyz # return [Cassia.Impl.TerminalServicesSession]
for return [hashtable]
Get-RdSession -ComputerName Server01.domain.xyz | Convert-RdSession # return
for return [pscustomobject]
Get-RdSession -ComputerName Server01.domain.xyz | Convert-RdSession | %{[pscustomobject]$_}

script for Local Security Policy

I'm looking for some guidance on how to automat applying a set of permissions withn the local security policy to a multiple users on multiple servers.
For example, via a script, I want to apply "act as part of the operating system" and "adjust memoroy quotas for a process" to user TEST1 and TEST2.
Any feedback on how to get started would be appreciated. thanks!
From a command line, the Microsoft-provided solution is secedit. AppDeploy is a great resource for packaging in general, and they have a good page on secedit here: http://www.osdeploy.com/tips/detail.asp?id=23
In short, change your policies using the Local Security Settings MMC snap-in, then export with secedit as in this page (http://www.webservertalk.com/message534715.html -- also assuming this computer isn't a member of a domain), then import as usual.
Is this machine domain joined? If so, you'll need to make sure no domain policies are applied. Otherwise the domain policies will be exported along with the local ones.
Simpler answer here:
Scripting Local Security Policy
Use ntrights.exe from the Windows 2003 Resource Kit.
However, this doesn't seem to help with the "adjust memory quotas for a process" right.

Resources