User home folder points to SYSTEM32 folder after runas - windows

I have a problem running runas /USER:testuser cmd or runas /USER:testuser powershell:
If testuser has opened RDP session, %HOMEPATH% points to \Users\testuser
If testuser is logged off, the environment looks strange to me:
PS C:\Windows\system32> echo $env:HOMEPATH
\Windows\system32
PS C:\Windows\system32> echo $env:APPDATA
C:\Users\testuser\AppData\Roaming
PS C:\Windows\system32> echo $env:USERPROFILE
C:\Users\testuser
PS C:\Windows\system32> cd ~
PS C:\Windows\system32> cd $home
PS C:\Windows\system32>
I need a correct %HOMEPATH% for my scheduled script. Is it expected behaviour? What can I do about that?
I've tested it on two Win2008, Win7, Win2012 with the same result.
UPDATE: The initial issue was a hanging scheduled task. When I had tested it with runas, I found that ssh command doesn't see a configuration placed in user directory and asks user for additional info.

Since you mentioned ssh, I'm going to take a stab at an answer, since I just worked through a similar issue. I'm using cwRsync 3.1.0, and the example script that comes packaged with it uses %HOMEPATH% to setup %HOME% for rsync execution. Like you experienced, when using 'runas' with the target user not logged into the host, the script halts to accept a hostid, because Windows\system32.ssh doesn't exist. The HOMEPATH is set to Windows\system32.
When the target user is logged into the host (but runas is run under a distinct user's login), the HOMEPATH is set to user's profile path (Users\), and the .ssh path does resolve.
My solution was to change the script o use %USERPROFILE%, rather than %HOMEPATH%. At https://serverfault.com/questions/29948/difference-between-profile-and-home-path and http://blogs.msdn.com/b/patricka/archive/2010/03/18/where-should-i-store-my-data-and-configuration-files-if-i-target-multiple-os-versions.aspx there is discussion that to my understanding, indicates %HOMEPATH% is for user content, whereas %USERPROFILE% is for settings, etc., and probably better for pointing to .ssh.

Related

Run command as System User in Powershell

I found several answers on the web, but not really what I was searching for.
The issue is as follows:
When restoring a file with "Networker", the ACLs of the file are the same ones as when the file was backed up, regardles of inheritance in the folder the file is restored to. Meaning the inheritence of ACL does not affect the newly restored file.
This leaves me with the problem that only 3 Accounts have the right to alter the ACL.
The user, the file belongs to
The domain Admins
The system account
To solve the issue I would like to run an automated script fixing the ACL and activating the correct inheritance.
The system user for the script has to be one of the three.
The User is changing and thefore not a valid choice, also I dont want to leave any domain admin credentials nor give domain admin rights to a service account.
This leaves me with the system account to do the job and here comes the question:
How do I execute a task in powershell under system account credentials?
I tried
$username = "NT Authority\System"
$password = ConvertTo-SecureString -String "" -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist #($username, $password)
Since the password is an empty I can not really create credentials with it.
The name of the account in all locales is .\LocalSystem. The name,
LocalSystem or ComputerName\LocalSystem can also be used. This account
does not have a password.
https://msdn.microsoft.com/de-de/library/windows/desktop/ms684190(v=vs.85).aspx
So now I am a little bit confused as to how I can get this to work.
Edit:
The file system runs on EMC and is not a real Windows File System, but just kinda hooked onto a Linux system. So there is no local administrator account.
TL;DR
I want to inherit ACL Permissions on files using the system account with powershell, how?
https://github.com/mkellerman/Invoke-CommandAs
Made a function to Invoke-Command against local/remote computer using provided credentials or SYSTEM. Returns PSObjects, handles network interruptions and resolves any Double-Hop issues.
Try it out let me know if this resolves your issues.
If you're ok installing a (very useful) 3rd party program, you can try the following. It's a portable .zip, no real installation.
Run as administrator:
C:\WINDOWS\system32>nircmd.exe elevatecmd runassystem c:\windows\System32\cmd.exe
starts a new cmd window:
Microsoft Windows [Version 10.0.18362.418]
(c) 2019 Microsoft Corporation. All rights reserved.
C:\WINDOWS\system32>whoami
nt authority\system
C:\WINDOWS\system32>
https://www.nirsoft.net/utils/nircmd.html
Domain Admins get access via the local Administrators group. Local Administrators can take ownership of any local object and subsequently grant new permissions to that object.
Running something like this as an administrator should do what you want:
takeown /f C:\some\file_or_folder /a /r /d:y
icacls C:\some\file_or_folder /reset /t /c /q
Never use the SYSTEM account for things like this.

Could not connect sessionID 0 to sessionname console .bat from psexec

I'm attempting to force a VM to log the current user out and send the session to the console via running a .bat script.
I can get this working if I manually run a .bat file on the VM which contains the following:
%windir%\System32\tscon.exe 0 /dest:console
However, when using psexec or paexec to call the same .bat:
c:\>psexec.exe \\virtualmachine -u domain\username -p password -h cmd /c
c:\user\atest\desktop\test.bat
I get an access denied:
Could not connect sessionID 0 to session name console, Error code 5
Error [5]:Access is denied. C:\windows\system32\tscon.exe exited on
virtualmachine with error code 1.
Alternatively, I've tried (same result):
C:\>PsExec.exe \\virtualmachine -u domain\username -p password -h
C:\windows\system32\tscon.exe 0 /dest:console
I'm not sure where I'm going wrong, because this starts iexplore.exe fine:
C:\>PsExec.exe \\virtualmachine -u domain\username -p password -h "c:\program files\internet explorer\iexplore.exe"
The problem was because the user was connected via RDP, it was not session 0. I had to run "query user" to get the session ID of the RDP connection, then pass that into PsExec using "-i" like so:
C:\>PsExec.exe -s -i $id \\virtualmachine c:\windows\system32\tscon.exe $id /dest:console
Because this is running as system (-s) I didn't need to pass in any authentication.
This answer helped me with the concept of sessions, hope it helps someone else.
I had a batch file that worked for years ending a RDP session and leaving the host screen unlocked, it had conditions for sessionid's 0 through 10 just in case. Then this week after a windows update loaded it stopped working and I kept getting 7045 errors in the results of the batch file. The RDP session would close but the host machines screen was locked. The host machine runs a message board so this was not acceptable and the machine is mounted to the ceiling so no mouse or keyboard is possible.
I searched a ton and found nothing that worked more than once if it worked at all. Then I found this by chance, and when I ran this power shell command my problem was solved. It works great so far and better yet you don't have to know the sessionID or name, or pass a password in a text or batch file.
#powershell -NoProfile -ExecutionPolicy unrestricted -Command "$sessionid=((quser $env:USERNAME | select -Skip 1) -split '\s+')[2]; tscon $sessionid /dest:console" 2> UnlockErrors.log
Just copy the script into a text file, rename it something.cmd then create a shortcut to it on the hosts desktop and go to the properties and select advanced and have it run as administrator. Easy. Works on win7 pro. I found the script here https://steamcommunity.com/groups/homestream/discussions/0/617335934139051123/?ctp=5
I also faced the same issue with the following command
Command – tscon SessionID /dest:console /password: ****
Resolution: I worked a lot and finally got to know the issue is with password. i.e. the password length should not be greater than 13 characters. But in this case password = 20 characters.
Later I changed the password to ****(12 characters) and issue got resolved.
If you are not a local administrator of the VM, you won't be able to do this. The session I was logged-in with was not a local admin, but when running the shortcut "as an administrator", I tried using another account that was a local admin (when prompted). However, this doesn't work. The account you are moving to the console session is the one you are logged-in with, but if you use a different account for the shortcut elevation, TSCON will try using that account instead.

run command as administrator on remote windows machine

Situation: Running the bat file on windows machine:
1. When I double click the bat file: Bat running is failed.
2. When I right click on bat file and run as administrator: Bat run is successful.
Now I have to run this bat file successfully from remote machine.
What I did:
1. Installed freeSSDd on remote machine and configured administrator user on freeSSHd to access shell and SFTP.
2. Now I am able to login to the remote machine using putty.
Problem:
I am not able to run the bat file successfully. How can I achieve this?
I also used runas /savecred /user:administrator C:/install.bat, but It didn't helped.
There is a way to get this working without any 3rd party software.
You have to create a task on the remote machine using the windows task scheduler which simply executes the desired command. There is an option where you can tell the scheruler to run a bat with a specific account. Enter an admin account and the password and check the "run with highest privileges" box. Leave "Triggers" empty, go to "Settings" and check the "Allow task to be run on demand" box. That's it!
Now when you want to run your file from a different location do
SCHTASKS /RUN /S <RemoteServerName> /U username /P password /TN "<task name>"
If you don't want to enter username and password each time you can adept the user policy (e.g. add the calling machine to the trusted list of the server).
If you have installed an ssh daemon, then you can run your BAT in a remote shell, but you remote shell may open up in something other than CMD.COM. I use cygwin to set up sshd and then from a remote machine, if I ssh in to run a command, it is using cygwin's bash. I can run a BAT file, but need to call CMD first:
ssh WINDOWS_SERVER "cmd /C D:\PATH_TO_BAT\BATCHFILE.BAT"
But there are some pieces missing here. I looked briefly at the Freesshd page and saw only graphical interfaces. Does freesshd support remote command execution, or just secure fire transfer? And what sort of shell get executed on the windows server when you run it?
cygwin is an entire Linux subsystem that runs under Windows and includes an sshd server, but might be a bit much for someone starting out: https://cygwin.com/
\n makes a powershell remote server that listens on port 22 (ssh) and dumps you into a powershell prompt, you can then use my steps above to call CMD from powershell, versus a bash shell.
http://www.powershellserver.com/

Windows 8.1 Task Scheduler Won't Execute Rsync/SSH Without being Logged On

I've created and scheduled a batch file in Windows 8.1 (to perform rsync offsite backups through an SSH tunnel) and I can run it:
manually
through task scheduler manually when I right click -> Run
through task scheduler automatically when I am logged on and it's scheduled to run at a given time
... but when I'm not logged on, it just sits at "Running" even though I've set it as follows:
user=me (I'm a member of admin group)
run whether logged on or not
run with highest privileges
I can see in Task Manager that rsync.exe and ssh.exe are running, so it must be hanging on the rsync/ssh call. That leads me to believe the problem is that, even though I've explicitly set the user name, something isn't really running as me?
(sidebar: I've also tried running the task as SYSTEM user - no luck there either)
The command I'm issuing looks like this:
rsync --archive --verbose --human-readable --hard-links --delete --exclude '*.log' --exclude '*log*.*' -e "%CWRSYNCBIN%\ssh -p 22103 -i C:\Users\test\.ssh\id_rsa" "/cygdrive/c/Users/test/Downloads" admin#1.2.3.4:/path/to/remote 1> %REPORTLOG% 2> %ERRORLOG%
Any ideas? (thanks!)
This seems to be problem with home directory and non-interactive environment in scheduled jobs in newer Windows version (starting from Server 2008 and Vista?). I find it in few discussions, but with not much info to solve it:
http://answers.google.com/answers/threadview/id/528721.html
Rsync for Windows cannot run on Task Scheduler
https://serverfault.com/questions/207118/cwrsync-on-server-2008-r2-as-a-scheduled-task
https://superuser.com/questions/368828/rsync-on-windows-xp-works-fine-on-demand-but-hangs-when-run-as-a-scheduled-task
My solution was:
set task to run under user that is proven to be able to finish rsync, set run whenever user are logged on or not, I also set to does not save password,
find location of .ssh folder under this user (in his home directory),
copy .ssh to simplier path to use it in HOME variable (SET HOME=D:\CWRSYNC\HOME),
use following script to run rsync:
#ECHO OFF
SETLOCAL
SET CWRSYNCHOME=D:\CWRSYNC
SET HOME=D:\CWRSYNC\HOME
SET CWOLDPATH=%PATH%
SET PATH=%CWRSYNCHOME%;%PATH%
rsync.exe -rtvz --delete /cygdrive/b/ user#192.168.1.2:/volume1/NetBackup/ >> D://nas-backup-log.txt
When I experienced this problem on Windows Server 2012 R2, I found SSH.exe was experiencing a permissions error when attempting to create a known_hosts file, despite the task running with an admin's credentials and with highest privileges.
The solution was to point to the user's existing known_hosts file using the UserKnownHostsFile SSH option:
rsync -e "ssh -i sshkey -o UserKnownHostsFile path/to/known_hosts" source dest

psexec giving the system cannot find the file specified

I'm trying to run this from my win7 CMD (as Admin):
psexec IpAddress -u domain\user -p pword c:\Autobatch\ClientJobSender.exe http://reportserver.net:8070/JobExecutor.asmx c:\AutoBatch\backup\trigger.xml
but am getting a "the system cannot find the file specified" error.
I've also tried it this way:
psexec IpAddress -u domain\user -p pword c:\Autobatch\ClientJobSender.exe http://reportserver.net:8070/JobExecutor.asmx c:\AutoBatch\backup\trigger.xml
but get a unknown user or bad password.
What's weird is that I can connect via Remote desktop with the same IP address and user/pass.
Make sure the server has the settings below:
a) Admin share is enabled: run services.msc and check the Service "Server" is enabled
b) Add the key for the share in the registry and restart:
reg add "HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters" /v AutoShareServer /t REG_DWORD /d 1
And then use:
psexec \\IpAddress -u domain\user -p pword -w "c:\Autobatch" "ClientJobSender.exe http://reportserver.net:8070/JobExecutor.asmx c:\AutoBatch\backup\trigger.xml"
Actually, I don't see a difference between your 2 command lines. However, the error from the first command is because your syntax is incorrect. You must use
PsExec \\a.b.c.d ...
instead of
PsExec a.b.c.d ...
I got it to work by elevating the local batch file to execute with administrator privileges, that is to say, the terminal window was operating with administrator privileges.
If you're trying to use automation services, you can use the ClientJobSender.exe on the local machine (or on the machine where you set up the scheduling). Just copy the ClientJobSender.exe and the related config file from the install pack to the scheduler server and refer it locally.
You might have the directory path wrong. Try change the .exe path into cmd.exe and cd into your intended path to see if it is actually the correct path.

Resources