Current situation:
We've got a domain with mostly Win Server 2022, including one database server. Next to that our backup server is in a different (accessible) VLAN, but did not join the domain (still in Workgroup). I've got a shared folder on our backup-server with permissions to Everyone.
Future situation:
I would love to write a powershell-script that automatically sends file from our Database-server (in domain) to our backup server (workgroup).
I keep struggling with permissions and auomatically putting them into the PowerShell scripting ... Anyone has got a solution to this?
You can authorize against the share with net-use first, then call your powershell
net use \\server\share /user:<domain\username> <password>
Or if you want to go powershell only, use the New-PSDrive cmdlet.
New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist
Hope this helps.
I am checking how to make the proxy settings of a windows VM by using desired state configuration (DSC) in Azure. Is there a library of DSC?
Normally, i am using below commands to set the proxy from the cli:
Set-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' -name ProxyServer -Value "123.123.123.123:80"
Set-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' -name ProxyEnable -Value 1
netsh winhttp set proxy 123.123.123.123:80
Any idea?
You may try with Script resource. In that resource, you may use TestScript and/or GetScript property to check if proxy setting is already set as required. If proxy setting is already not set then use SetScript property to actually set proxy setting using cmdlets you have provided.
I have been trying to enable or disable a Local group policy with powershell to automate the process, I tried installing Remote Server Administration Tools but it's module in powershell needs the pc to be in a domain.
Is there any way to enable\disable a Local group policy with powershell?
Use the registry (note that this requires elevation):
Set-ItemProperty -Path <HKLM:RegistryPath> -Name <PropertyToChange> -Value <NewValue>
Example (Enabling Search Suggestions from Edge):
Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\MicrosoftEdge\SearchScopes" -Name "ShowSearchSuggestionsGlobal" -Value 1
I am trying to make a script in powershell (if you have suggestions for another tool to make this with please advise) that would map network drives for userA to map their own drives temporarily while userB is still logged in.
I tried to use both the New-PSDrive method, as well as the MapNetworkDrive method.
They both throw this error:
"Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again"
After I saw this, I tried disconnecting all drives associated with the server before connecting the desired share via:
net use * /d /y
net use \\server\ipc$
net use \\server\ipc$ /d /y
(thanks #jessehouwing !)
The same error still occurs.
If you want to check my connection code I have it below:
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive($drLetter, $share, $false, $user, $pass)
and
New-PSDrive -Name $drLetter -PSProvider FileSystem -Root $share -Credential $user -Persist
You are getting that error because you are not allowed to have multiple connection to the same resource with different credentials. I am going to Assume you don't just have a temporary connection to this resource defined by server.
What I always to in situations like this is use the IP address of the host. so...
net use \\10.10.10.10\ipc$
I am going to try and find the articles that discuss what is occurring here but in short this will allow the separate connections.
I am having issues setting up OpenSSH for Windows, using public key authentication.
I have this working on my local desktop and can ssh with a key from Unix machines or other OpenSSH for Windows machines.
I have replicated the build onto a server, I can get password authentication working fine, but when I use the keys I get the following issue:
debug1: Authentications that can continue: publickey,password,keyboard-interactive
debug3: start over, passed a different list publickey,password,keyboard-interactive
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /cygdrive/c/sshusers/jsadmint2232/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
Connection closed by 127.0.0.1
So for the purposes of testing, I have been just trying to SSH to localhost, but even when tried remotely I get the same issue.
Even more strange, is that when I have both password and public key enabled in sshd_config, it will only attempt to use keys and then bomb out with the above message and won't even try to use password.
Here are the steps I have taken:
Install OpenSSH for Windows
mkgroup -l >>..\etc\group (added local groups)
mkgroup -d >>..\etc\group (added domain groups)
mkpasswd -L -u openssh >>..\passwd (added my local user)
mkpasswd -D -u jsadmint2232 >>..\passwd (added my domain user)
Edited the homedir in file passwd to point to c:\sshusers%USER% - where %USER% is the user name
Enabled password authentication, disabled key authentication
Created SSH keys for both jsadmint2232 / OpenSSH and ensured that the files were created in home directories
Added authorized_keys files into .ssh directories for each user and added keys for incoming connecting users
net stop opensshd / net start opensshd
Test if password authentication works both locally and remotely
Updated sshd_config, to enabled key auth - restart opensshd
Test connection and get above error. Also, it doesn't even try password authentication.
Updated sshd_config, to disable password authentication completely - restart opensshd
Test connection and still get above error
It appears the server is killing the connection for some reason.
Following are setup steps for OpenSSH shipped with Windows 10 v.1803 (April 2018 update. See comments to this post, it might not work with 1809).
Server setup (elevated powershell):
Install OpenSSH server: Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0.
Start agent and sshd services: Start-Service ssh-agent; Start-Service sshd (this will generate host keys and default configuration automatically in $env:ProgramData\ssh).
[Optional] Install OpenSSHUtils powershell module: Install-Module -Force OpenSSHUtils
Client setup (non-elevated powershell):
Generate user key: cd $env:USERPROFILE\.ssh; ssh-keygen.exe, follow prompts, agree to the default suggested file location. This will create 2 files: id_rsa and id_rsa.pub;
[Optional] add key to authentication agent, so you don't have to enter password each time you use it: ssh-add .\id_rsa (or whatever file was generated);
Server setup continued (non-elevated powershell):
Log in as a user, for which public key auth to be used
cd $env:USERPROFILE; mkdir .ssh; cd .ssh; New-Item authorized_keys;
Paste the contents of the id_rsa.pub file from the client to the .ssh\authorized_keys file from the previous step.
Setup permissions properly (important!!!):
Run start . to open explorer with the current folder ($env:USERPROFILE\.ssh);
Right click authorized_keys, go to Properties -> Security -> Advanced
Click "Disable inheritance";
Choose "Convert inherited permissions into explicit permissions on this object" when prompted;
(really, really important) Remove all permissions on file except for the SYSTEM and yourself. There must be exactly two permission entries on the file. Some guides suggest running the Repair-AuthorizedKeyPermission $env:USERPROFILE\.ssh\authorized_keys - this will try to add the sshd user to the permission list and it will break the authentication, so, don't do that, or at least do not agree on adding the sshd user). Both SYSTEM and yourself should have full control over the file.
If your Windows build is 1809 or later, it is required to comment out the following lines in C:\ProgramData\ssh\sshd_config file. Then restart the sshd service.
# Match Group administrators
# AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys
Client:
Run ssh <serverusername>#<serverhostname>. It should work at this point.
Tried that with Windows 10 as server and both itself and a Debian Linux as a client.
Use this sequence of commands in PowerShell to correct permission of administrators_authorized_keys
$acl = Get-Acl C:\ProgramData\ssh\administrators_authorized_keys
$acl.SetAccessRuleProtection($true, $false)
$administratorsRule = New-Object system.security.accesscontrol.filesystemaccessrule("Administrators","FullControl","Allow")
$systemRule = New-Object system.security.accesscontrol.filesystemaccessrule("SYSTEM","FullControl","Allow")
$acl.SetAccessRule($administratorsRule)
$acl.SetAccessRule($systemRule)
$acl | Set-Acl
Only SYSTEM and Administrators group must be have permission in file without inherited.
One more tip, if you are stuck, is to run sshd in debug mode. I did this:
Stop the sshd service
Open a PowerShell console with administrator privileges
Type 'sshd -d'
Type login from my client machine
It turns out the key need to be in e.g. C:\ProgramData\ssh\administrators_authorized_keys instead of C:\Users\yourUsser.ssh\authorized_keys.
I have solved the issue...
It is related to the account that started the service - it was using the Local System account - this was stopping it accessing the public key and authorized_keys file.
Once I stopped the service and started as the user I was trying to connect into, it worked!
So basically, you need to start with a service account and then external users connect in as that user.
This is just my scripted version of #n0rds great answer.
Place this script in a directory w/ your private/public key/pair and run!
PowerShell.exe -ExecutionPolicy Bypass -File "C:\bypass\prompt\standard.ps1" 2>&1>$null
Add-WindowsCapability -Online -Name OpenSSH.Server
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH SSH Server' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 -Program "%WINDIR%\System32\OpenSSH\sshd.exe"
#Must Enable ssh-agent before starting
Set-Service -Name ssh-agent -StartupType Automatic
Set-Service -Name sshd -StartupType Automatic
Start-Service ssh-agent; Start-Service sshd
$sshdir="$env:USERPROFILE\.ssh"
mkdir $sshdir
copy .\id_rsa $sshdir\
cat $sshdir\id_rsa
copy .\*.pub $sshdir\authorized_keys
cat $sshdir\authorized_keys
ssh-add $sshdir\id_rsa
$sshd_config="C:\ProgramData\ssh\sshd_config"
(Get-Content $sshd_config) -replace '#PubkeyAuthentication', 'PubkeyAuthentication' | Out-File -encoding ASCII $sshd_config
(Get-Content $sshd_config) -replace 'AuthorizedKeysFile __PROGRAMDATA__', '#AuthorizedKeysFile __PROGRAMDATA__' | Out-File -encoding ASCII $sshd_config
(Get-Content $sshd_config) -replace 'Match Group administrators', '#Match Group administrators' | Out-File -encoding ASCII $sshd_config
cat C:\ProgramData\ssh\sshd_config
Restart-Service ssh-agent; Restart-Service sshd
Write-Host "Use this to Login/test Now"
write-host ssh $env:UserName#localhost
n0rd's solution is on the money but there's an added complication for users that are also in the administrator's group. If you're looking for a solution to a situation involving the following conditions:
You want to use public keys on a per-user basis (or you don't want to use the administrators_authorized_keys file).
And you don't want to use PasswordAuthentication.
And some of the users also belong to the admin group.
The issue I ran across is that when I tried n0rd's solution it didn't work for users under the conditions above. After some tinkering, I found a solution that works consistently for me. Follow n0rd's solution and just change the following
In the ssh_config make sure the following settings are set:
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no
PubkeyAuthentication yes
Also, make sure to comment out the Match Group Administrators setting:
#Match Group administrators
# AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys
Make sure to include the client's public key in the servers C:\Users\username\.ssh\authorized_keys file.
Finally, to help match the user to the account I found it helpful to be more specific with the user data on the client. Instead of using the plain username, I used the username along with the domain of the user on the server. In my case, my client's C:\Users\UserName\.ssh\config file looked like this:
Host my_short_name
HostName my.serveraddress.net
User serversname\username
IdentityFile .ssh\id_rsa
In this case, my Windows 10 server would be called serversname (under device name). By specifying the user in this way I could avoid password authentication.
As an added bonus, this worked very well with a default shell of PowerShell 7. Even my default PowerShell profile worked over ssh and I got full support for posh-git and oh-my-posh. However, I found that the default method suggested for making PowerShell the default shell environment, (by editing the ssh_conf to include 'Subsystem powershell c:/progra~1/powershell/7/pwsh.exe -sshs -NoLogo') did not work for me. Instead, on the server use the command in an elevated PowerShell window:
New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "c:/progra~1/powershell/7/pwsh.exe" -PropertyType String -Force
This just creates a registry entry. You can always pop in the registry to remove it later if you want.
If you are using mls-software.com's version of OpenSSH here is another note.
If you install using the SSHD_SERVER account and privilege separation you will be able to use public key authentication (per http://www.mls-software.com/opensshd-pki.html). However if UAC is enable you will not be successful with the install. The user(s) will not be created properly and the service will not be created. Manually trying to get these items up after the fact is very difficult. Simply disabling UAC before installation will allow the installation process to properly create the user(s) and the service. After installation you can re-enable UAC.
When I created the SSHD_SERVER account manually authentication succeed when using password authentication but the client termination the connection with "/bin/bash: Operation not permitted". Authentication with public keys was closed by the server (original error posted by Cambolie).
I solved it by:
Installing in SSHD_SERVER + privilege separation mode. I also set privilege separation to "yes" in the config manually. This didn't work for me for a lot time, the user didn't get created. Then it worked, I don't know why. I only went to user accounts in control panel to check that UAC is off. I also had /var/empty with full access for everyone.
For C:\openssh\var\empty I've set "attributes get/set" permissions to Everyone and myself and "full" permissions to .\sshd_server. I also made it the owner.
I ran into a different situation.
First, debug as gWay said, with another terminal windows connecting to the server.
I gotread_keyfile_line: C:\\Users\\yieatn\\.ssh/authorized_keys line 1 exceeds size limit
recode the authorized_keys into utf-8
The reason is that I created authorized_keys with cat id_rsa >> authorized_keys and powershell in Chinese uses UTF-16 to create files.
I've thoroughly tested n0rd's solution on multiple Windows Pro 1809 and 2004 computers. I concur with most of his steps.
Server setup (elevated PowerShell): Agree with all.
Client setup (non-elevated PowerShell): Agree with all.
Server setup continued (non-elevated PowerShell): Steps 1,2,3: Agree
Server setup continued (non-elevated PowerShell): Step 4: Do NOT perform anything in step 4.
Server setup continued (non-elevated PowerShell): Step 5: Agree
Server setup continued (non-elevated PowerShell): Step 6: (added) Uncomment (remove #) from C:\ProgramData\ssh\sshd_config: #PasswordAuthentication yes
Server setup continued (non-elevated PowerShell): Step 7: (added) In Services, restart OpenSSH SSH Server.
I did not find any issues, with any file, regarding security, permissions or Unicode. They were all correct out of the box.
This is a very English language centric default Microsoft use.
The group match lines currently check for the ENGLISH language version string of the Administrators group called 'administrators' this FAILS on many other language installs of windows. On a German installation that line needs to be 'administratoren' instead. They better make it possible le to match group by SID instead. ( This is even more important in the DenyGroups matching feature - have not tested this yet - but if they check for strings instead of SID there then the denies are meaningless and easily circumvented by using a different windows language install )
( also see https://github.com/MicrosoftDocs/windowsserverdocs/issues/1911#issuecomment-771552030 )
I couldn't get it to work with my ed25519 client public key (ssh-keygen -t ed215519) but it does work with an rsa key ( ssh-keygen -t rsa).
No one has pointed out that the file ~/.ssh/authorization_keys must use DOS/Windows line endings. It won't work with Unix line endings. If you have tried everything and still not working, try this (I am using cygwin):
gawk -v ORS='\r\n' '1' authorized_keys > authorized_keys2
Check that the file has now DOS line endings:
hexdump -C authorization_keys2
Replace the original file:
mv authorized_keys2 authorized_keys