Unpacking Software Livestream

Join our monthly Unpacking Software livestream to hear about the latest news, chat and opinion on packaging, software deployment and lifecycle management!

Learn More

Chocolatey Product Spotlight

Join the Chocolatey Team on our regular monthly stream where we put a spotlight on the most recent Chocolatey product releases. You'll have a chance to have your questions answered in a live Ask Me Anything format.

Learn More

Chocolatey Coding Livestream

Join us for the Chocolatey Coding Livestream, where members of our team dive into the heart of open source development by coding live on various Chocolatey projects. Tune in to witness real-time coding, ask questions, and gain insights into the world of package management. Don't miss this opportunity to engage with our team and contribute to the future of Chocolatey!

Learn More

Calling All Chocolatiers! Whipping Up Windows Automation with Chocolatey Central Management

Webinar from
Wednesday, 17 January 2024

We are delighted to announce the release of Chocolatey Central Management v0.12.0, featuring seamless Deployment Plan creation, time-saving duplications, insightful Group Details, an upgraded Dashboard, bug fixes, user interface polishing, and refined documentation. As an added bonus we'll have members of our Solutions Engineering team on-hand to dive into some interesting ways you can leverage the new features available!

Watch On-Demand
Chocolatey Community Coffee Break

Join the Chocolatey Team as we discuss all things Community, what we do, how you can get involved and answer your Chocolatey questions.

Watch The Replays
Chocolatey and Intune Overview

Webinar Replay from
Wednesday, 30 March 2022

At Chocolatey Software we strive for simple, and teaching others. Let us teach you just how simple it could be to keep your 3rd party applications updated across your devices, all with Intune!

Watch On-Demand
Chocolatey For Business. In Azure. In One Click.

Livestream from
Thursday, 9 June 2022

Join James and Josh to show you how you can get the Chocolatey For Business recommended infrastructure and workflow, created, in Azure, in around 20 minutes.

Watch On-Demand
The Future of Chocolatey CLI

Livestream from
Thursday, 04 August 2022

Join Paul and Gary to hear more about the plans for the Chocolatey CLI in the not so distant future. We'll talk about some cool new features, long term asks from Customers and Community and how you can get involved!

Watch On-Demand
Hacktoberfest Tuesdays 2022

Livestreams from
October 2022

For Hacktoberfest, Chocolatey ran a livestream every Tuesday! Re-watch Cory, James, Gary, and Rain as they share knowledge on how to contribute to open-source projects such as Chocolatey CLI.

Watch On-Demand

Downloads:

212,816

Downloads of v 2016.05.30.20160827:

9,060

Last Update:

27 Aug 2016

Package Maintainer(s):

Software Author(s):

  • Microsoft

Tags:

win32-openssh admin

Win32 OpenSSH (Microsoft Port)

This is not the latest version of Win32 OpenSSH (Microsoft Port) available.

  • 1
  • 2
  • 3

2016.05.30.20160827 | Updated: 27 Aug 2016

Downloads:

212,816

Downloads of v 2016.05.30.20160827:

9,060

Maintainer(s):

Software Author(s):

  • Microsoft

Win32 OpenSSH (Microsoft Port) 2016.05.30.20160827

This is not the latest version of Win32 OpenSSH (Microsoft Port) available.

Legal Disclaimer: Neither this package nor Chocolatey Software, Inc. are affiliated with or endorsed by Microsoft. The inclusion of Microsoft trademark(s), if any, upon this webpage is solely to identify Microsoft goods or services and not for commercial purposes.

  • 1
  • 2
  • 3

Some Checks Have Failed or Are Not Yet Complete

Not All Tests Have Passed


Validation Testing Passed


Verification Testing Passed

Details

Scan Testing Resulted in Flagged:

This package was submitted (and approved) prior to automated virus scanning integration into the package moderation processs.

We recommend clicking the "Details" link to make your own decision on installing this package.

Details
Learn More

Deployment Method: Individual Install, Upgrade, & Uninstall

To install Win32 OpenSSH (Microsoft Port), run the following command from the command line or from PowerShell:

>

To upgrade Win32 OpenSSH (Microsoft Port), run the following command from the command line or from PowerShell:

>

To uninstall Win32 OpenSSH (Microsoft Port), run the following command from the command line or from PowerShell:

>

Deployment Method:

NOTE

This applies to both open source and commercial editions of Chocolatey.

1. Enter Your Internal Repository Url

(this should look similar to https://community.chocolatey.org/api/v2/)


2. Setup Your Environment

1. Ensure you are set for organizational deployment

Please see the organizational deployment guide

2. Get the package into your environment

  • Open Source or Commercial:
    • Proxy Repository - Create a proxy nuget repository on Nexus, Artifactory Pro, or a proxy Chocolatey repository on ProGet. Point your upstream to https://community.chocolatey.org/api/v2/. Packages cache on first access automatically. Make sure your choco clients are using your proxy repository as a source and NOT the default community repository. See source command for more information.
    • You can also just download the package and push it to a repository Download

3. Copy Your Script

choco upgrade win32-openssh -y --source="'INTERNAL REPO URL'" --version="'2016.05.30.20160827'" [other options]

See options you can pass to upgrade.

See best practices for scripting.

Add this to a PowerShell script or use a Batch script with tools and in places where you are calling directly to Chocolatey. If you are integrating, keep in mind enhanced exit codes.

If you do use a PowerShell script, use the following to ensure bad exit codes are shown as failures:


choco upgrade win32-openssh -y --source="'INTERNAL REPO URL'" --version="'2016.05.30.20160827'" 
$exitCode = $LASTEXITCODE

Write-Verbose "Exit code was $exitCode"
$validExitCodes = @(0, 1605, 1614, 1641, 3010)
if ($validExitCodes -contains $exitCode) {
  Exit 0
}

Exit $exitCode

- name: Install win32-openssh
  win_chocolatey:
    name: win32-openssh
    version: '2016.05.30.20160827'
    source: INTERNAL REPO URL
    state: present

See docs at https://docs.ansible.com/ansible/latest/modules/win_chocolatey_module.html.


chocolatey_package 'win32-openssh' do
  action    :install
  source   'INTERNAL REPO URL'
  version  '2016.05.30.20160827'
end

See docs at https://docs.chef.io/resource_chocolatey_package.html.


cChocoPackageInstaller win32-openssh
{
    Name     = "win32-openssh"
    Version  = "2016.05.30.20160827"
    Source   = "INTERNAL REPO URL"
}

Requires cChoco DSC Resource. See docs at https://github.com/chocolatey/cChoco.


package { 'win32-openssh':
  ensure   => '2016.05.30.20160827',
  provider => 'chocolatey',
  source   => 'INTERNAL REPO URL',
}

Requires Puppet Chocolatey Provider module. See docs at https://forge.puppet.com/puppetlabs/chocolatey.


4. If applicable - Chocolatey configuration/installation

See infrastructure management matrix for Chocolatey configuration elements and examples.

NOTE

Private CDN cached downloads available for licensed customers. Never experience 404 breakages again! Learn more...

Package Approved

This package was approved as a trusted package on 27 Aug 2016.

Description

Open SSH tools for Windows.
This is the Microsoft PowerShell Team's recent port.
Works in all CLIs and does not require .NET.
Includes the following tools:
* ssh.exe
* ssh-add.exe
* ssh-agent.exe
* ssh-keygen.exe
* ssh-keyscan.exe
* ssh-keysign.exe
* ssh-pkcs11-helper.exe
* scp.exe
* sftp.exe
* sshd.exe (server)
* sftp-server.exe

This package performs the following operations that you normally have to hack at until you get what you want:
* Install Appropriate Bitness for the version of Windows
* Install to Program Files (malware protection and following advice of dev team)
* Add SSH location to System PATH
* Optionally install sshd windows service (Requires parameter - see below)
* Optionally install sshd server "key based authentication" (Requires parameter - see below)
* Cleanly uninstall all of the above (removing config files and server keys requires special switch - see below)

The package also attempts to keep you out of trouble when configuring the sshd service:
* Will not install sshd server if an different sshd server is already running
* Will not delete server keys on uninstall or reinstall (unless you override with switch below)
* Will not upgrade or uninstall if the service is running and you did not specify /SSHServerFeature (you forget about the service on a machine where you want to upgrade the client tools)
* If you use the server's Key Based Authentication feature, install and uninstall behave differently to account for the integration of this component

This package supports the following parameters:

-params '"/SSHServerFeature"' (Install and Uninstall)
Also install sshd Windows Service - including opening port 22.
If this parameter is not included on an upgrade or uninstall and
the sshd server is installed - an error is generated. You must
use this switch to indicate you have made preparations for the
sshd service to be interrupted or removed.

-params '"/SSHServerFeature /KeyBasedAuthenticationFeature"'
Also install sshd Windows Service - including opening port 22 and
it with Key Based Authentication (reboot required before active)

-params '"/SSHServerFeature /KeyBasedAuthenticationFeature /DeleteServerKeysAfterInstalled"'
Also install sshd Windows Service - including opening port 22 and
it with Key Based Authentication (reboot required before active)
Server keys are deleted after added to the ssh-agent (you will not have an opportunity to copy them)

-params '"/DeleteConfigAndServerKeys"' (Uninstall)
By default an uninstall does not remove config files nor server keys.

-params '"/UseNTRights"'
By default the install uses PowerShell code that was tested on Nano - which means it should work on server core without WOW64.
If this code does not work for you, you can use this switch to invoke the 32-bit ntrights.exe
Please be aware that 32-bit ntrights.exe will NOT work on Windows Systems that doe not have WOW64 installed - this would mainly
affect Server Core where this feature is optional and not installed by default and Server Nano where 32-bit is not supported.


tools\AddAccountToLogonAsAService.ps1
param($accountToAdd)
#written by Ingo Karstein, http://blog.karstein-consulting.com
#  v1.0, 01/03/2014

## <--- Configure here

if( [string]::IsNullOrEmpty($accountToAdd) ) {
	Write-Host "no account specified"
	exit
}

## ---> End of Config

$sidstr = $null
try {
	$ntprincipal = new-object System.Security.Principal.NTAccount "$accountToAdd"
	$sid = $ntprincipal.Translate([System.Security.Principal.SecurityIdentifier])
	$sidstr = $sid.Value.ToString()
} catch {
	$sidstr = $null
}

Write-Host "Account: $($accountToAdd)" -ForegroundColor DarkCyan

if( [string]::IsNullOrEmpty($sidstr) ) {
	Write-Host "Account not found!" -ForegroundColor Red
	exit -1
}

Write-Host "Account SID: $($sidstr)" -ForegroundColor DarkCyan

$tmp = [System.IO.Path]::GetTempFileName()

Write-Host "Export current Local Security Policy" -ForegroundColor DarkCyan
secedit.exe /export /cfg "$($tmp)"

$c = Get-Content -Path $tmp

$currentSetting = ""

foreach($s in $c) {
	if( $s -like "SeServiceLogonRight*") {
		$x = $s.split("=",[System.StringSplitOptions]::RemoveEmptyEntries)
		$currentSetting = $x[1].Trim()
	}
}

if( $currentSetting -notlike "*$($sidstr)*" ) {
	Write-Host "Modify Setting ""Logon as a Service""" -ForegroundColor DarkCyan

	if( [string]::IsNullOrEmpty($currentSetting) ) {
		$currentSetting = "*$($sidstr)"
	} else {
		$currentSetting = "*$($sidstr),$($currentSetting)"
	}

	Write-Host "$currentSetting"

	$outfile = @"
[Unicode]
Unicode=yes
[Version]
signature="`$CHICAGO`$"
Revision=1
[Privilege Rights]
SeServiceLogonRight = $($currentSetting)
"@

	$tmp2 = [System.IO.Path]::GetTempFileName()


	Write-Host "Import new settings to Local Security Policy" -ForegroundColor DarkCyan
	$outfile | Set-Content -Path $tmp2 -Encoding Unicode -Force

	#notepad.exe $tmp2
	Push-Location (Split-Path $tmp2)

	try {
		secedit.exe /configure /db "secedit.sdb" /cfg "$($tmp2)" /areas USER_RIGHTS
		#write-host "secedit.exe /configure /db ""secedit.sdb"" /cfg ""$($tmp2)"" /areas USER_RIGHTS "
	} finally {
		Pop-Location
	}
} else {
	Write-Host "NO ACTIONS REQUIRED! Account already in ""Logon as a Service""" -ForegroundColor DarkCyan
}

Write-Host "Done." -ForegroundColor DarkCyan
tools\chocolateyinstall.ps1

If (Test-Path variable:shimgen)
{
  $RunningUnderChocolatey = $True
  Write-Output "Running under Chocolatey"
}

$ErrorActionPreference = 'Stop'; # stop on all errors
$toolsDir   = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$OSBits = ([System.IntPtr]::Size * 8) #Get-ProcessorBits

#On 64-bit, always favor 64-bit Program Files no matter what our execution is now (works back past XP / Server 2003)
If ($env:ProgramFiles.contains('x86'))
{
  $PF = $env:ProgramFiles.replace(' (x86)','')
}
Else
{
  $PF = $env:ProgramFiles
}

$filename = "$toolsdir\OpenSSH-Win$($OSBits).zip"
#$TargetFolder = "$PF\OpenSSH"
#$TargetFolderOld = "$PF\OpenSSH-Win$($OSBits)"
$TargetFolder = "$PF\OpenSSH-Win$($OSBits)"
$ExtractFolder = "$env:temp\OpenSSHTemp"

$packageArgs = @{
  packageName   = 'win32-openssh'
  unziplocation = "$ExtractFolder"
  fileType      = 'EXE_MSI_OR_MSU' #only one of these: exe, msi, msu
  url           = 'https://github.com/PowerShell/Win32-OpenSSH/releases/download/5_30_2016/OpenSSH-Win32.zip'
  url64bit      = 'https://github.com/PowerShell/Win32-OpenSSH/releases/download/5_30_2016/OpenSSH-Win64.zip'

  checksum      = 'B44CC37CCF9C3E4917440B1DFEBB8052'
  checksumType  = 'md5'
  checksum64    = '1D9574A785EB0CD45380DD33DB11D7B0'
  checksumType64= 'md5'
}

If ($RunningUnderChocolatey)
{
  # Default the values before reading params
  $SSHServerFeature = $false
  $KeyBasedAuthenticationFeature = $false
  $DeleteServerKeysAfterInstalled = $false
  $UseNTRights = $false

  $arguments = @{};
  $packageParameters = $env:chocolateyPackageParameters
}

<#
If (Test-Path $TargetFolderOld)
{
  Throw "Upgrading Win32-OpenSSH over the old folder ($TargetFolderOld) will result in unpredictable results, please uninstall (with the /DeleteConfigAndServerKeys switch) and reinstall instead.)."
}
#>

# Now parse the packageParameters using good old regular expression
if ($packageParameters) {
    $match_pattern = "\/(?<option>([a-zA-Z]+)):(?<value>([`"'])?([a-zA-Z0-9- _\\:\.]+)([`"'])?)|\/(?<option>([a-zA-Z]+))"
    #"
    $option_name = 'option'
    $value_name = 'value'

    if ($packageParameters -match $match_pattern ){
        $results = $packageParameters | Select-String $match_pattern -AllMatches
        $results.matches | % {
          $arguments.Add(
              $_.Groups[$option_name].Value.Trim(),
              $_.Groups[$value_name].Value.Trim())
      }
    }
    else
    {
      throw "Package Parameters were found but were invalid (REGEX Failure)"
    }

    if ($arguments.ContainsKey("SSHServerFeature")) {
        Write-Host "Including SSH Server Feature."
        $SSHServerFeature = $true
    }

    if ($arguments.ContainsKey("UseNTRights")) {
        Write-Host "Using ntrights.exe to set service permissions (will not work, but generate warning if WOW64 is not present on 64-bit machines)"
        $UseNTRights = $true
    }

    if ($arguments.ContainsKey("DeleteServerKeysAfterInstalled")) {
        Write-Host "Deleting server private keys after they have been secured."
        $DeleteServerKeysAfterInstalled = $true
    }

    if ($arguments.ContainsKey("KeyBasedAuthenticationFeature")) {
        Write-Host "Including LSA DLL Feature."
        $KeyBasedAuthenticationFeature = $true
        If (!$SSHServerFeature)
        {
          Write-Warning "KeyBasedAuthenticationFeature was specified, but is only value when SSHServerFeature is specified, ignoring..."
        }
    }

} else {
    Write-Debug "No Package Parameters Passed in";
}

Function CheckServicePath ($ServiceEXE,$FolderToCheck)
{
  #The modern way:
  #Return ([bool]((Get-WmiObject win32_service | ?{$_.Name -ilike "*$ServiceEXE*"} | select -expand PathName) -ilike "*$FolderToCheck*"))
  #The NANO TP5 Compatible Way:
  Return ([bool]((wmic service | ?{$_ -ilike "*$ServiceEXE*"}) -ilike "*$FolderToCheck*"))
}

#$SSHServiceInstanceExistsAndIsOurs = ([bool]((Get-WmiObject win32_service | ?{$_.Name -ilike 'sshd'} | select -expand PathName) -ilike "*$TargetFolder*"))
$SSHServiceInstanceExistsAndIsOurs = CheckServicePath 'sshd' "$TargetFolder"
#$SSHAGENTServiceInstanceExistsAndIsOurs = ([bool]((Get-WmiObject win32_service | ?{$_.Name -ilike 'ssh-agent'} | select -expand PathName) -ilike "*$TargetFolder*"))
$SSHAGENTServiceInstanceExistsAndIsOurs = CheckServicePath 'ssh-agent' "$TargetFolder"

If ($SSHServerFeature -AND (!$SSHServiceInstanceExistsAndIsOurs) -AND ([bool](Get-Service sshd -ErrorAction SilentlyContinue)))
{
  $ExistingSSHDInstancePath = split-path -parent (((wmic service | ?{$_ -ilike '*sshd*'}) -ilike "*$TargetFolder*").split('=')[1].trim())
  #(Get-WmiObject win32_service | ?{$_.Name -ilike 'sshd'} | select -expand PathName)
  Throw "You have requested that the SSHD service be installed, but this system appears to have an instance of an SSHD service configured for another folder ($ExistingSSHDInstancePath).  You can remove the package switch /SSHServerFeature to install just the client tools, or you will need to remove that instance of SSHD to use the one that comes with this package."
}

If ((!$SSHServerFeature) -AND $SSHServiceInstanceExistsAndIsOurs)
{
  Throw "There is a configured instance of the SSHD service, please specify the /SSHServerFeature to confirm it is OK to shutdown and upgrade the SSHD service at this time."
}

If ([bool](get-process ssh -erroraction silentlycontinue | where {$_.Path -ilike "*$TargetPath*"}))
{
  Throw "It appears you have instances of ssh.exe (client) running from the folder this package installs to, please terminate them and try again."
}

If ($SSHServiceInstanceExistsAndIsOurs -AND ([bool](Get-Service SSHD -ErrorAction SilentlyContinue | where {$_.Status -ieq 'Running'})))
{
    #Shutdown and unregister service for upgrade
    stop-service sshd -Force
    If (([bool](Get-Service SSHD | where {$_.Status -ieq 'Running'})))
    {
      Throw "Could not stop the SSHD service, please stop manually and retry this package."
    }
    If ($SSHAGENTServiceInstanceExistsAndIsOurs)
    {
      stop-service ssh-agent -Force
      If (([bool](Get-Service ssh-agent | where {$_.Status -ieq 'Running'})))
      {
        Throw "Could not stop the ssh-agent service, please stop manually and retry this package."
      }
    }

}

If ($SSHServiceInstanceExistsAndIsOurs)
{
  Stop-Service sshd
  sc.exe delete sshd | out-null
}
If ($SSHAGENTServiceInstanceExistsAndIsOurs)
{
  Stop-Service ssh-agent -erroraction silentlycontinue
  sc.exe delete ssh-agent | out-null
}

#Placing these security sensitive exe files in a location secure from viruses
# (and as per project install instructions)
If ($RunningUnderChocolatey)
{
  Install-ChocolateyZipPackage @packageArgs
  Install-ChocolateyPath "$TargetFolder" 'Machine'
}
Else
{
  If ($OSBits -eq 64)
  {
    $DownloadURL = $packageargs.url64bit
    $DownloadChecksum = $packageargs.checksum64
    $DownloadChecksumType = $packageargs.checksumType64
  }
  Else
  {
    $DownloadURL = $packageargs.url
    $DownloadChecksum = $packageargs.checksum
    $DownloadChecksumType = $packageargs.checksumType
  }
  $DownloadFileName = split-path -leaf $DownloadURL
  $DownloadFileFullPath = "$env:temp\$DownloadFileName"

  #Download Zip and compare hash
  Invoke-WebRequest -URI $DownloadURL -outfile $DownloadFileFullPath
  If ((Get-FileHash $DownloadFileFullPath -Algorithm $DownloadChecksumType).Hash -eq $DownloadChecksum)
  {
    Write-Output "Hashes Match"
  }
  #Unzip to targetfolder
  If ([bool](Get-command expand-archive -ea SilentlyContinue))
  {
    #covers Nano and server 2016
    Expand-Archive -Path $DownloadFileFullPath -DestinationPath $ExtractFolder
  }
  ElseIf (Test-Path "$toolsdir\7z.exe")
  {
    #use 7zip
  }
  Else
  {
    Throw "You need a copy of 7z.exe next to this script.  You can get a copy at 7-zip.org"
  }

  #add to path
}

Copy-Item "$ExtractFolder\*" "$PF" -Force -Recurse
Remove-Item "$ExtractFolder" -Force -Recurse

$SSHLsaVersionChanged = $true
If (Test-Path "$env:windir\system32\ssh-lsa.dll")
{
  #Using file size because open ssh files are not currently versioned.  Submitted problem report asking for versioning to be done
  If (((get-item $env:windir\system32\ssh-lsa.dll).length) -eq ((get-item $TargetFolder\ssh-lsa.dll).length))
  {$SSHLsaVersionChanged = $false}
}


If ($SSHServerFeature)
{
  Write-Warning "You have specified SSHServerFeature - this machine is being configured as an SSH Server including opening port 22."
  If ($KeyBasedAuthenticationFeature)
  {
    Write-Warning "You have specified KeyBasedAuthenticationFeature - a new lsa provider will be installed."
    If (Test-Path "$env:windir\sysnative")
    { #We are running in a 32-bit process under 64-bit Windows
      $sys32dir = "$env:windir\sysnative"
    }
    Else
    { #We are on a 32-bit OS, or 64-bit proc on 64-bit OS
      $sys32dir = "$env:windir\system32"
    }

    If ($SSHLsaVersionChanged)
    {
      Copy-Item "$TargetFolder\ssh-lsa.dll" "$sys32dir\ssh-lsa.dll" -Force
    }

    #Don't destroy other values
    $key = get-item 'Registry::HKLM\System\CurrentControlSet\Control\Lsa'
    $values = $key.GetValue("Authentication Packages")
    $values += 'msv1_0\0ssh-lsa.dll'
    Set-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\" "Authentication Packages" $values
  }

  If((Test-Path "$TargetFolder\sshd_config") -AND ([bool]((gc "$TargetFolder\sshd_config") -ilike "*#LogLevel INFO*")))
  {
    Write-Warning "Explicitly disabling sshd logging as it currently logs about .5 GB / hour"
    (Get-Content "$TargetFolder\sshd_config") -replace '#LogLevel INFO', 'LogLevel QUIET' | Set-Content "$TargetFolder\sshd_config"
  }

  If (!(Test-Path "$TargetFolder\KeysGenerated.flg"))
  { #Only ever generate a key the first time SSHD server is installed
      Write-Output "Generating sshd keys in `"$TargetFolder`""
      start-process "$TargetFolder\ssh-keygen.exe" -ArgumentList '-A' -WorkingDirectory "$TargetFolder" -nonewwindow -wait
      New-Item "$TargetFolder\KeysGenerated.flg" -type File | out-null
  }
  Else
  {
    Write-Warning "Found existing server ssh keys in $TargetFolder, you must delete them manually to generate new ones."
  }

  netsh advfirewall firewall add rule name='SSHD Port win32-openssh' dir=in action=allow protocol=TCP localport=22
  New-Service -Name ssh-agent -BinaryPathName "$TargetFolder\ssh-agent.exe" -Description "SSH Agent" -StartupType Automatic | Out-Null
  cmd.exe /c 'sc.exe sdset ssh-agent D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RP;;;AU)'

  Start-Service ssh-agent

  Start-Sleep -seconds 3

  $keylist = "ssh_host_dsa_key", "ssh_host_rsa_key", "ssh_host_ecdsa_key", "ssh_host_ed25519_key"
  $fullpathkeylist = "'$TargetFolder\ssh_host_dsa_key'", "'$TargetFolder\ssh_host_rsa_key'", "'$TargetFolder\ssh_host_ecdsa_key'", "'$TargetFolder\ssh_host_ed25519_key'"

  schtasks.exe /create /RU "NT AUTHORITY\SYSTEM" /RL HIGHEST /SC ONSTART /TN "ssh-add" /TR "'$TargetFolder\ssh-add.exe'  $fullpathkeylist" /F

  schtasks.exe /Run /I /TN "ssh-add"

  schtasks.exe /Delete /TN "ssh-add" /F

  #Start-Process "$toolsDir\psexec.exe" -ArgumentList "-accepteula -s -w `"$TargetFolder`" ssh-add.exe $keylist " -wait

  If ($DeleteServerKeysAfterInstalled)
  {
    pushd $TargetFolder
    Foreach ($keyfile in $keylist)
    {
      If (Test-Path $keyfile)
      {
        Remove-Item $keyfile -force
      }
    }
    popd
  }
  Else
  {
    Write-Warning "The following private keys should be removed from the machine: $keylist"
  }
  New-Service -Name sshd -BinaryPathName "$TargetFolder\sshd.exe" -Description "SSH Deamon" -StartupType Automatic -DependsOn ssh-agent | Out-Null
  sc.exe config sshd obj= "NT SERVICE\SSHD"

  If (!$UseNTRights)
  {
    #The code in this .PS1 has been tested on Nano - the hardest case to date for setting special privileges in script
    . "$toolsdir\AddAccountToLogonAsAService.ps1" -AccountToAdd "NT SERVICE\SSHD"
  }
  Else
  {
    If (($OSBits -eq 64) -and (!(Test-Path "$env:windir\syswow64")))
    {
      Write-Warning "This 64-bit system does not have the WOW64 subsystem installed, please manually grant the right SeLogonAsAService to `"NT SERVICE\SSHD`"."
      Write-Warning "OR try again WITHOUT the /UseNTRights switch."
    }
    Else
    {
      write-output "Using ntrights.exe to grant logon as service."
      Start-Process "$TargetFolder\ntrights.exe" -ArgumentList "-u `"NT SERVICE\SSHD`" +r SeServiceLogonRight"
    }
  }

  If (!$SSHLsaVersionChanged)
  {
    Write-Output "Starting sshd Service"
    Start-Service sshd
  }
  Else
  {
    Write-Warning "You must reboot so that key based authentication can be fully installed for the SSHD Service."
  }
}

Write-Warning "You must start a new prompt, or re-read the environment for the tools to be available in your command line environment."
tools\chocolateyuninstall.ps1

$ErrorActionPreference = 'Stop'; # stop on all errors

$packageName= 'win32-openssh'
$toolsDir   = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"

$OSBits = Get-ProcessorBits

#On 64-bit, always favor 64-bit Program Files no matter what our execution is now (works back past XP / Server 2003)
If ($env:ProgramFiles.contains('x86'))
{
  $PF = $env:ProgramFiles.replace(' (x86)','')
}
Else
{
  $PF = $env:ProgramFiles
}

#$TargetFolder = "$PF\OpenSSH"
$TargetFolder = "$PF\OpenSSH-Win$($OSBits)"
$TargetFolderOld = "$PF\OpenSSH-Win$($OSBits)"

# Default the values
$SSHServerFeature = $false
$KeyBasedAuthenticationFeature = $false

$arguments = @{};
$packageParameters = $env:chocolateyPackageParameters;

# Now parse the packageParameters using good old regular expression
if ($packageParameters) {
    $match_pattern = "\/(?<option>([a-zA-Z]+)):(?<value>([`"'])?([a-zA-Z0-9- _\\:\.]+)([`"'])?)|\/(?<option>([a-zA-Z]+))"
    #"
    $option_name = 'option'
    $value_name = 'value'

    if ($packageParameters -match $match_pattern ){
        $results = $packageParameters | Select-String $match_pattern -AllMatches
        $results.matches | % {
          $arguments.Add(
              $_.Groups[$option_name].Value.Trim(),
              $_.Groups[$value_name].Value.Trim())
      }
    }
    else
    {
      throw "Package Parameters were found but were invalid (REGEX Failure)"
    }

    if ($arguments.ContainsKey("SSHServerFeature")) {
        Write-Host "/SSHServerFeature - Uninstalling SSH Server Feature if Present."
        $SSHServerFeature = $true
    }

    if ($arguments.ContainsKey("DeleteConfigAndServerKeys")) {
        Write-Host "/DeleteConfigAndServerKeys - Removing SSH Config and Server Keys."
        $DeleteConfigAndServerKeys = $true
    }

} else {
    Write-Debug "No Package Parameters Passed in";
}

$SSHServiceInstanceExistsAndIsOurs = ([bool]((Get-WmiObject win32_service | ?{$_.Name -ilike 'sshd'} | select -expand PathName) -ilike "*$TargetFolder*"))

If ($SSHServerFeature -AND (!$SSHServiceInstanceExistsAndIsOurs) -AND (Get-Service sshd -ErrorAction SilentlyContinue))
{
  $ExistingSSHDInstancePath = (Get-WmiObject win32_service | ?{$_.Name -ilike 'sshd'} | select -expand PathName)
  Throw "You have requested that the SSHD service be uninstalled, but this system appears to have an instance of an SSHD service configured for another folder ($ExistingSSHDInstancePath).  Ignoring /SSHServerFeature"
  $SSHServerFeature = $False
}

If ((!$SSHServerFeature) -AND $SSHServiceInstanceExistsAndIsOurs)
{
  Throw "There is a configured instance of the SSHD service, please specify the /SSHServerFeature to confirm it is OK to UNINSTALL the SSHD service at this time."
}


If ([bool](get-process ssh -erroraction silentlycontinue | where {$_.Path -ilike "*$TargetPath*"}))
{
  Throw "It appears you have instances of ssh.exe (client) running from the folder this package installs to, please terminate them and try again."
}

If ($SSHServiceInstanceExistsAndIsOurs -AND ([bool](Get-Service SSHD -ErrorAction SilentlyContinue | where {$_.Status -ieq 'Running'})))
{
#Shutdown and unregister service for upgrade
    Stop-Service SSHD -Force
    Start-Sleep -seconds 3
    If (([bool](Get-Service SSHD | where {$_.Status -ieq 'Running'})))
    {
      Throw "Could not stop the SSHD service, please stop manually and retry this package."
    }
    Stop-Service ssh-agent -Force
    Start-Sleep -seconds 3
    If (([bool](Get-Service ssh-agent | where {$_.Status -ieq 'Running'})))
    {
      Throw "Could not stop the ssh-agent service, please stop manually and retry this package."
    }
}

If ((get-item 'Registry::HKLM\System\CurrentControlSet\Control\Lsa').getvalue("authentication packages") -contains 'msv1_0\0ssh-lsa.dll')
{
  $KeyBasedAuthenticationFeatureINSTALLED = $True
}

If ($SSHServiceInstanceExistsAndIsOurs -AND ([bool](Get-Service SSHD | where {$_.Status -ieq 'Running'})))
{
#Shutdown and unregister service for upgrade
    Stop-Service sshd -Force
    If (([bool](Get-Service SSHD | where {$_.Status -ieq 'Running'})))
    {
      Throw "Could not stop the SSHD service, please stop manually and retry this package."
    }
    Stop-Service ssh-agent -Force
    Start-Sleep -seconds 3
    If (([bool](Get-Service ssh-agent | where {$_.Status -ieq 'Running'})))
    {
      Throw "Could not stop the ssh-agent service, please stop manually and retry this package."
    }
}

If ($SSHServiceInstanceExistsAndIsOurs -AND ($SSHServerFeature))
{
  Stop-Service sshd
  sc.exe delete sshd 1> null
  Stop-Service ssh-agent
  sc.exe delete ssh-agent 1> null
}

If ($KeyBasedAuthenticationFeatureINSTALLED)
{
  If (Test-Path "$env:windir\sysnative")
  { #We are running in a 32-bit process under 64-bit Windows
    $sys32dir = "$env:windir\sysnative"
  }
  Else
  { #We are on a 32-bit OS, or 64-bit proc on 64-bit OS
    $sys32dir = "$env:windir\system32"
  }

  $AuthpkgToRemove = 'msv1_0\0ssh-lsa.dll'
  foreach ($authpackage in (get-item 'Registry::HKLM\System\CurrentControlSet\Control\Lsa').getvalue("authentication packages"))
  {
    If ($authpackage)
    {
      If ($authpackage -ine "$AuthpkgToRemove")
      {
        [string[]]$Newauthpackages += "$authpackage"
      }
    }
  }
  Set-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\" "Authentication Packages" $Newauthpackages
  del "$sys32dir\ssh-lsa.dll" -force
}

#Don't remove config in case they reinstall.
If ($DeleteConfigAndServerKeys)
{
    Write-Warning "Removing all config and server keys as requested by /DeleteConfigAndServerKeys"
    If (Test-Path $TargetFolder) {Remove-Item "$TargetFolder\*" -Recurse -Force}
    If (Test-Path $TargetFolderOLD) {Remove-Item "$TargetFolderOLD\*" -Recurse -Force}
}
Else
{

  If (Test-Path $TargetFolder) {Remove-Item "$TargetFolder\*.*" -include *.exe,*.dll,*.cmd -Recurse -Force}
  If (Test-Path $TargetFolderOLD) {Remove-Item "$TargetFolder\*.*" -include *.exe,*.dll,*.cmd -Recurse -Force}
  Write-Warning "NOT REMOVED: Config files and any keys in `"$TargetFolder`" were NOT REMOVED - you must remove them manually or use the package uninstall parameter /DeleteConfigAndServerKeys."
}
netsh advfirewall firewall delete rule name='SSHD Port win32-openssh'

$PathToRemove = "$TargetFolder"
foreach ($path in [Environment]::GetEnvironmentVariable("PATH","Machine").split(';'))
{
  If ($Path)
  {
    If (($path -ine "$PathToRemove") -AND ($path -ine "$PathToRemove\"))
    {
      [string[]]$Newpath += "$path"
    }
  }
}
$AssembledNewPath = ($newpath -join(';')).trimend(';')

[Environment]::SetEnvironmentVariable("PATH",$AssembledNewPath,"Machine")
tools\ntrights.exe
md5: 416C43AEB17252EE33048BD1F277D2A5 | sha1: 085DEB77551F9F6201E5AA352B62CAD91C3005E5 | sha256: F46BAA1B6227226518E42263E9B4808F81C27D060207DF160F9AC64DEAE4F4F5 | sha512: 3155DE3FB04F1DF246D6CECFA1C89F8AE9963C18BE1CE717731FF210AB39D537BE01231002A54D4346B4116E3505F387C92DFECC18A80CE7EB99C6D33E5F1F2A
tools\ntrights.exe.ignore
 
tools\PlainInstall.ps1

<#
.\Plaininstall.ps1 -SSHServerFeature -KeyBasedAuthenticationFeature
#>

Param (
  [Parameter(HelpMessage="Including SSH Server Feature.")]
  [switch]$SSHServerFeature,
  [Parameter(HelpMessage="Using ntrights.exe to set service permissions (will not work, but generate warning if WOW64 is not present on 64-bit machines)")]
  [switch]$UseNTRights,
  [Parameter(HelpMessage="Deleting server private keys after they have been secured.")]
  [switch]$DeleteServerKeysAfterInstalled,
  [Parameter(HelpMessage="Use key based authentication for SSHD, must also use -SSHServerFeature")]
  [switch]$KeyBasedAuthenticationFeature
  )

#$passedargList += $MyInvocation.BoundParameters.GetEnumerator() | foreach {$curarg = $_ ;"$(. { switch ($($curarg.Value)) {'true' { "-$($curarg.Key)" } 'false' { '' } default { "-$($curarg.Key) $($curarg.Value)" } }})"}

. ".\chocolateyinstall.ps1"

Log in or click on link to see number of positives.

In cases where actual malware is found, the packages are subject to removal. Software sometimes has false positives. Moderators do not necessarily validate the safety of the underlying software, only that a package retrieves software from the official distribution point and/or validate embedded software against official distribution point (where distribution rights allow redistribution).

Chocolatey Pro provides runtime protection from possible malware.

Add to Builder Version Downloads Last Updated Status
Win32 OpenSSH (Microsoft Port) 2016.05.30.20160908 24394 Saturday, September 10, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.05.30.20160902 12449 Saturday, September 3, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.05.30.20160827 9060 Saturday, August 27, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.05.30.20160807 6195 Thursday, August 11, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.05.30 12498 Saturday, June 4, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.05.15 645 Wednesday, May 18, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.04.05 115812 Wednesday, April 6, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.03.19 905 Sunday, March 20, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.02.25.20150315 667 Tuesday, March 15, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.02.25.20150310 664 Thursday, March 10, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.02.25 751 Sunday, February 28, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2015.12.22 729 Monday, February 15, 2016 Approved
Win32 OpenSSH (Microsoft Port) 0.0.0.9 520 Sunday, September 18, 2016 Approved

WARNING: Target folder is changing to re-align with current Win32-OpenSSH installation from the product team.
It is recommended that you uninstall and reinstall if you have an older version.
With switch /UseNTRights Package uses ntrights.exe on 32-bit windows and on 64-bit windows - ONLY IF THE 32-bit SUBSYSTEM IS INSTALLED - otherwise it attempts to use Posh Code to grant logonasaservice right.
Code used for setting rights WITHOUT /UseNTRights was tested as working on Nano, which means it should work on server core without WOW64.
Package explicity sets log level to QUIET because on some systems the current version of sshd repeatedly logs the same line at a rate of about 1 GB / 2 hours with default log settings.
Package incorporates securing of the server keys using the SSH agent as per the product release notes below.
Product release notes: https://github.com/PowerShell/Win32-OpenSSH/releases/tag/5_15_2016
https://github.com/PowerShell/Win32-OpenSSH/releases/tag/5_30_2016


This package has no dependencies.

Discussion for the Win32 OpenSSH (Microsoft Port) Package

Ground Rules:

  • This discussion is only about Win32 OpenSSH (Microsoft Port) and the Win32 OpenSSH (Microsoft Port) package. If you have feedback for Chocolatey, please contact the Google Group.
  • This discussion will carry over multiple versions. If you have a comment about a particular version, please note that in your comments.
  • The maintainers of this Chocolatey Package will be notified about new comments that are posted to this Disqus thread, however, it is NOT a guarantee that you will get a response. If you do not hear back from the maintainers after posting a message below, please follow up by using the link on the left side of this page or follow this link to contact maintainers. If you still hear nothing back, please follow the package triage process.
  • Tell us what you love about the package or Win32 OpenSSH (Microsoft Port), or tell us what needs improvement.
  • Share your experiences with the package, or extra configuration or gotchas that you've found.
  • If you use a url, the comment will be flagged for moderation until you've been whitelisted. Disqus moderated comments are approved on a weekly schedule if not sooner. It could take between 1-5 days for your comment to show up.
comments powered by Disqus