Why Search-ADAccount is giving different results when Run as Administrator - powershell

I am connected as Domain Admin to my DC. When I run the following command in a PowerShell windows, it finds 2 users
Search-ADAccount -UsersOnly -AccountInactive -TimeSpan 90.00:00:00 -SearchBase "OU=myOu,DC=myDomain,DC=local"
| Where {$_.enabled} | Sort-Object -Property LastLogonDate
When I run the same command in a PowerShell Run as Administrator, it finds 28 users
it looks like if the PowerShell console is started as Administrator, it can affect the cmdlet's ability to read certain Object and I do not understand why.
Has someone has seen such behavior and can explain why please?

You can temporarily disable User Account Control (UAC) and then run your PowerShell command which should return the expected results even if you don't invoke Run as Administrator. That's your quick answer.
The reason is because UAC is not giving you the admin token which you think you already have (but don't) when you run PowerShell as a non-administrator (even though you are logged into the DC as a domain administrator). When UAC is bypassed, such as (1) when it's disabled, (2) has its security level lowered enough, or (3) you invoke Run as Administrator, you have all the rights to read all the properties in AD and all the expected data returns. But in this case PowerShell will not show values for properties when there is no admin token attached because UAC is enabled on the DC. It will simply show no values/data (as opposed to throwing an error). There's a Reddit thread on this here.

Related

O365 Set-Mailbox with DeliverToMailboxAndForward

Background
Working in a small O365 environment that recently upgraded from E3 to E5.
Issue
The audit log shows that a user enabled DeliverToMailboxAndForward on their mailbox with the Set-Mailbox operation.
Questions
Is PowerShell the only way to issue Set-Mailbox or can it be done
through the GUI somehow?
Is there a way to disable/prevent users from settings this (i.e. do the end users have too many permissions)?
When I query Get-Mailbox user | fl name,forwardingSMTPAddress,delivertomailboxandforward the ForwardingSmtpAddress is empty and DeliverToMailboxAndForward is False. Is this the only way to ensure the action is disabled? Does the disable action appear in any event/audit log?
Is PowerShell the only way to issue Set-Mailbox or can it be done through the GUI somehow?
As an Exchange admin, you can use the Exchange Admin Center (EAC) to go to the Mailbox properties -> Mailbox Features -> Under Mail Flow, select View details -> Check the Enable forwarding, and Browse to the recipient.
Configure email forwarding for a mailbox
Is there a way to disable/prevent users from settings this (i.e. do
the end users have too many permissions)?
From a user perspective they can forward using the Outlook GUI:
Forward email from Office 365 to another email account
When I query Get-Mailbox user | fl name,forwardingSMTPAddress,delivertomailboxandforward the
ForwardingSmtpAddress is empty and DeliverToMailboxAndForward is
False. Is this the only way to ensure the action is disabled? Does the
disable action appear in any event/audit log?
You can use either the PowerShell script to query, or navigate through ECA console to verify. The disable action should appear in the audit if it is set up.
On to the issue,
The audit log shows that a user enabled DeliverToMailboxAndForward on
their mailbox with the Set-Mailbox operation.
Typically most users don't have access to the Exchange Management Console, and the ability to run PowerShell operations. That makes this audit entry "seem" odd. But then digging through the docs I come up to this entry:
Cmdlets that are run directly in the Exchange Management Shell are
audited. In addition, operations performed using the Exchange admin
center (EAC) are also logged because those operations run cmdlets in
the background.
Administrator audit logging in Exchange Server
So what you are likely seeing is an entry that is a GUI running a cmdlet in the background, without the user actually having direct Exchange Management Shell access. As for permissions, I'm not sure about explicit permissions to deny this specific action without denying a lot of other stuff (i.e. it's like denying permissions to forward messages) unless you have a business need to do this.
This question may get a better response in an Office 365 forum, but I'll try to answer your questions:
The GUI/Web UI is executing PowerShell commands on the back end when users change their configuration. In order to be allowed to change a setting in the GUI, the same permission needs to exist for the PowerShell cmdlets.
This permissions is a default included in the MyBaseOptions management role for Office 365 mailbox users. This role includes many other permissions which users require to manage their own mailbox, such as permissions to create inbox rules or update their picture. You can see all the actions included in this role with this command:
Get-ManagementRole -Identity mybaseoptions |Select -Expand roleEntries
The easiest way to audit current mailbox settings is likely running the command as you have done. A more efficient way to query all your mailboxes for just those with specific settings is to use the -Filter parameter on the Get-Mailbox command like this:
Get-Mailbox -Filter {DeliverToMailboxAndForward -eq $true -and ForwardingSMTPAddress -ne $null}
I hope that helps answer your questions!

Get-EventLog not parsing Message when run by SYSTEM user

Problem
I am trying to schedule a job that monitors events on remote machines.
I wrote the script based on the Get-EventLog command and it works properly when run by my account. But when I run the Get-EventLog as SYSTEM user, the .Message attribute of the returned objects shows the following error:
The description for Event ID '4724' in Source 'Microsoft-Windows-Security-Auditing' cannot be found. The local computer may not have the necessary registry information or message DLL files to display the message, or you may not have permission to access them. The following information is part of the event: {somedata}
When I use the Get-WinEvent command as SYSTEM user, the problem does not appear and the .Message part displays properly.
I would stick with Get-WinEvent, especially since the data is much easier to parse (thanks to the ToXML() method), but the Get-EventLog happens to be terribly faster :(
Question
Does anyone have any idea why the Get-EventLog fails to render .Message when run by SYSTEM user and perhaps how to fix it?
To avoid obvious answers:
the COMPUTER$ account is member of DOMAIN\Event Log Readers group,
the COMPUTER$ account does have the read privileges over the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Security on remote machines,
obviously, the registry entries for Microsoft-Windows-Security-Auditing and related DLL's are identical on both the source and target computers.
Try:
Get-WinEvent -LogName “Microsoft-Windows-Security-Auditing” | where ID -eq 4724 | select-object -ExpandProperty Message

Get user permissions to folder including indirect permissions through AD and local groups

I want to check whether a given Active Directory user (specified by username and domain) has read/(write) permissions on a given folder. And this unrelated to having them granted directly by user name or indirectly by some group membership. However I've been googling like 5 hours by now to no avail.
I understand, that Get-Acl Cmdlet is used to read folder permissions. Most likely the user is member of some group, that indirectly grants it permissions.
So my idea was to just match the output of
(Get-Acl <Folder>).Access | ft
against the group membership of the user.
I collect the group Information using the command
Get-ADPrincipalGroupMembership "<Username>" | select name
but found out, that this features an entirely different set of group names. I assumed, that the groups outputted by Get-Acl are local ones, while the other ones were AD-sided groups.
I found the command whoami /groups, that prints all groups, but only for the currently logged in user.
After quite some additional time I figured out the command (based on .NET):
(New-Object Security.Principal.WindowsIdentity -ArgumentList #(,"<User#fullDomain.com>")).Claims | select Value
This however just prints SIDs, while
(Get-Acl <Folder>).Access | ft
displays some human friendly output like "NT SERVICE\TrustedInstaller" and such.
I believe I'm pretty close, but I just can't get it to work.
On another note: Does this really have to be that complicated?
Other solutions I found only work based on direct user permissions but do not check group permissions.
Oh and one thing: Everything has to run on PowerShell 4.0 on Windows Server 2012 R2 and the PowerShell script will be running locally. No NuGet packages or anything requiring an Internet connection are allowed.

Powershell: Unable to use the -Recursive switch for AD group membership

I have (what I think is) an odd problem.
I have two domain admin accounts and one domain controller (for the purpose of this question). Here is the scenario:
Admin1 RDPs to dc01 and runs the Powershell command (see command below), and it succeeds
Admin2 RDPs to dc01 and runs the Powershell command (see command below), and it fails (see error below).
In both cases, we are entering the credentials of admin1 when prompted by Get-Credential
Command:
Get-ADGroupMember administrators -Credential (Get-Credential) -Server dc01 -Recursive
Error:
Get-ADGroupMember : There is no such object on the server
If I remove the -Recursive parameter, then the command works for both admins (again, using the credentials of admin1). If I open ADUC as admin1, then look at the members of Administrators, I can see all members, opening sub-groups without issue.
What in the world is going on? Thanks.
Well, looks like it was a permissions issue. I added the service account to Enterprise Admins and the failure stopped. I have no idea which object is causing the failure.

SID for Administrators group doesn't show in a member account

Now, before I start, I will let you in on a secret: this is on a Domain Controller.*
*The above statement is stricken due to irrelevance as the only significant change that occurs to the Local Administrator account and the Local Administrator Group (within the context and scope of this question) is minimal and doesn't alter the outcome enough to require differentiation.
I didn't have this kind of trouble on any of the other servers and I am willing to bet that the reason behind it is because it is on a DC.*
*Same reason as stated above. The accepted answer explains the inconsistency and was an oversight on my part, not the architecture (read features) of Windows Security or Domain Controllers.
I have been playing around with a few ideas on how to check if a script has been called from an account that is either the local Administrator or, at the very least, called by an account that is part of the Local Administrators group.
I have renamed the local Admin account, however, I know that I can see if the script has been called by local Admin account by typing:
(New-Object System.Security.Principal.NTAccount('reserved')).Translate([System.Security.Principal.SecurityIdentifier]).Value
and I can see if the SID ends in -500.
The problem occurs when I run a condition to see if the calling account is part of the Administrators group (which is a larger scope) by typing:
PS> [bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).Groups -match "S-1-5-32-544")
PS> False
A quick check to see what account it was using:
PS> $env:username
PS> reserved
or the needlessly complicated way (though I prefer it sometimes):
PS> Write-Host ((Get-WmiObject Win32_Account | ?{$_.SID.Substring($_.SID.Length-4,4) -eq '-500'}).Caption).Split("\",2)[1] -fore GREEN
PS> reserved
and I even type:
PS> net user reserved
where it tells me Local Group Memberships *Administrators.
I pull up ADUC (dsa.msc) and I look in the Builtin container and double-click on the Administrators group. I select the Members tag and lo, and behold, reserved is actually a member!
So, a recap:
By typing net user reserved, I was able to verify it was part of the Local Administrators group
I looked in ADUC and verified reserved was a member of the builtin Administrators group
I ensured reserved was indeed the Local Administrator account by verifying the SID started with S-1-5... and ended with ...-500
To take it a step further, I made sure the SID matched the Active Directory Group named "Administrators" by typing Get-ADGroup -Identity "Administrators". I then typed Get-ADGroupMember -Identity "Administrators" and made sure reserved was listed (it was AND the SID matched!).
When I check to see if the well-known Administrators Group SID is found in the Groups of that account (by getting the current Windows Identity), it says that it isn't.
What gives?
Why do I get every indication that it actually is a member of the Local Administrators group but that SID isn't found in the account's groups?
When a computer is promoted to a domain controller, there are no more local users or groups on the machine. Member computers have local users and groups, and can also use domain users and groups for authentication, but on a DC, there are only domain objects.
See also: https://serverfault.com/a/264327/236470
I happened to stumble across something and I realized the answer to this question. For the sake of those that come here looking for assistance, here is the answer to my question:
Very simply--in regards to Powershell--if the Administrator Group SID (S-1-5-32-544) does not show up in the Groups of the user, that is a first-line indication that the script is not running with Administrative credentials.
For example, when I type out:
([Security.Principal.WindowsIdentity]::GetCurrent()).Groups
and I do not see the Administrator Group SID listed even though I know for a fact that the account I am signed into is a member of the Administrator Group, it means the current Powershell process does not have Administrative credentials.
If you click Run As Administrator and type the same as above, you will see that it lists the Administrator Group SID in Groups.
The reason why I was experiencing the inconsistency is simply because I was not running the Powershell process as an Administrator.
So, in short, there are a few ways you can check to verify if your current Powershell session has Administrator credentials. The first one is found in countless websites around the internet and is very common (I did not write this one):
$myWindowsID = [Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal = New-Object Security.Principal.WindowsPrincipal($myWindowsID)
$adminRole = [Security.Principal.WindowsBuiltInRole]::Administrator
if($myWindowsPrincipal.IsInRole($adminRole)) {
\\ TODO: Process is running as Administrator
Clear-Host
} else {
$newProcess = New-Object System.Diagnostics.ProcessStartInfo "Powershell"
$newProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"
$newProcess.Verb = "runas"
[System.Diagnostics.Process]::Start($newProcess)
exit
}
Here is another way (I did write this one):
[Security.Principal.WindowsIdentity]::GetCurrent() | %{
if($_.Groups -contains "S-1-5-32-544") {
\\ TODO: Process is running as Administrator
Clear-Host
} else {
Start Powershell -ArgumentList "& '$MyInvocation.MyCommand.Path'" -Verb runas
exit
}
}
# The Foreach-Object (%) could be replaced with another pipeline filter
I see a lot of people asking this question and because of Powershell appealing to many Systems Administrator (especially ones without a background in programming), I really think this will come in handy for others down the line.