Allow SSH from PowerShell without Administrator privileges - powershell

I mean to get a terminal in an Ubuntu 20.04LTS server via ssh under PS 5.1 in Win 10.
I know I can work with native support for OpenSSH, and I have already done it before.
Now I want to do it without having admin rights, to minimize "tainting" my system.
For reasons described below (1), I think I cannot work with native OpenSSH.
For reasons described below (2), I think it is possible.
For instance, I can already start a session and issue remote commands ref, see below (3).
But I couldn't start a terminal.
Is there a way to accomplish what I mean?
How?
(1) Why, for my purposes, I cannot work with native OpenSSH?
For instance, the first two commands in the PS-way of enabling OpenSSH already require admin (my PS is in Spanish):
> Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'
Get-WindowsCapability : La operación solicitada requiere elevación.
> Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
Add-WindowsCapability : La operación solicitada requiere elevación.
(2) Why I think it might be possible to get an ssh terminal without admin rights in PS?
Because I can already perform several similarly demanding actions as a regular user without admin rights, outside PS:
1.1. I can ssh from Msys2 portable
1.2. I can connect from putty (portable)
1.3. I can transfer via WinSCP portable
Item (3) below.
(3) How to start an ssh session and issue remote commands from PS
Install Posh-SSH for the current user only.
Then
> New-SSHSession -Host xxx.xxx.0.xxx -Credential (Get-Credential)
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Credential
Server SSH Fingerprint
Do you want to trust the fingerprint xx:xx:...
[] Y [] N [?] Ayuda (el valor predeterminado es "N"): y
SessionId Host Connected
--------- ---- ---------
0 xxx.xxx.0.xxx True
> Get-SSHSession
SessionId Host Connected
--------- ---- ---------
0 xxx.xxx.0.xxx True
> Invoke-SSHCommand -Index 0 -Command "pwd"
Host : xxx.xxx.0.xxx
Output : {/home/user1}
ExitStatus : 0

The latest versions of Windows 10 (and 11) have the ssh.exe built-in. It does not need to be installed. If you do not have it, you either do not have up-to-date version of Windows 10, or the OpenSSH component was somehow explicitly removed/forbidden.
Anyway, you can download ssh.exe manually from Win32-OpenSSH project. You do not need Administrator permissions for that. It does not need any installation.
But on the other hand, if you are not supposed to install software, why are you trying to bypass those restrictions, if you already have PuTTY? Use PuTTY, not ssh. If you need a console tool for automation, you can use PuTTY plink.exe. It's a console equivalent of PuTTY. And for automation purposes, it's identical to OpenSSH ssh (it does not have all the interactive features of ssh – for interactive purposes, use PuTTY).

Windows 10 has SSH built in since v1809. An OpenSSH-Client is already installed, you can directly use it by calling ssh. Try Get-Command ssh. It should return C:\WINDOWS\System32\OpenSSH\ssh.exe. You can connect to anything that supports SSH without administrative privileges "out of the box":
ssh -l <username> <DNS-Name/IP>
There is also an OpenSSH-Server available, but has to be enabled as a feature first. You probably need administrative privileges to enable that.
MS documentation on enabling OpenSSH-Server

Related

TeamCity BuildAgent does not see the network drive

I want to copy the file to a network drive using build agent (powershell or cmd (Build Steps)).
P:
# or
cd P:\foolder\
# ...
But the commands don't work. Build log: "Disk P not found".
The disk is connected via windows. When running from windows, the commands work.
I assume java/BuildAgent doesn't have rights. But my user has rights. And java, and BuildAgent runs under my user.
Please, do not offer FTP
Open command prompt as Administrator
bind your drive again using below command
net use x: \\10.1.2.3\Share
again do the same in Command prompt without administrator (if its not bounded)

PSExec could not start Regedit.exe on remote PC

Background:
I have several registry keys that are saved and used to update/configure remote PCs in my environment. I may not have deployed the device, previously, but I use these registry keys to update the PC as I fix/repair/etc...I am part of a team of 45 managing about 25,000 workstations and peripherals in our region of the enterprise.
if I use this command from my Win 10 PC to a Win 7 PC, it executes without problems.
psexec \remotecomputer -u domain\adminaccount regedit.exe /i /s "\server\share\directory1\directory2\directory3\someregistry.reg"
psexec starts regedit, imports the above registry file and closes.
If I run that exact same command from my Win 10 PC to another Win 10 PC, I get the following error, from CMD as ADMIN,
"PsExec could not start regedit.exe on REMOTEPC_HOSTNAME:
The system cannot find the file specified."
it can't find regedit??? WTF??
I'm curious why Win 10 is blocking me, as an admin, from importing a registry key?
I've tried reg import as a solution, but I keep getting syntax errors and it can't find the file/pathway.
It's almost like the remote PC, doesn't recognize admin input due to UAC settings?
In testing, I've set the group policy editor to enable remote registry tools, no change. I've enabled remote registry services and set to start the service automatically. I can access the PC registry via remote registry...but psexec just won't work on the remote device.
I can RDP to the device and run the command line equivalent:
regedit.exe /i /s "\UNC\pathway...\etc*.*reg" it executes, without issues.
this proves that regedit is working
Can anyone provide some expertise on this?
add -s flag to psexec to run regedit
The old PsExec trick of running RegEdit doesn't always work. This is because psexec depend on a hidden SMB Administrator service. (Which in any security sense should be disabled.)
PsExec allows redirects of the input and output of a remotely started
executable through the use of SMB and the hidden $ADMIN share on the
remote system. With this share, PsExec uses the Windows Service
control Manager API to start the PsExecsvc service on the remote
system which creates a named pipe that PsExec communicates with. This
named pipe is what allows for input/output redirection back to the
system that launched PsExec.
So instead, in order to remove any TrustedInstaller owned registry Keys, you can use a different tool. This worked:
ExecTI - Run as TrustedInstaller
Run it to open the ExecTI GUI and enter: C:\Windows\regedit.exe

Is there a SCP alternative for PowerShell?

I need to write a script that transfers files from a folder onto another server (Linux), but the script that's transferring files is on windows, and I was wondering if there was an alternative to scp for PowerShell (or if there was another way of doing this)
There is a handy little tool that comes with Putty called pscp.exe that will do this and can be called in powershell easily.
Example below copies from windows to a CentOS box (logging in as the usercode "bill") and you use the -pw switch in pscp to pass in a password (otherwise the command window that is spawned will prompt for the Linux password):
Start-Process 'C:\Program Files (x86)\PuTTY\pscp.exe' -ArgumentList ("-scp -pw password C:\Document.rtf bill#192.168.0.28:/home/bill/")
PuTTY Secure Copy client
Release 0.62
Usage: pscp [options] [user#]host:source target
pscp [options] source [source...] [user#]host:target
pscp [options] -ls [user#]host:filespec
Options:
-V print version information and exit
-pgpfp print PGP key fingerprints and exit
-p preserve file attributes
-q quiet, don't show statistics
-r copy directories recursively
-v show verbose messages
-load sessname Load settings from saved session
-P port connect to specified port
-l user connect with specified username
-pw passw login with specified password
-1 -2 force use of particular SSH protocol version
-4 -6 force use of IPv4 or IPv6
-C enable compression
-i key private key file for authentication
-noagent disable use of Pageant
-agent enable use of Pageant
-batch disable all interactive prompts
-unsafe allow server-side wildcards (DANGEROUS)
-sftp force use of SFTP protocol
-scp force use of SCP protocol
pscp.exe is a viable option, but I have been using a library from Rebex for a couple years now for SFTP and FTPS transfers in both C# apps and PowerShell scripts with great success. Their package also includes an SCP object but I haven't personally used it.
It does cost money vs. pscp being free. Before selecting the Rebex package, I had considered going the PuTTY route but my team decided that having a library we could easily roll into any app/script was worthwhile in the long term.
You can use WinSCP .NET assembly from PowerShell for SCP transfers.
For example see http://winscp.net/eng/docs/library_powershell#example
The example uses SFTP protocol. To use SCP, just modify it to:
$sessionOptions.Protocol = [WinSCP.Protocol]::Scp
Though if your server support SCP protocol, it's likely it also supports SFTP. SFTP is better choice, if you have the option.
Why use an alternative to SCP when you can use SCP?
Windows has OpenSSH (which includes SCP) as an optional component these days, so you could just use that. It first appeared in the Autumn 2018 version of Windows 10. It's nearly identical to the command you find in most Linux distributions, as it's derived from the same code base. Microsoft just made one or two minor tweaks to make it work on windows.
It is simple to install just go to Start->Settings->Apps->Optional Features->View Features enter in OpenSSH in the search box and check the OpenSSH client and click next. See OpenSSH in Windows for more detailed instructions on how to set it up. For a more PowerShell way of installing it run this from an elevated PowerShell prompt:
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
You can use this command to check if there is a newer version and whether you already have it installed:
Get-WindowsCapability -Online | Where Name -Like '*ssh*'
Once installed, you call scp from PowerShell just like you would any other executable command.
scp file.dat user.name#example.com:/target/path
If you really don't want to use SCP use Copy-Item
This requires PowerShell to be installed on your server. Yes you can install PowerShell on Linux. Just call Copy-Item with the -ToSession parameter passed an SSH connected session, I've never actually tried it though. It requires a recent version of PowerShell and some setting up see PowerShell remoting over SSH. Something like this:
Copy-Item C:\localPath\*.* ~\remotePath\ -ToSession (New-PSSession -HostName UserA#LinuxServer01:22 -KeyFilePath c:\\userAKey_rsa)
If both machines are Windows machines you can use the same -ToSession parameter to copy files over WinRM. But both machines have to be domain joined or there is the possibility of security issues.
There is also a ".NET friendly" way:
you can use the SharpSSH dll to execute ssh commands, and do scp/sftp tranfers.
For example:
[Reflection.Assembly]::LoadFrom((Resolve-Path .\Tamir.SharpSSH.dll))
$ssh = New-Object Tamir.SharpSsh.Sftp("server","user","password")
$ssh.Connect()
$ssh.Put("C:\localfile","distantfile")
$ssh.Close()
There is the SSH.Net library, too, it does approximatively the same things.

FreeSSHd in jenkins and from commandline

i have installed fresshd in one of my windows server.now i am connect to the system through putty. It is working fine.
my issue us when i am running from command line
PuTTY.lnk -ssh -2 -P 22 username#XXX -pw pswd -m command.txt
commands given in the command.txt files are not executed it just open the putty console and it is closing.
when Running from Jenkins also same issue.
I am not sure if you are connecting to Windows from a Linux machine, or to Linux from a Windows machine. Or Windows to Windows?
PuTTY.lnk is not an executable. If you try to run that, it should produce an error 'PuTTY.lnk' is not recognized as an internal or external command. I am assuming you are running the command from a Windows machine, since you are referring to windows shortcut file (.lnk)
You need to use PuTTY.exe + the rest of your command line. Please note that unless it is in your $PATH settings, you would have to provide a full path to the .exe, for example C:\LocationOfPuttyInstall\putty.exe -ssh -2 -P 22 username#XXX -pw pswd -m command.txt. For the sake of preventing any other problem, you should also specify a correct full path to the command.txt file.
If you are not sure where your Putty is installed, on the Windows machine, do the following:
Right click your PuTTY shortcut (the PuTTY.lnk file)
Look under "Target"
That would list your full path to PuTTY.exe executable.
This should resolve your problem.
p.s.
Usually Putty is used to connect from a Windows machine to a Linux machine. From your question, it almost looks like you are trying to connect from a Windows machine to another Windows machine.
You should use PsExec windows tool for such purposes:
http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx

PSEXEC, access denied errors

While I'm using PSEXEC.exe getting 'Access denied' error for remote systems.
Any idea about how to solve this?
Hi i am placing here a summary from many sources online for various solutions to "access is denied" :
most information can be found here (including requirements needed) - sysinternal help
as someone mentioned add this reg key, and then restart the computer :
reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system
/v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
Read this knowledge base article to learn what this does and why it is
needed
Disable firewall (note - this will leave you with out any firewall
protection)
netsh advfirewall set allprofiles state off
if target user has a blank PW and you dont want to add one, run on target:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa]
"LimitBlankPasswordUse"=dword:00000000
This didnt work for me, but i have read it did for others in a few places,
on target execute:
Start -> Run -> secpol.msc -> Local Policies -> Security Options -> Network Access: Sharing > and security model for local accounts > Classic – local users authenticate as themselves
if already in 'Classic':
move to "Guest only - .." run from elevated command prompt gpupdate \force
move back to 'Classic - .." again run from elevated command prompt gpupdate \force
This one solved my issue:
run on target from elevated command prompt "net use" look at ouput chart and for shares listed in remote column there (i only deleted the disconnected ones - you can try them all) run "net use [remote path from before list] /delete" then run 'net use \target\Admin$ /user:[user name]' enter prompt password request (if empty PW just press enter), viola should work.
I just solved an identical symptom, by creating the registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system\LocalAccountTokenFilterPolicy and setting it to 1. More details are available here.
This helped in my case:
cmdkey.exe /add:<targetname> /user:<username> /pass:<password>
psexec.exe \\<targetname> <remote_command>
PsExec has whatever access rights its launcher has. It runs under regular Windows access control. This means whoever launched PsExec (be it either you, the scheduler, a service etc.) does not have sufficient rights on the target machine, or the target machine is not configured correctly. The first things to do are:
Make sure the launcher of PsExec is familiar to the target machine, either via the domain or by having the same user and password defined locally on both machines.
Use command line arguments to specify a user that is known to the target machine (-u user -p password)
If this did not solve your problem, make sure the target machine meets the minimum requirements, specified here.
You can try the command
net use \\computername\ipc$ /user:adminname password
to get admin permissions on remote PC before use psexec.
I had the same problem. And after a hard work, I found a easy and full solution:
I use runas to run the script in a admin account
I use the -s parameter in psExec to run in a system account
Inside the PsExec, I login again with a admin account
You can use & to run multiples commands
Remember to replace [USERNAME], [PASSWORD], [COMPUTERNAME], [COMMAND1] and [COMMAND2] with the real values
The code looks like this:
runas /user:[USERNAME] "psexec -e -h -s -u [USERNAME] -p [PASSWORD] \\[COMPUTERNAME] cmd /C [COMMAND1] & [COMMAND2]"
If you whant to debug your script in the another machine, run the following template:
runas /user:[USERNAME] "psexec -i -e -h -s -u [USERNAME] -p [PASSWORD] \\[COMPUTERNAME] cmd /C [COMMAND1] & [COMMAND2] & pause"
Try setting this key on the target (remote) machine, and restart the machine:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System]
"LocalAccountTokenFilterPolicy"=dword:00000001
See: http://forum.sysinternals.com/topic10924.html and http://www.brandonmartinez.com/2013/04/24/resolve-access-is-denied-using-psexec-with-a-local-admin-account/
I just added "-с" parameter. It makes Psexec copy executable to remote machine. So it works without access errors.
I found Sophos kept placing psexec.exe into the Quarantine section. Once I authorized it, it ran fine.
I still use psexec, even on win 10. Replace the psexec.exe in the Windows 10's win32 folder with the older version to work -> I use version 2.11.0.0. The Windows 10 version I was using would only run .bat files as background/hidden process on the remote computer. Took a whole day to figure this out.
Adding the registry key from above to the remote computer helps as well:
reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
I found another reason PSEXEC (and other PS tools) fail - If something (...say, a virus or trojan) hides the Windows folder and/or its files, then PSEXEC will fail with an "Access is Denied" error, PSLIST will give the error "Processor performance object not found on " and you'll be left in the dark as to the reason.
You can RDP in; You can access the admin$ share; You can view the drive contents remotely, etc. etc., but there's no indication that file(s) or folder(s) being hidden is the reason.
I'll be posting this information on several pages that i was perusing yesterday while trying to determine the cause of this odd problem, so you might see this elsewhere verbatim - just thought I'd put the word out before anyone else pulled their hair out by the roots trying to understand why the performance counter has anything to do with PSEXEC running.
I had a case where AV was quarantining Psexec - had to disable On-access scanning
For anybody who may stumble upon this. There is a recent (Dec 2013) Security Update from Microsoft Windows on Windows 7 that is preventing remote execution.
See http://support.microsoft.com/kb/2893294/en-us
I uninstalled the Security Update by going to Control Panel\Programs\Programs and Features\Installed Updates
It worked right after that.
The following worked, but only after I upgraded PSEXEC to 2.1 from Microsoft.
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System]
"LocalAccountTokenFilterPolicy"=dword:00000001 See:
http://forum.sysinternals.com/topic10924.html
I had a slightly older version that didn't work. I used it to do some USMT work via Dell kace, worked a treat :)
On Windows Server 2012 R2 I had trouble to run from user account
psexec -u administrator -p password \\machinename -h -s -d -accepteula cmd.exe
But it works fine if you run without parameters -h -s. That's why I use this to solve my trouble:
psexec -accepteula -u administrator -p password \\machinename %PathToLocalUtils%\psexec.exe -h -s -d cmd.exe
I couldn't get access to remote machines unless I had UAC disabled.
That has to be done locally, either from control panel or running the following through cmd:
reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f
While UAC is enabled, make sure you run cmd as administrator.
For a different command I decided to change the network from public to work.
After trying to use the psexec command again it worked again.
So to get psexec to work try to change your network type from public to work or home.
I tried a lot of way but I could not use psexec. It gives "Access denied". After I change the target user account type from Standard to Admin, I connected the machine via psexec.
I researched the reason why admin type account is required then I found this answer.
You can change target machine user account this way: Control Panel -> User Accounts -> Change Account Type. You must enter an admin account and password to change that account if you logged in standard account.
After that I logged in with this command: psexec \\remotepcname -u remoteusername -p remotepassword cmd
Tried all suggestions above, but still was unable to resolve the error. Finally once I made the below change, I could successfully run the PSexec command.
Turns out that when you have UAC enabled psexec does not work as supposed. We need to set HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA to 0 then psexec starts working as expected.