Double hop issue from appserver to sqlinstance - kerberos

We have released a change that makes a windows console application authenticate with an ad-user (trusted connection = yes) instead of sql-user.
This has caused problems starting the application from System Center Orchestrator via Powershell due to double jump issues.
Orchestrator -> Appserver -> SQLServer
Powershell from Orchestrator:
Invoke-Command -ComputerName Appserver -ScriptBlock {
cd 'D:\Program Files\Application\'
.\Application.exe }
Errormsg:
"Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'. 'SELECT * FROM Globals"
The aduser running the script is local admin on all three servers and sa on the sql-instance.
The solution I tested, that works when double jumping between SQL servers, is to set attributes msDS-AllowedToDelegateTo and UserAccountControl.
Set-adcomputer -Identity Appserver -Add #{'msDS-AllowedToDelegateTo'=#(
'MSSQLSvc/SQLServer.Domain.local',
'MSSQLSvc/SQLServer.Domain.local:1433',
'MSSQLSvc/SQLServer.Domain.local:INSTANCENAME'
)}
Set-adcomputer -Identity Appserver -Replace #{UserAccountControl= 4096}
This however does not make a difference in this case.
Does anyone know a solution to this problem?

Related

How to start a process on remote computer using powershell WMI?

We are upgrading our servers and need to stop our application before we perform update and then start it back again.
I was reading online about this and most of the links talk about remoting but some of the machines don't have PSRemoting enabled and therefore I need to stick to using wmi.
Would appreciate some pointers on this ?
To terminate the process I am using something like below:
$processes=Get-WmiObject -Class Win32_Process -ComputerName $Address -Filter "name='$ProcessName'"
foreach ($process in $processes)
{
$returnval = $process.terminate()
$processid = $process.handle
if($returnval.returnvalue -eq 0) {
write-host "The process $ProcessName `($processid`) terminated successfully"
}
else {
write-host "The process $ProcessName `($processid`) termination has some problems"
}
}
You don't say what OS and PS version(s) you are trying to deal with.
You are not saying what or if you are having issues with what you posted.
Even using only WMI, you still must have Windows WMI properly configured to do this as well as know Windows is not out of the boxed configured to let you what you are after without making all the proper WinRM, WMI and firewall manual configs.
It's far simpler just to enable PSRemoting via GPO.
Otherwise, you will need tp look toward maybe winrs.exe or MS SysInternals psexec.
winrs
Windows remote Management allows you to manage and execute programs remotely.
PsExec v2.2
Also back to my what OS and PowerShell version you are using. There is the
Invoke-Wmi​Method
Which can lead to stuff like this ---
Invoke-WmiMethod -ComputerName $TargetMachine -Namespace root\cimv2 -Class Win32_Process..."

Powershell "screen" - keep the processes running even the connection is dropped?

I'm using enter-pssession to run scripts on remote servers. So I can login remotely to the servers. Run commands interactively, close the powershell console and later I can reattach the session and check the commands outputs.
Is there a Linux screen like functionality in powershell? I cannot use Windows remote desktop to connect the servers.
You can use Invoke-Command with -InDisconnectedSession, it will start session in asynchronous mode. After you can connect to this session, take data from it, etc. You can read more about this here.
You can create session, disconnect from session, connect back to it.
May be useful for you: New-PSSessionOption with -IdleTimeout.
-IdleTimeout:
Determines how long the session stays open if the remote computer does not receive any communication from the local computer. This includes the heartbeat signal. When the interval expires, the session closes. MSDN Link
I have recently run into double-hop issues with using PSSessions. What I did to work around that is to create a Session Configuration on the remote server that uses the -RunAs parameter to set the credentials that I need the commands on the remote server to be executed as. Then you connect to that session configuration on the remote server, and things should work as expected.
$MyCreds = Get-Credential ''
Invoke-Command -ScriptBlock {
Set-PSSessionConfiguration -Name "My Remote Config" -RunAsCredential $using:MyCreds -Force
} -ComputerName Server01
Then once the session configuration exists I can start a session using that config, and the whole double hop issue is null and void.
Now, mind you I do add some additional security, so that other people cannot use my session config, since that config has my credentials cached on the server (encrypted), and if they used that config they could do whatever they wanted as me. So to accomplish that I get my domain account SID, generate a SDDL line, and restrict access to the Session Config to only my account.
$Searcher = [adsisearcher]"(&(sAMAccountName=$($Creds.UserName.Split('\')[1]))(objectClass=user))"
$Results=$Searcher.FindOne().GetDirectoryEntry()
$MySID = new-object System.Security.Principal.SecurityIdentifier($Results.objectSid.value,0)|% value
$SDDL = "O:NSG:BAD:P(A;;GR;;;BA)(A;;GR;;;IU)(A;;GA;;;$MySID)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)"
$FQDN = $Server.ServerName,$Server.Forest -join '.'
$MySessionName = "DoubleHop-{0}" -f $MyCreds.UserName.Split('\')[1]
Invoke-Command -ScriptBlock {
Register-PSSessionConfiguration -Name $using:MySessionName -RunAsCredential $using:MyCreds -Force -SecurityDescriptorSddl $using:SDDL
} -ComputerName $FQDN -ea 4

How to set share permissions on a remote share with Powershell?

I need to set the share permissions of a remote share from a Powershell 4 script. I've looked at this page, specifically the command Grant-SmbShareAccess but that cmdlet sets permissions on local shares, I would love to have seen a -ComputerName parameter but, alas, there isn't one.
I want to do something like: Grant-SmbShareAccess -ComputerName MYREMOTESERVER -Name <share_name> -AccountName <domain_account> -AccessRight Full
Any ideas on how to do this? My remote server could be a Windows Server or a NetApp vFiler.
EDIT
I tried Matt's suggestion of Invoke-Command in the comments against a NetApp vFiler and got this error:
Connecting to remote server MYREMOTESERVER failed with the following error message : The client cannot connect to the destination specified in the request. Verify that the service on the destination is running and is accepting requests. Consult the logs and documentation for the WS-Management service running on the destination, most commonly IIS or WinRM. If the destination is the WinRM service, run the following command on the destination to analyze and configure the WinRM service: "winrm quickconfig".
Changing the security of the share in Windows Explorer works fine.
Grant-SmbShareAccess is a CDXML command, which means that it uses CIM. As you've already noticed, it should only work on a Windows system running at least PSv3 (in this case the WMI class used only exists on Windows 8 and Server 2012 or higher).
There may be other ways to do this against a non-Windows server, but I would try the PowerShell Access Control Module:
$SharePath = "\\ServerName\ShareName"
$Principal = <account name here>
# Add permission to $Principal (-Force will suppress the prompt)
Get-SecurityDescriptor -Path $SharePath -ObjectType LMShare |
Add-AccessControlEntry -Principal $Principal -LogicalShareRights FullControl -Apply #-Force
# Verify:
Get-SecurityDescriptor -Path $SharePath -ObjectType LMShare |
Get-AccessControlEntry
I honestly don't know if this will work since I've only tested it against Windows servers and I don't deal with share permissions very often. Try it out, and if it works, I'll take this part out of the answer.
For Windows Server SMB shares, use the -CimSession parameter.
For non-Windows SMB shares, I would not expect the Windows SMB administration cmdlets to work with them.
The Netapp Powershell toolkit will help with this. Once installed you can import the module into your script, and manage your shares. Here is a rough example that connects to a filer, prompts for a sharename, then configures that share with some default permissions:
# Import the Netapp Powershell Module
import-module dataontap
# Connect to the filer
connect-nacontroller *filername*
# Get the sharename
$sharename = Read-Host -Prompt 'Enter the share you want to configure'
# Configure the CIFS Permissions
Set-NaCifsShareAcl $sharename "Authenticated users" -AccessRights "Change"
Set-NaCifsShareAcl $sharename filername\administrators -AccessRights "Full Control"
Set-NaCifsShareAcl $sharename domain\somegroup -AccessRights "Full Control"
Remove-NaCifsShareAcl $sharename everyone

powershell script - different behavior after start with windows scheduler

I have this script to check if there is mapped disk on remote server. When I run it in command line, it works perfectly, from PowerGUI and ISE it works perfectly, but when I shedule it in Windows task scheduler, I get a mail message (mail sending part of script is not included), that disk is not mapped - the "else" is executed in spite of disk is mapped.
if(Invoke-Command -ComputerName sdebt -ScriptBlock { Get-WmiObject win32_logicaldisk -ComputerName sdebt -Filter "DeviceID = 'L:'"}) {
Write-Host -ForegroundColor Green "L: is OK"} else {
Write-Host -ForegroundColor Magenta "L: is NOT OK"
$subject = "CHYBA: Disk L is not mapped"
$body += "Disk L is not mapped `r" }
Thank you.
Probably is related with permissions.
When you run it from your commandline/ISE/PowerGUI you are using your credentials
When you run it from schedule task by default you run it with system credentials
If I were you I would:
Try running it with your credentials to see if this make a difference.
Try running it with highest privileges
If after 1) and 2) still fails at least you know for sure that is not a permission issue :-)

PowerShell 2.0: Accessing Windows Shares during a Remote Session

I am having trouble accessing a shared network location while within a PowerShell remote session.
From the PowerShell prompt, I enter a new session:
Enter-PSSession server1
The session is properly created and entered. I then attempt to list the contents of the share:
dir \\server2\share1
The response is this error:
Get-ChildItem : Cannot find path '\\server2\share1' because it does not exist.
However, if I remote desktop into server1, bring up PowerShell, and execute the very same dir command, the contents are correctly listed.
I've tried various things using credentials, but that doesn't seem to fix it. I've also confirmed via the "whoami" command that I have the same identity in both examples.
What would cause this?
If you can't use credential delegation as mentioned above, you can mount (or just authenticate as below) the remote share in the remote session using explicit credentials, e.g.
[server1] ps> net use \\server2\share * /user:username
(prompts for password)
[server1] ps> dir \\server2\share
(listing)
This problem has nothing to do with powershell per-se; you are trying to replay your local credentials in a remote session to a third location and falling foul of the NTLM "double hop" limitation.
Read the section "Credential Delegation"
Here - Credit to Keith Hill
and perform the steps if you have not already done so.
Another option is kerberos resource delegation
eg:
$server_name = "my-server" $servers = #(get-adcomputer -identity $server_name)
$target = "target-server" $tgt_srv = get-adcomputer -identity $target
Set-ADComputer -Identity $to_delegate -PrincipalsAllowedToDelegateToAccount $servers