Notices: This section not yet converted to new layout. Download stats are rolling back out.

Win32 OpenSSH (Universal Installer)

0.0.24.0

Package test results are passing.

This package was approved as a trusted package on 12/5/2017.

Open SSH tools for Windows.

************************
This package is actually a universal installer that can install in any scenario - including without Chocolatey.
Read here for more information: https://github.com/DarwinJS/ChocoPackages/blob/master/openssh/readme.md
************************

CloudyWindows.io Utility Scripts:
* Set-SSHDefaultShell.ps1

See release notes for package parameters

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

C:\> choco install openssh

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

C:\> choco upgrade openssh

Files

Hide
  • tools\7z.dll Show
    md5: 9943B3BCB2CA91CCBEF2D96682CECB79 | sha1: D467F1F7A8407D1650060C8FE3DC6A0CCFF4D409 | sha256: 7F47382791A5264EED7310706E105C1CFA0E727359102F14933D4927BD296640 | sha512: D724BA334CEC2E3D69BBC93FEA635377EDC941962E2FFBE8246C2ADA80D445DEAB7F3BB5A18FCEAE295428C5B47CE42F3CD56F94AB9F170560DDDED167BE2995
  • tools\7z.exe Show
    md5: 506E5B371882A5A62B669F04CE04DBA8 | sha1: 7447EB123655792FEDE586AD049AC737EFFA9E6C | sha256: BB783A594067DB5CB4E43030D9E6928636555A9CE6AA3533532731975094230A | sha512: 7F367D22B95E14AF8BDA3BE1354A4A54EDFDA283700D086878FEA72B349E64B497F2D241AE31E0B2B0C56957D3A39299E51E09B0D67D2C6201AE20033555212E
  • tools\7z.exe.ignore
  • tools\barebonesinstaller.ps1 Show
    <#
    .SYNOPSIS
    Enables installing SSH even when your system does not have WOW64 or Chocolatey.
    .DESCRIPTION
    This script enables installing  SSH even when your system does NOT have:
      [1] Chocolatey installed
      [2] WOW64 installed
      [3] .NET Core (Nano)
    
    The use cases are Server Nano and Server Core without WOW64 installed.
    
    To use barebonesinstaller.ps1, expand the .nupkg that this file is contained in
    and then place the \tools folder on the target system.
    
    To push tools folder to Nano use 'Copy-Item -tosession $sessionvariable tools c:\tools -recurse'
    .PARAMETER SSHServerFeature
    Include SSH Server Feature.
    .PARAMETER SSHServerPort
    The port that SSHD Server should listen on.
    .PARAMETER DeleteServerKeysAfterInstalled
    Delete server private keys after they have been secured
    .PARAMETER DeleteConfigAndServerKeys
    Delete server private keys and configuration upon uninstall.
    .PARAMETER Uninstall
    Uninstall (default is to install)
    .PARAMETER DisableKeyPermissionsReset
    By default the install runs a custom utility script called "Reset-SSHKeyPermissions.ps1". This switch disables that functionality.
    .EXAMPLE
    .\barebonesinstaller.ps1 -SSHServerFeature
    .EXAMPLE
    .\barebonesinstaller.ps1 -SSHServerFeature -Uninstall
    #>
    
    Param (
      [switch]$SSHServerFeature,
      [string]$SSHServerPort='22',
      [switch]$DeleteServerKeysAfterInstalled,
      [switch]$DeleteConfigAndServerKeys,
      [switch]$UseNTRights,
      [switch]$Uninstall,
      [switch]$OverWriteSSHDConf,
      [string]$SSHLogLevel,
      [switch]$ReleaseSSHLSAForUpgrade,
      [string]$TERM,
      [switch]$DisableKeyPermissionsReset,
      [string]$PathSpecsToProbeForShellEXEString,
      [string]$SSHDefaultShellCommandOption,
      [switch]$AllowInsecureShellEXE
      )
    
    Write-Output "Configuring on Port $SSHServerPort"
    
    cd "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
    
    If (!$Uninstall)
    {
      . ".\chocolateyinstall.ps1"
    }
    Else
    {
      . ".\chocolateyuninstall.ps1"
    }
    
  • tools\chocolateyinstall.ps1 Show
    <#
    ATTENTION: This code is used extensively to run under PowerShell 2.0 to update 
    images from RTM / SP1 source for Windows 7 and Server 2008 R2.  It is also
    used under Powershell Core to add OpenSSH to Nano.  Test all enhancements and 
    fixes under these two specialty cases (speciality for Chocolatey packagers who are 
    likely up to the latest version on everything PowerShell).
    #>
    
    
    $ErrorActionPreference = 'Stop'; # stop on all errors
    
    $ProductName = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name 'ProductName').ProductName
    $EditionId = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name 'EditionID').EditionId
    
    #This has to work for Win7 (no get-ciminstance) and Nano (no get-wmiobject) - each of which specially construct win32_operatingsystem.version to handle before and after Windows 10 version numbers (which are in different registry keys)
    If ($psversiontable.psversion.major -lt 3)
    {
      $OSVersionString = (Get-WMIObject Win32_OperatingSystem).version
    }
    Else 
    {
      $OSVersionString = (Get-CIMInstance Win32_OperatingSystem).version
    }
    
    
    Write-Output "Running on: $ProductName, ($EditionId)"
    Write-Output "Windows Version: $OSVersionString"
    
    $RunningOnNano = $False
    If ($EditionId -ilike '*Nano*')
    {$RunningOnNano = $True}
    
    If (Test-Path variable:shimgen)
    {$RunningUnderChocolatey = $True}
    Else
    {  Write-Output "Running Without Chocolatey"}
    
    $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
    }
    
    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"
    }
    $filename = "$toolsdir\OpenSSH-Win$($OSBits).zip"
    #$TargetFolder = "$PF\OpenSSH"
    #$TargetFolderOld = "$PF\OpenSSH-Win$($OSBits)"
    $TargetFolder = "$PF\OpenSSH-Win$($OSBits)"
    $ExtractFolder = "$env:temp\OpenSSHTemp"
    $TERMDefault = 'xterm' #Overall Default
    If ([version]$OSVersionString -ge [version]'10.0.0')
    {
      $TERMDefault = 'xterm-256color' #Windows 10 / 2016 default
    }
    
    $packageArgs = @{
      packageName   = 'openssh'
      unziplocation = "$ExtractFolder"
      fileType      = 'EXE_MSI_OR_MSU' #only one of these: exe, msi, msu
    
      checksum      = '40C0198122F4B0F8BDDF5345D3C5340132647D23'
      checksumType  = 'SHA1'
      checksum64    = 'A181D320159DDA8188BEE172F6AADECDFB9FCC1D'
      checksumType64= 'SHA1'
    }
    
    If ($RunningUnderChocolatey)
    {
      # Default the values before reading params
      $SSHServerFeature = $false
      $KeyBasedAuthenticationFeature = $false
      $DeleteServerKeysAfterInstalled = $false
      $UseNTRights = $false
      $SSHServerPort = '22'
      $DisableKeyPermissionsReset = $False
    
      $arguments = @{};
      $packageParameters = $env:chocolateyPackageParameters
    }
    
    $OpeningMessage = @"
    
    ************************************************************************************
    ************************************************************************************
    This package is a Universal Installer and can ALSO install Win32-OpenSSH on 
    Nano, Server Core, Docker Containers and more WITHOUT using Chocolatey.
    
    See the following for more details:
    https://github.com/DarwinJS/ChocoPackages/blob/master/openssh/readme.md
    ************************************************************************************
    ************************************************************************************
    
    "@
    
    Write-Output $OpeningMessage
    
    function Get-PackageParametersCustom {
      [CmdletBinding()]
      param(
         [string] $Parameters = $Env:ChocolateyPackageParameters,
         # Allows splatting with arguments that do not apply and future expansion. Do not use directly.
         [parameter(ValueFromRemainingArguments = $true)]
         [Object[]] $IgnoredArguments
      )
    
      $res = @{}
    
      $re = "\/([a-zA-Z0-9]+)(:[`"'].+?[`"']|[^ ]+)?"
      $results = $Parameters | Select-String $re -AllMatches | select -Expand Matches
      foreach ($m in $results) {
          if (!$m) { continue } # must because of posh 2.0 bug: https://github.com/chocolatey/chocolatey-coreteampackages/issues/465
    
          $a = $m.Value -split ':'
          $opt = $a[0].Substring(1); $val = $a[1..100] -join ':'
          if ($val -match '^(".+")|(''.+'')$') {$val = $val -replace '^.|.$'}
          $res[ $opt ] = if ($val) { $val } else { $true }
      }
      $res
    }
    
    
    # Now parse the packageParameters using good old regular expression
    if ($packageparameters) {
    
      $pp = Get-PackageParametersCustom
      
        if ($pp.SSHAgentFeature) {
            Write-Host "/SSHAgentFeature was used, including SSH Agent Service."
            $SSHAgentFeature = $true
        }
    
        if ($pp.SSHServerFeature) {
            Write-Host "/SSHServerFeature was used, including SSH Server Feature."
            $SSHServerFeature = $true
        }
    
        if ($pp.DisableKeyPermissionsReset) {
            Write-Host "/DisableKeyPermissionsReset was used, will not reset key permissions."
            $DisableKeyPermissionsReset = $true
        }
    
        if ($pp.OverWriteSSHDConf) {
            Write-Host "/OverWriteSSHDConf was used, will overwrite any existing sshd_conf with one from install media."
            $OverWriteSSHDConf = $true
        }
    
        if ($pp.SSHServerPort) {
            $SSHServerPort = $pp.Get_Item("SSHServerPort")
            Write-Host "/SSHServerPort was used, attempting to use SSHD listening port $SSHServerPort."
            If (!$SSHServerFeature)
            {
              Write-Host "You forgot to specify /SSHServerFeature with /SSHServerPort, autofixing for you, enabling /SSHServerFeature"
              $SSHServerFeature = $true
            }
        }
    
        if ($pp.SSHLogLevel) {
    
          $ValidLogSettings = @('QUIET', 'FATAL', 'ERROR', 'INFO', 'VERBOSE', 'DEBUG', 'DEBUG1', 'DEBUG2','DEBUG3')
          $SSHLogLevel = $pp.Get_Item("SSHLogLevel").toupper()
          If ($ValidLogSettings -inotcontains $SSHLogLevel)
          {Throw "$SSHLogLevel is not one of the valid values: $(($ValidLogSettings -join ' ') | out-string)"}
          Write-Host "/SSHLogLevel was used, setting LogLevel in sshd_conf to $SSHLogLevel"
    
        }
        Else
        {
          $SSHLogLevel = $null
        }
    
        if ($pp.TERM) {
          $TERM = $pp.Get_Item("TERM")
          Write-Host "/TERM was used, setting system TERM environment variable to $TERM"
          $TERMSwitchUsed = $True
        }
        Else
        {
          $TERM = 'xterm'
          Write-Host "Defaulting system TERM environment variable to $TERM"
        }
    
        if ($pp.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 ($pp.DeleteServerKeysAfterInstalled) {
            Write-Host "Deleting server private keys after they have been secured."
            $DeleteServerKeysAfterInstalled = $true
        }
    
        if ($pp.KeyBasedAuthenticationFeature) {
            Write-Host "Including Key based authentication."
            $KeyBasedAuthenticationFeature = $true
            If (!$SSHServerFeature)
            {
              Write-Warning "KeyBasedAuthenticationFeature was specified, but is only value when SSHServerFeature is specified, ignoring..."
            }
        }
    
        if ($pp.PathSpecsToProbeForShellEXEString) {
          $PathSpecsToProbeForShellEXEString = $pp.Get_Item("PathSpecsToProbeForShellEXEString")
    
          Write-Host "PathSpecsToProbeForShellEXEString was used, probing for suitable shell using search specs: $PathSpecsToProbeForShellEXEString"
        }
    
        if ($pp.AllowInsecureShellEXE) {
          $AllowInsecureShellEXE = $True
        }
    
        if ($pp.SSHDefaultShellCommandOption) {
          $SSHDefaultShellCommandOption = $pp.Get_Item("SSHDefaultShellCommandOption")
        }
    
    } 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*"))
    }
    
    #Extract Files Early
    If ($RunningUnderChocolatey)
    {
      If (Test-Path $ExtractFolder)
      {
        Remove-Item $ExtractFolder -Recurse -Force
      }
      Get-ChocolateyUnzip "$filename" $ExtractFolder
    }
    Else
    {
      If (Test-Path "$toolsdir\7z.exe")
      {
        #covers nano
        cd $toolsdir
        start-process .\7z.exe -argumentlist "x `"$filename`" -o`"$ExtractFolder`" -aoa" -nonewwindow -wait
      }
      Else
      {
        Throw "You need a copy of 7z.exe next to this script for this operating system.  You can get a copy at 7-zip.org"
      }
    }
    
    If ($SSHServerFeature -OR $SSHAgentFeature)
    {
      . "$toolsdir\SetSpecialPrivileges.ps1"
    }
    
    If ($SSHServerFeature)
    {  #Check if anything is already listening on port $SSHServerPort, which is not a previous version of this software.
      Write-Host "/SSHAgentFeature is also automatically enabled when using /SSHServerFeature."
      $SSHAgentFeature = $true
      $AtLeastOneSSHDPortListenerIsNotUs = $False
      Write-Output "Probing for possible conflicts with SSHD server to be configured on port $SSHServerPort ..."
      . "$toolsdir\Get-NetStat.ps1"
      $procslisteningonRequestedSSHDPort = @(Get-Netstat -GetProcessDetails -FilterOnPort $SSHServerPort)
      If ((checkservicepath 'svchost.exe -k SshBrokerGroup' 'Part of Microsoft SSH Server for Windows') -AND (checkservicepath 'svchost.exe -k SshProxyGroup' 'Part of Microsoft SSH Server for Windows'))
      {
        Write-Warning "  > Detected that Developer Mode SSH is present (Probably due to enabling Windows 10 Developer Mode)"
        $DeveloperModeSSHIsPresent = $True
      }
    
      If ($procslisteningonRequestedSSHDPort.count -ge 1)
      {
        ForEach ($proconRequestedSSHDPort in $procslisteningonRequestedSSHDPort)
        {
          Write-output "  > Checking $($proconRequestedSSHDPort.Localaddressprocesspath) against path $TargetFolder"
          If ("$($proconRequestedSSHDPort.Localaddressprocesspath)" -ilike "*$TargetFolder*")
          {
            Write-Output "  > Found a previous version of Win32-OpenSSH installed by this package on Port $SSHServerPort."
          }
          Else
          {
            $AtLeastOneSSHDPortListenerIsNotUs = $True
            Write-Warning "  > Found something listening on Port $SSHServerPort that was not installed by this package."
            Write-Warning "      $($proconRequestedSSHDPort.LocalAddressProcessPath) is listening on Port $SSHServerPort"
            $ProcessOccupyingPort = "$($proconRequestedSSHDPort.LocalAddressProcessPath)"
          }
        }
      }
    
      If ($AtLeastOneSSHDPortListenerIsNotUs)
      {
      $errorMessagePort = @"
    "$ProcessOccupyingPort" is listening on port $SSHServerPort and you have not specified a different listening port (list above) using the /SSHServerPort parameter.
    Please either deconfigure or deinstall whatever is running on Port $SSHServerPort and try again OR specify a different port for this SSHD Server using the /SSHServerPort package parameter.
    If you see the message 'Detected that Developer Mode SSH is present' above, you may be able to simply disable the services 'SSHBroker' and 'SSHProxy'
    "@
      Throw $errorMessagePort
      }
    }
    
    $SSHServiceInstanceExistsAndIsOurs = CheckServicePath 'sshd.exe' "$TargetFolder"
    $SSHAGENTServiceInstanceExistsAndIsOurs = CheckServicePath 'ssh-agent.exe' "$TargetFolder"
    
    If ($SSHServerFeature -AND (!$SSHServiceInstanceExistsAndIsOurs) -AND ([bool](Get-Service sshd -ErrorAction SilentlyContinue)))
    {
      $ExistingSSHDInstancePath = get-itemproperty hklm:\system\currentcontrolset\services\* | where {($_.ImagePath -ilike '*sshd.exe*')} | Select -expand ImagePath
      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 "*$TargetFolder*"}))
    {
      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 ((Test-Path $TargetFolder) -AND (@(dir "$TargetFolder\*.exe").count -gt 0)) 
    {
      Write-Output "`r`nCURRENT VERSIONS OF SSH EXES:"
        Write-Output "$(dir "$TargetFolder\*.exe"| select -expand fullname | get-command | select -expand fileversioninfo | ft filename, fileversion -auto | out-string)"
    }
    
    If (Test-Path "$env:windir\system32\ssh-lsa.dll") 
    {
      Write-Output "`r`nCURRENT VERSION OF SSH-LSA.DLL:"
      Write-Output "$(get-command "$env:windir\system32\ssh-lsa.dll" | select -expand fileversioninfo | ft filename, fileversion -auto | out-string)"
    }
    
    If ($SSHServiceInstanceExistsAndIsOurs -AND ([bool](Get-Service SSHD -ErrorAction SilentlyContinue | where {$_.Status -ieq 'Running'})))
    {
        #Shutdown and unregister service for upgrade
        stop-service sshd -Force
        Stop-Service SSH-Agent -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."
        }
        If ($SSHAGENTServiceInstanceExistsAndIsOurs)
        {
          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)
    {
      Write-output "Stopping SSHD Service for upgrade..."
      Stop-Service sshd
      sc.exe delete sshd | out-null
    }
    If ($SSHAGENTServiceInstanceExistsAndIsOurs)
    {
      Write-output "Stopping SSH-Agent Service for upgrade..."
      Stop-Service ssh-agent -erroraction silentlycontinue
      sc.exe delete ssh-agent | out-null
    }
    
    If ($OSBits -eq 64)
    {
      $SourceZipChecksum = $packageargs.checksum64
      $SourceZipChecksumType = $packageargs.checksumType64
    }
    Else
    {
      $SourceZipChecksum = $packageargs.checksum
      $SourceZipChecksumType = $packageargs.checksumType
    }
    
    If ([bool](get-command get-filehash -ea silentlycontinue))
    {
      If ((Get-FileHash $filename -Algorithm $SourceZipChecksumType).Hash -eq $SourceZipChecksum)
      {
        Write-Output "Hashes for internal source match"
      }
      Else
      {
        throw "Checksums for internal source do not match - something is wrong."
      }
    }
    Else
    {
      Write-Output "Source files are internal to the package, checksums are not required nor checked."
    }
    
    $ExcludeParams = @{}
    If ((Test-Path "$TargetFolder\sshd_config") -AND !($OverWriteSSHDConf))
    {
      Write-Output "sshd_config already exists, not overwriting"
      $ExcludeParams.Add("Exclude","sshd_config")
    }
    
    Copy-Item "$ExtractFolder\*" "$PF" @ExcludeParams -Force -Recurse -Passthru -ErrorAction Stop
    #Fixed version of module
    #Write-Host "Updating OpenSSHUtils PowerShell Module to Latest"
    #Copy-Item "$toolsdir\OpenSSHUtils.ps*" "$TargetFolder" -Force -PassThru -ErrorAction Stop
    Copy-Item "$toolsdir\Set-SSHDefaultShell.ps1" "$TargetFolder" -Force -PassThru -ErrorAction Stop
    
    Remove-Item "$ExtractFolder" -Force -Recurse
    
    If ($RunningUnderChocolatey)
    {
      Install-ChocolateyPath "$TargetFolder" 'Machine'
    }
    Else
    {
      $PathToAdd = $TargetFolder
      $ExistingPathArray = @(((Get-ItemProperty 'Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' | select -expand path).split(';')))
      if (($ExistingPathArray -inotcontains $PathToAdd) -AND ($ExistingPathArray -inotcontains "$PathToAdd\"))
      {
        $Newpath = $ExistingPathArray + @("$PathToAdd")
        $AssembledNewPath = ($newpath -join(';')).trimend(';')
        Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -Name 'PATH' -Value "$AssembledNewPath"
      }
    }
    If ($env:Path -inotlike "*$TargetFolder*")
    {
      $env:path += ";$TargetFolder"
    }
    
    $ExistingTermValue = $null
    $ExistingTermValue = (get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -EA SilentlyContinue | Select -Expand TERM -EA SilentlyContinue)
    
    If (!$TERM) {$TERM = $TERMDefault}
    
    If ((!$ExistingTermValue) -OR ($ExistingTermValue -ine $TERM))
    { 
      Write-Host "Updating machine environment variable TERM from `"$ExistingTermValue`" to `"$TERM`""
      Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -Name 'TERM' -Value "$TERM"
    }
    
    If ($SSHAgentFeature)
    {
      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
    
      If (!$UseNTRights)
      {
        #The code in this .PS1 has been tested on Nano - the hardest case to date for setting special privileges in script
        $sshagentSid = (Get-OpenSSHUserSID -User "NT SERVICE\SSH-Agent").Value
        Add-OpenSSHPrivilege -Account $sshagentSid -Privilege SeServiceLogonRight
      }
      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\SSH-Agent`" +r SeServiceLogonRight"
        }
      }
    }
    
    If ($SSHServerFeature)
    {
      Write-Warning "You have specified SSHServerFeature - this machine is being configured as an SSH Server including opening port $SSHServerPort."
    
      If((Test-Path "$TargetFolder\sshd_config"))
      {
        #(Get-Content "$TargetFolder\sshd_config") -replace '#LogLevel INFO', 'LogLevel QUIET' | Set-Content "$TargetFolder\sshd_config"
    
        $CurrentLogLevelConfig = ((gc "$TargetFolder\sshd_config") -imatch "^#*LogLevel\s\w*\b.*$")
        Write-Output 'Setting up SSH Logging'
        If ($SSHLogLevel)
        { #command line specified a log level - override whatever is there
          If ([bool]($CurrentLogLevelConfig -inotmatch "^LogLevel\s$SSHLogLevel\s*$"))
          {
            Write-Output "Current LogLevel setting in `"$TargetFolder\sshd_config`" is `"$CurrentLogLevelConfig`", setting it to `"LogLevel $SSHLogLevel`""
            (Get-Content "$TargetFolder\sshd_config") -replace "^#*LogLevel\s\w*\b.*$", "LogLevel $SSHLogLevel" | Set-Content "$TargetFolder\sshd_config"
          }
        }
        Else
        { #command line did not specify a log level, set it to QUIET - only if it has never been set (currently commented INFO setting)
          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"
          }
        }
    
         $CurrentPortConfig = ((gc "$TargetFolder\sshd_config") -match "^#*Port\s\d*\s*$")
         If ([bool]($CurrentPortConfig -notmatch "^Port $SSHServerPort"))
         {
           Write-Output "Current port setting in `"$TargetFolder\sshd_config`" is `"$CurrentPortConfig`", setting it to `"Port $SSHServerPort`""
           (Get-Content "$TargetFolder\sshd_config") -replace "^#*Port\s\d*\s*$", "Port $SSHServerPort" | Set-Content "$TargetFolder\sshd_config"
         }
         Else
         {
           Write-Output "Current port setting in `"$TargetFolder\sshd_config`" already matches `"Port $SSHServerPort`", no action necessary."
         }
      }
    
      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."
      }
    
      
    
      If ($PathSpecsToProbeForShellEXEString)
      {
        $ParamsSSHDefaultShell = @{}
        $ParamsSSHDefaultShell.add('PathSpecsToProbeForShellEXEString',"$PathSpecsToProbeForShellEXEString")
        If ($AllowInsecureShellEXE) {$ParamsSSHDefaultShell += @{'AllowInsecureShellEXE'=$AllowInsecureShellEXE}}
        If ($SSHDefaultShellCommandOption) {$ParamsSSHDefaultShell += @{'SSHDefaultShellCommandOption'="$SSHDefaultShellCommandOption"}}
        
        Write-Host "$ParamsSSHDefaultShell"
      
        . $TargetFolder\Set-SSHDefaultShell.ps1 @ParamsSSHDefaultShell
      }
    
      netsh advfirewall firewall add rule name='SSHD Port OpenSSH (chocolatey package: openssh)' dir=in action=allow protocol=TCP localport=$SSHServerPort
    
      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 Daemon" -StartupType Automatic -DependsOn ssh-agent | Out-Null
      sc.exe config sshd obj= "NT SERVICE\SSHD"
      sc.exe privs sshd SeAssignPrimaryTokenPrivilege
      
      If (!$DisableKeyPermissionsReset)
      {
        Write-Host "Ensuring all ssh key and configuration files have correct permissions for all users"
        . "$TargetFolder\FixHostFilePermissions.ps1" -Confirm:$false
      }
    
      $logsdir = "$TargetFolder\Logs"
      If (!(Test-Path $logsdir))
      {
        New-Item $logsdir -ItemType Directory | out-null
        $rights = [System.Security.AccessControl.FileSystemRights]"Read, Write"
        $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("NT SERVICE\sshd", $rights, "ContainerInherit,ObjectInherit", "None", "Allow")
        If (!$RunningOnNano)
        {
          $aclAccess = (Get-Item -Path $logsdir).GetAccessControl('Access')
          $aclAccess.SetAccessRule($accessRule)
          Set-Acl -AclObject $aclAccess -Path $logsdir -Confirm:$false
        }
        Else
        {
          $aclAccess = Get-Acl -Path $logsdir
          $aclAccess.SetAccessRule($accessRule)
          Set-Acl -Path $logsdir -AclObject $aclAccess
        }
      }
    
      If (!$UseNTRights)
      {
        #The code in this .PS1 has been tested on Nano - the hardest case to date for setting special privileges in script
        $sshdSid = (Get-OpenSSHUserSID -User "NT SERVICE\SSHD").value
        Add-OpenSSHPrivilege -Account $sshdSid -Privilege SeAssignPrimaryTokenPrivilege
        Add-OpenSSHPrivilege -Account $sshdSid -Privilege SeServiceLogonRight
      }
      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 SeAssignPrimaryTokenPrivilege"
          Start-Process "$TargetFolder\ntrights.exe" -ArgumentList "-u `"NT SERVICE\SSH-Agent`" +r SeServiceLogonRight"
        }
      }
    }
    
    If (CheckServicePath 'sshd.exe' "$TargetFolder")
    {
      write-output "Starting SSHD..."
      Start-Service SSHD
    }
    If (CheckServicePath 'ssh-agent.exe' "$TargetFolder")
    {
      write-output "Starting SSH-Agent..."
      Start-Service SSH-Agent
    }
    
    $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'"
    
    
    If ($SSHServerFeature)
    {
      If (!(Test-Path "$TargetFolder\KeysAddedToAgent.flg"))
      {
        Write-Output "Installing Server Keys into SSH-Agent"
    
        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
    
        New-Item "$TargetFolder\KeysAddedToAgent.flg" -type File | out-null
      }
      
    }
    
    If (Test-Path "$TargetFolder\ssh.exe") 
    {
      Write-Output "`r`nNEW VERSIONS OF SSH EXES:"
      Write-Output "$(dir "$TargetFolder\*.exe" | select -expand fullname | get-command | select -expand fileversioninfo | ft filename, fileversion -auto | out-string)"
    }
    
    write-output ""
    Write-Warning "You must start a new prompt, or use the command 'refreshenv' (provided by your chocolatey install) to re-read the environment for the tools to be available in this shell session."
    
  • tools\chocolateyuninstall.ps1 Show
    $ErrorActionPreference = 'Stop'; # stop on all errors
    $ProductName = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name 'ProductName').ProductName
    $EditionId = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name 'EditionID').EditionId
    
    Write-Output "Running on: $ProductName, ($EditionId)"
    
    $RunningOnNano = $False
    If ($EditionId -ilike '*Nano*')
    {$RunningOnNano = $True}
    
    If (Test-Path variable:shimgen)
    {$RunningUnderChocolatey = $True}
    Else
    { Write-Output "Running Without Chocolatey"
    $RunningUnderChocolatey = $False}
    
    $packageName= 'openssh'
    $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
    }
    
    #$TargetFolder = "$PF\OpenSSH"
    $TargetFolder = "$PF\OpenSSH-Win$($OSBits)"
    $TargetFolderOld = "$PF\OpenSSH-Win$($OSBits)"
    
    If ($RunningUnderChocolatey)
    {
      # Default the values before reading params
      $SSHServerFeature = $false
      $KeyBasedAuthenticationFeature = $false
      $DeleteConfigAndServerKeys = $false
    
      $arguments = @{};
      $packageParameters = $env:chocolateyPackageParameters
    }
    # Now parse the packageParameters using good old regular expression
    if ((test-path variable:packageparameters) -AND $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";
    }
    
    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 (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'})))
    {
        Stop-Service SSHD -Force
        Stop-Service SSH-Agent -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."
        }
    }
    
    $KeyBasedAuthenticationFeatureINSTALLED = $False
    If ((get-item 'Registry::HKLM\System\CurrentControlSet\Control\Lsa').getvalue("authentication packages") -contains 'ssh-lsa')
    {
      $KeyBasedAuthenticationFeatureINSTALLED = $True
      Write-Warning "ssh-lsa.dll will be deconfigured - but not deleted.  It must be manually deleted after a reboot."
    }
    
    #uninstall agent service if it was installed without SSHD
    If ($SSHAGENTServiceInstanceExistsAndIsOurs -AND (!$SSHServiceInstanceExistsAndIsOurs))
    {
      Stop-Service ssh-agent -Force
      sc.exe delete ssh-agent | out-null
    }
    
    If ($SSHServiceInstanceExistsAndIsOurs -AND ($SSHServerFeature))
    {
      Stop-Service sshd -Force
      sc.exe delete sshd  | out-null
      Stop-Service ssh-agent -Force
      sc.exe delete ssh-agent | out-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 = 'ssh-lsa'
      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
    }
    
    #Don't remove config in case they reinstall.
    If (($SSHServiceInstanceExistsAndIsOurs -AND $DeleteConfigAndServerKeys) -OR (!$SSHServiceInstanceExistsAndIsOurs))
    {
        Write-Warning "Removing all config and server keys as requested by /DeleteConfigAndServerKeys"
        
        #Ensure we have permissions to all keys and config files:
        #$ErrorActionPreference = 'SilentlyContinue'
        If (Test-Path "$TargetFolder\OpenSSHUtils.psm1") {Import-Module "$TargetFolder\OpenSSHUtils" -Force}
        $RunningUser = New-Object System.Security.Principal.NTAccount($($env:USERDOMAIN), $($env:USERNAME))
        #dir "$TargetFolder\*" | % {repair-filepermission -FilePath $_.fullname -ReadAccessOK $RunningUser -AnyAccessOK $RunningUser -ReadAccessNeeded $RunningUser -confirm:$false}
        dir "$TargetFolder\*" | % {repair-filepermission -FilePath $_.fullname -confirm:$false}
        If (Test-Path $TargetFolder) {Remove-Item "$TargetFolder" -Recurse -Force}
        #$ErrorActionPreference = 'Stop'
    }
    Else
    {
    
      If (Test-Path $TargetFolder) {Get-ChildItem "$TargetFolder\*.*" -include *.exe,*.dll,*.cmd,*.ps1,*.psm1,*.psd1 | Remove-Item -Recurse -Force}
      If (Test-Path "$TargetFolder\logs") {Remove-Item "$TargetFolder\logs" -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 OpenSSH (chocolatey package: openssh)'
    
    $PathToRemove = "$TargetFolder"
    #Code has been modified to work with Nano - do not change method of environment variable access
    #foreach ($path in [Environment]::GetEnvironmentVariable("PATH","Machine").split(';'))
    foreach ($path in ((Get-ItemProperty 'Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment').path.split(';')))
    {
      If ($Path)
      {
        If (($path -ine "$PathToRemove") -AND ($path -ine "$PathToRemove\"))
        {
          [string[]]$Newpath += "$path"
        }
      }
    }
    $AssembledNewPath = ($newpath -join(';')).trimend(';')
    
    Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -Name 'PATH' -Value "$AssembledNewPath"
    
    $TermVarExists = [bool](get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -Name 'TERM' -EA SilentlyContinue)
    If ($TermVarExists)
    {
      Remove-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -Name 'TERM'
    }
  • tools\fileinuseutils.ps1 Show
    Add-Type @'
        using System;
        using System.Text;
        using System.Runtime.InteropServices;
    
        public class LockedFileUtils
        {
          public enum MoveFileFlags
          {
              MOVEFILE_REPLACE_EXISTING           = 0x00000001,
              MOVEFILE_COPY_ALLOWED               = 0x00000002,
              MOVEFILE_DELAY_UNTIL_REBOOT         = 0x00000004,
              MOVEFILE_WRITE_THROUGH              = 0x00000008,
              MOVEFILE_CREATE_HARDLINK            = 0x00000010,
              MOVEFILE_FAIL_IF_NOT_TRACKABLE      = 0x00000020
          }
    
            [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
            static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, MoveFileFlags dwFlags);
    
            public static bool DeleteLockedFile (string sourcefile)
            {
                return MoveFileEx(sourcefile, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);
            }
            public static bool CopyLockedFile (string sourcefile, string destination)
            {
                return MoveFileEx(sourcefile, destination, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);
            }
        }
    '@
    
    Function Remove-FileEvenIfLocked
    {
      param ([parameter(mandatory=$true,ValueFromPipeline=$true)][string]$Path)
      Process
      {
        $path = (Resolve-Path $path -ErrorAction Stop).Path
    
        try
        {
          Remove-Item $path -ErrorAction Stop
        }
        catch [System.IO.IOException]
        {
          If ($_.exception -ilike "*used by another process*")
          {
            Write-host "$path is locked by another process, attempting to setup removal at reboot..."
            $deleteResult = [LockedFileUtils]::DeleteLockedFile($path)
            if ($deleteResult -eq $false)
            {
              throw "Was not able to remove in use file $path `r`n $(New-Object System.ComponentModel.Win32Exception)"
            }
            else
            {
              write-host "(File locked.  Deleting $path at next reboot.  Reboot is required to complete operation.)"
            }
          }
        }
      }
    }
    
    Function Copy-FileEvenIfLocked
    {
      param ([parameter(mandatory=$true,ValueFromPipeline=$true)][string]$Path,
             [parameter(mandatory=$true,ValueFromPipeline=$true)][string]$Destination)
      Process
      {
        $Path = (Resolve-Path $path -ErrorAction Stop).Path
        Write-output "`$path is now $path"
        If (Test-Path $Destination)
        {
          $Destination = (Resolve-Path $Destination -ErrorAction Stop).Path
        }
        Write-output "`$Destination is now $Destination"
    
        try
        {
          Copy-Item $Path $Destination -ErrorAction Stop
          Return "RebootNotRequired"
        }
        catch [System.IO.IOException]
        {
          If ($_.exception -ilike "*used by another process*")
          {
            Write-host "$path is locked by another process, attempting to setup copy at reboot..."
            $copyResult = [LockedFileUtils]::CopyLockedFile($path,$Destination)
            if ($copyResult -eq $false)
            {
              throw "Was not able to copy in use file $path to $destination `r`n $(New-Object System.ComponentModel.Win32Exception)"
            }
            else
            {
              write-host "Destination file is locked.  Copying $path to $Destination at next reboot.  Reboot is required to complete operation.)"
              Return "RebootRequired"
            }
          }
        }
      }
    }
    
  • tools\Get-NetStat.ps1 Show
    function Get-NetStat
    {
    <#
    .SYNOPSIS
    	This function will get the output of netstat -n and parse the output
    .DESCRIPTION
    	This function will get the output of netstat -n and parse the output
    .LINK
    	http://www.lazywinadmin.com/2014/08/powershell-parse-this-netstatexe.html
    .NOTES
    	Francois-Xavier Cat
    	www.lazywinadmin.com
    	@LazyWinAdm
    
      2016/09/20 - Modified by DawinJS to:
      - only grab TCP ports so that parsing PID would be reliable (and is sufficient for my purposes)
      - If -GetProcessDetails
        - parse PID
        - use "get-process" to find exe name (netstat -b is not pulling it for my scenario)
        - finds a full process path name in a Nano TP5 compatible way (WMIC)
      - If -ShowProgress - show progress bar - takes a while to grab all exe paths for all processes
      - If -FilterOnPorts - filter results for these ports before grabbing process details
    
    #>
    Param (
      [switch]$ShowProgress,
      [string[]]$FilterOnPorts,
      [switch]$GetProcessDetails
      )
    	PROCESS
    	{
    		# Get the output of netstat
    		$data = netstat -a -n -o -p TCP | select -skip 4
    
    		# Keep only the line with the data (we remove the first lines)
    		#$data = $data[4..$data.count]
    
    		# Each line need to be splitted and get rid of unnecessary spaces
    		foreach ($line in $data)
    		{
          If ($ShowProgress)
          {
            $ItemBeingProcessed++
            $percentdone = [math]::round(($ItemBeingProcessed/$data.count) * 100)
            Write-Progress -Activity "Probing Listening Ports" -Status "$percentdone% Complete:" -PercentComplete $percentdone
          }
    
          $AddInstance = $True
          # Get rid of the first whitespaces, at the beginning of the line
    			$line = $line -replace '^\s+', ''
    
    			# Split each property on whitespaces block
    			$line = $line -split '\s+'
    
          $PortFromNetStat = (($line[1] -split ":")[1]).trim(' ')
    
          If ($FilterOnPorts)
          {
             If  (!($FilterOnPorts -contains $PortFromNetStat))
             {
               $AddInstance = $False
             }
          }
    
          If ($GetProcessDetails -AND $AddInstance)
          {
            If ($line[4].length -ge 1)
            {
            $ProcessInfo = Get-Process -id $($line[4])
            $ProcessEXEPath = $null
    
            If ([string](wmic process where "ProcessId='$($line[4])'" get ExecutablePath /format:list) -match "[A-Z]:\\.*exe")
            {
              #write-output "match: *$($Matches[0])*"
              $ProcessEXEPath = "$($Matches[0])"
            }
       <#
               If (Test-Path variable:matches) {write-host "got a match"}
    
                If ($getresult.GetType().Name -eq 'Boolean')
                {
                  $ProcessEXEPath = ($Matches[0]).trimend(' ')
                }
                ElseIf ($getresult.GetType().Name -eq 'String')
                {
                  $ProcessEXEPath = $getresult.trimend(' ')
                }
                Else
                {
                  $ProcessEXEPath = ''
                }
                #>
            }
          }
          If ($AddInstance)
          {
    			# Define the properties
      			$properties = @{
    	  			Protocol = $line[0].trim(' ')
    		  		LocalAddressIP = ($line[1] -split ":")[0].trim(' ')
    			  	LocalAddressPort = $PortFromNetStat
              LocalAddressPID = ($line[4]).trim(' ')
              LocalAddressProcessName = $ProcessInfo.Name
              LocalAddressProcessPath = $ProcessEXEPath
    		  		ForeignAddressIP = ($line[2] -split ":")[0].trim(' ')
    			  	ForeignAddressPort = ($line[2] -split ":")[1].trim(' ')
    				  State = $line[3]
    			  }
    
    			  # Output the current line
    			  New-Object -TypeName PSObject -Property $properties
          }
    		}
    	}
    }
    
  • tools\LICENSE.txt Show
    This file is part of the OpenSSH software.
    
    The licences which components of this software fall under are as
    follows.  First, we will summarize and say that all components
    are under a BSD licence, or a licence more free than that.
    
    OpenSSH contains no GPL code.
    
    1)
         * Copyright (c) 1995 Tatu Ylonen <[email protected]>, Espoo, Finland
         *                    All rights reserved
         *
         * As far as I am concerned, the code I have written for this software
         * can be used freely for any purpose.  Any derived versions of this
         * software must be clearly marked as such, and if the derived work is
         * incompatible with the protocol description in the RFC file, it must be
         * called by a name other than "ssh" or "Secure Shell".
    
        [Tatu continues]
         *  However, I am not implying to give any licenses to any patents or
         * copyrights held by third parties, and the software includes parts that
         * are not under my direct control.  As far as I know, all included
         * source code is used in accordance with the relevant license agreements
         * and can be used freely for any purpose (the GNU license being the most
         * restrictive); see below for details.
    
        [However, none of that term is relevant at this point in time.  All of
        these restrictively licenced software components which he talks about
        have been removed from OpenSSH, i.e.,
    
         - RSA is no longer included, found in the OpenSSL library
         - IDEA is no longer included, its use is deprecated
         - DES is now external, in the OpenSSL library
         - GMP is no longer used, and instead we call BN code from OpenSSL
         - Zlib is now external, in a library
         - The make-ssh-known-hosts script is no longer included
         - TSS has been removed
         - MD5 is now external, in the OpenSSL library
         - RC4 support has been replaced with ARC4 support from OpenSSL
         - Blowfish is now external, in the OpenSSL library
    
        [The licence continues]
    
        Note that any information and cryptographic algorithms used in this
        software are publicly available on the Internet and at any major
        bookstore, scientific library, and patent office worldwide.  More
        information can be found e.g. at "http://www.cs.hut.fi/crypto".
    
        The legal status of this program is some combination of all these
        permissions and restrictions.  Use only at your own responsibility.
        You will be responsible for any legal consequences yourself; I am not
        making any claims whether possessing or using this is legal or not in
        your country, and I am not taking any responsibility on your behalf.
    
    
    			    NO WARRANTY
    
        BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
        FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
        OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
        PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
        OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
        MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
        TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
        PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
        REPAIR OR CORRECTION.
    
        IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
        WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
        REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
        INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
        OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
        TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
        YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
        PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
        POSSIBILITY OF SUCH DAMAGES.
    
    2)
        The 32-bit CRC compensation attack detector in deattack.c was
        contributed by CORE SDI S.A. under a BSD-style license.
    
         * Cryptographic attack detector for ssh - source code
         *
         * Copyright (c) 1998 CORE SDI S.A., Buenos Aires, Argentina.
         *
         * All rights reserved. Redistribution and use in source and binary
         * forms, with or without modification, are permitted provided that
         * this copyright notice is retained.
         *
         * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
         * WARRANTIES ARE DISCLAIMED. IN NO EVENT SHALL CORE SDI S.A. BE
         * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY OR
         * CONSEQUENTIAL DAMAGES RESULTING FROM THE USE OR MISUSE OF THIS
         * SOFTWARE.
         *
         * Ariel Futoransky <[email protected]>
         * <http://www.core-sdi.com>
    
    3)
        ssh-keyscan was contributed by David Mazieres under a BSD-style
        license.
    
         * Copyright 1995, 1996 by David Mazieres <[email protected]>.
         *
         * Modification and redistribution in source and binary forms is
         * permitted provided that due credit is given to the author and the
         * OpenBSD project by leaving this copyright notice intact.
    
    4)
        The Rijndael implementation by Vincent Rijmen, Antoon Bosselaers
        and Paulo Barreto is in the public domain and distributed
        with the following license:
    
         * @version 3.0 (December 2000)
         *
         * Optimised ANSI C code for the Rijndael cipher (now AES)
         *
         * @author Vincent Rijmen <[email protected]>
         * @author Antoon Bosselaers <[email protected]>
         * @author Paulo Barreto <[email protected]>
         *
         * This code is hereby placed in the public domain.
         *
         * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
         * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
         * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
         * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
         * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
         * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
         * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
         * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
         * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
         * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
         * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    
    5)
        One component of the ssh source code is under a 3-clause BSD license,
        held by the University of California, since we pulled these parts from
        original Berkeley code.
    
         * Copyright (c) 1983, 1990, 1992, 1993, 1995
         *      The Regents of the University of California.  All rights reserved.
         *
         * Redistribution and use in source and binary forms, with or without
         * modification, are permitted provided that the following conditions
         * are met:
         * 1. Redistributions of source code must retain the above copyright
         *    notice, this list of conditions and the following disclaimer.
         * 2. Redistributions in binary form must reproduce the above copyright
         *    notice, this list of conditions and the following disclaimer in the
         *    documentation and/or other materials provided with the distribution.
         * 3. Neither the name of the University nor the names of its contributors
         *    may be used to endorse or promote products derived from this software
         *    without specific prior written permission.
         *
         * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
         * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
         * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
         * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
         * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
         * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
         * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
         * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
         * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
         * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
         * SUCH DAMAGE.
    
    6)
        Remaining components of the software are provided under a standard
        2-term BSD licence with the following names as copyright holders:
    
    	Markus Friedl
    	Theo de Raadt
    	Niels Provos
    	Dug Song
    	Aaron Campbell
    	Damien Miller
    	Kevin Steves
    	Daniel Kouril
    	Wesley Griffin
    	Per Allansson
    	Nils Nordman
    	Simon Wilkinson
    
        Portable OpenSSH additionally includes code from the following copyright
        holders, also under the 2-term BSD license:
    
    	Ben Lindstrom
    	Tim Rice
    	Andre Lucas
    	Chris Adams
    	Corinna Vinschen
    	Cray Inc.
    	Denis Parker
    	Gert Doering
    	Jakob Schlyter
    	Jason Downs
    	Juha Yrj�l�
    	Michael Stone
    	Networks Associates Technology, Inc.
    	Solar Designer
    	Todd C. Miller
    	Wayne Schroeder
    	William Jones
    	Darren Tucker
    	Sun Microsystems
    	The SCO Group
    	Daniel Walsh
    	Red Hat, Inc
    	Simon Vallet / Genoscope
    
         * Redistribution and use in source and binary forms, with or without
         * modification, are permitted provided that the following conditions
         * are met:
         * 1. Redistributions of source code must retain the above copyright
         *    notice, this list of conditions and the following disclaimer.
         * 2. Redistributions in binary form must reproduce the above copyright
         *    notice, this list of conditions and the following disclaimer in the
         *    documentation and/or other materials provided with the distribution.
         *
         * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
         * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
         * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
         * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
         * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
         * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
         * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
         * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
         * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
         * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    
    8) Portable OpenSSH contains the following additional licenses:
    
        a) md5crypt.c, md5crypt.h
    
    	 * "THE BEER-WARE LICENSE" (Revision 42):
    	 * <[email protected]> wrote this file.  As long as you retain this
    	 * notice you can do whatever you want with this stuff. If we meet
    	 * some day, and you think this stuff is worth it, you can buy me a
    	 * beer in return.   Poul-Henning Kamp
    
        b) snprintf replacement
    
    	* Copyright Patrick Powell 1995
    	* This code is based on code written by Patrick Powell
    	* ([email protected]) It may be used for any purpose as long as this
    	* notice remains intact on all source code distributions
    
        c) Compatibility code (openbsd-compat)
    
           Apart from the previously mentioned licenses, various pieces of code
           in the openbsd-compat/ subdirectory are licensed as follows:
    
           Some code is licensed under a 3-term BSD license, to the following
           copyright holders:
    
    	Todd C. Miller
    	Theo de Raadt
    	Damien Miller
    	Eric P. Allman
    	The Regents of the University of California
    	Constantin S. Svintsoff
    
    	* Redistribution and use in source and binary forms, with or without
    	* modification, are permitted provided that the following conditions
    	* are met:
    	* 1. Redistributions of source code must retain the above copyright
    	*    notice, this list of conditions and the following disclaimer.
    	* 2. Redistributions in binary form must reproduce the above copyright
    	*    notice, this list of conditions and the following disclaimer in the
    	*    documentation and/or other materials provided with the distribution.
    	* 3. Neither the name of the University nor the names of its contributors
    	*    may be used to endorse or promote products derived from this software
    	*    without specific prior written permission.
    	*
    	* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
    	* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    	* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    	* ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
    	* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    	* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
    	* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    	* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    	* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    	* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    	* SUCH DAMAGE.
    
           Some code is licensed under an ISC-style license, to the following
           copyright holders:
    
    	Internet Software Consortium.
    	Todd C. Miller
    	Reyk Floeter
    	Chad Mynhier
    
    	* Permission to use, copy, modify, and distribute this software for any
    	* purpose with or without fee is hereby granted, provided that the above
    	* copyright notice and this permission notice appear in all copies.
    	*
    	* THE SOFTWARE IS PROVIDED "AS IS" AND TODD C. MILLER DISCLAIMS ALL
    	* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
    	* OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL TODD C. MILLER BE LIABLE
    	* FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    	* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
    	* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
    	* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    
           Some code is licensed under a MIT-style license to the following
           copyright holders:
    
    	Free Software Foundation, Inc.
    
    	* Permission is hereby granted, free of charge, to any person obtaining a  *
    	* copy of this software and associated documentation files (the            *
    	* "Software"), to deal in the Software without restriction, including      *
    	* without limitation the rights to use, copy, modify, merge, publish,      *
    	* distribute, distribute with modifications, sublicense, and/or sell       *
    	* copies of the Software, and to permit persons to whom the Software is    *
    	* furnished to do so, subject to the following conditions:                 *
    	*                                                                          *
    	* The above copyright notice and this permission notice shall be included  *
    	* in all copies or substantial portions of the Software.                   *
    	*                                                                          *
    	* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
    	* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
    	* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
    	* IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
    	* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
    	* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
    	* THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
    	*                                                                          *
    	* Except as contained in this notice, the name(s) of the above copyright   *
    	* holders shall not be used in advertising or otherwise to promote the     *
    	* sale, use or other dealings in this Software without prior written       *
    	* authorization.                                                           *
    	****************************************************************************/
    
    
    ------
    $OpenBSD: LICENCE,v 1.19 2004/08/30 09:18:08 markus Exp $
  • tools\ntrights.exe Show
    md5: 416C43AEB17252EE33048BD1F277D2A5 | sha1: 085DEB77551F9F6201E5AA352B62CAD91C3005E5 | sha256: F46BAA1B6227226518E42263E9B4808F81C27D060207DF160F9AC64DEAE4F4F5 | sha512: 3155DE3FB04F1DF246D6CECFA1C89F8AE9963C18BE1CE717731FF210AB39D537BE01231002A54D4346B4116E3505F387C92DFECC18A80CE7EB99C6D33E5F1F2A
  • tools\ntrights.exe.ignore
  • tools\OpenSSH-Win32.zip Show
    md5: 5CF7AE1F66D73FB48EEB1E68D8517C93 | sha1: 40C0198122F4B0F8BDDF5345D3C5340132647D23 | sha256: DD4529B3509F5254A93D90A40BF6DE080FD899447183F89E49477FCADC31E42C | sha512: C0C8EA0D50D986B5B1EBC72CAB075F09254592A405D5F5C88120677E99D90A71F0720AB8F4AD1A6F2B3342E591091B99C0E9D8F830F5D0C9D8E79FDA5578F480
  • tools\OpenSSH-Win64.zip Show
    md5: 7DE4D48D7AA4789CBD41F123D18920CD | sha1: A181D320159DDA8188BEE172F6AADECDFB9FCC1D | sha256: B25648E6765E979929A9888B482F736776014DAD252D4DEE43F990683D70F9E3 | sha512: 8D4BAB5FD36926117E5B33963D068FCF1D8EDE93266928A685438557BAAFDE24B9745FE3DBA2726C21139CF9AB57E5DB9C841E45BBF65EF5D1CC15C511432B6E
  • tools\Set-SSHDefaultShell.ps1 Show
    <#
    .SYNOPSIS
        This script sets the default shell options for openssh.  It is run during the opensssh universal installer and can be called separately to update the default shell exe after releated update (e.g. like updating PowerShell Core)
    .DESCRIPTION
        This script is used during OpenSSH install if the appropriate package options were specified.
    
        It can also be used seperately (such as calling it after installing a new version of PowerShell Core 
        or updating another shell that should be the default for openssh)
    
        #It never really makes sense to search for cmd.exe as that is the default behavior and you shouldn't try to put old versions of cmd.exe on a newer version of windows 
        (I guess the exception would be configuring ssh to use 32-bit cmd.exe under 64-bit sshd.exe system - no I don't know why you would do that - but Murphy predicts someone out there will need to - hopefully not you)
    
        #"Windows Powershell" should always be at the end of a multi-filespec request because it will always be found
    
        #Environment variables are preferred for paths so that your call applies to windows not being on C: and folder redirection scenarios
    
        #If the list of path specs does not result in one or more valid results, then the default behavior (no registry keys) is used (graceful fall through)
    
        # ATTENTION - if you run this package under a 32-bit process on 64-bit Windows (e.g. SCCM "Package" objects), it will result in setting up 32-bit system exes as the shell for 64-bit sshd.exe
    
    
        Rules (For the sake of sanity, don't read these rules if you just want to do something simple like set Windows PowerShell to be your default ssh shell - use the examples)
        - the combined results will be in order that the filespecs are provided so that precedence can be specified for specific shell EXE filenames
        - the exes in each filespec can be the same (when searching multiple folder heirarchies for the same shell exe) or different (when giving preference to one shell EXE, but providing a fall through default if none are found)
        - wildcards can only be used in the pathname, not the filename  (filename wild cards will cause the filespec to be filtered out of the list)
        - each filespec must be searching for a SPECIFIC exe file (cannot search for <something>\*.exe nor <something>\* nor anything not ending in .exe) (any that don't match are filtered out of the filespec list)
        - each filespec result set is sorted by descending version number before being concatenated to the combined result list so that the newest of that shell exe will be chosen 
        - because early powershell core exe do not include versions in the PE header, they are sorted by full folder name which includes the version
        - the file list will only contain actually found EXEs
        - the file list is screened for known secure folders that require admin rights to update on windows configured with default security (the rest are filtered out)
        - the first valid hit in the overall resultant file list will be used.
        - if you do not want version autoselection, then specify the path exact location to the exact version you wish to have considered
    
    .LINK
    	http://www.lazywinadmin.com/2014/08/powershell-parse-this-netstatexe.html
    
    .EXAMPLE
    #All of these filespecs will be filtered out (dropped) because you can't wildcard the exe name, for securities sake you must know what the shell is called to use it:
    -PathSpecsToProbeForShellEXEString "$env:userprofile\downloads\*.exe;c:\Program Files\PowerShell\*\P*.exe;c:\windows\system32\*"
    
    .EXAMPLE
    #PowerShell for Windows instead of default cmd.exe, if not found, default behavior (no registry key created, cmd.exe is ssh default):
    -PathSpecsToProbeForShellEXEString '$env:windir\system32\windowspowershell\v1.0\powershell.exe"
    
    .EXAMPLE
    #The latest version of powershell core (including favoring the new EXE name), if not found, use windows powershell
    -PathSpecsToProbeForShellEXEString "$env:programfiles\PowerShell\*\pwsh.exe;$env:programfiles\PowerShell\*\Powershell.exe;c:\windows\system32\windowspowershell\v1.0\powershell.exe"
    
    .EXAMPLE
    #The latest version of Ruby, if not found, powershell core if not found, default behavior (no registry key created, cmd.exe is ssh default)
    -PathSpecsToProbeForShellEXEString "c:\tools\ruby*\bin\ruby.exe;c:\Program Files\PowerShell\*\pwsh.exe;c:\Program Files\PowerShell\*\Powershell.exe"
    
    #I have no idea if ruby can actually be an SSH shell - just an example
    
    .EXAMPLE
    #Windows Subsystem for Linux Bash.exe, if not found, the latest version of git's bash.exe, if not found, default behavior (no registry key created, cmd.exe is ssh default)
    -PathSpecsToProbeForShellEXEString "$env:windir\system32\bash.exe;$env:programfiles\Git\usr\bin\bash.exe"
    
    #I have no idea if git's bash can actually be an SSH shell - just an example
    
    .EXAMPLE
    #Specific version of powershell core, if not found, windows powershell
    -PathSpecsToProbeForShellEXEString "c:\Program Files\PowerShell\6.0.0-beta.6\Powershell.exe;c:\windows\system32\windowspowershell\v1.0\powershell.exe"
    
    .EXAMPLE
    #malware.exe filtered out because it is not in a secure folder, Specific version of powershell core, if not found, windows powershell
    -PathSpecsToProbeForShellEXEString "$env:userprofile\downloads\malware.exe;c:\Program Files\PowerShell\6.0.0-beta.6\Powershell.exe;c:\windows\system32\windowspowershell\v1.0\powershell.exe"
    
    .EXAMPLE
    #malware.exe is used because of -AllowInsecureShellEXE
    -AllowInsecureShellEXE -PathSpecsToProbeForShellEXEString "$env:userprofile\downloads\malware.exe;c:\Program Files\PowerShell\6.0.0-beta.6\Powershell.exe;c:\windows\system32\windowspowershell\v1.0\powershell.exe"
    
    .NOTES
    	Darwin Sanoy
    	cloudywindows.io
     
    #>
    Param (
      [Parameter(Mandatory=$True)]
      [string]$PathSpecsToProbeForShellEXEString,
      [string]$SSHDefaultShellCommandOption=$null,
      [switch]$AllowInsecureShellEXE
      )
    
      $OpeningMessage = @"
      
      ************************************************************************************    
      This utility script:
      
        $($MyInvocation.MyCommand.Definition)
    
      can be run outside of this package in order to update the OpenSSH DefaultShell when 
      an installer runs to update the default shell.
      
      See the following for more details:
      https://github.com/DarwinJS/ChocoPackages/blob/master/openssh/readme.md
      https://cloudwindows.io
      ************************************************************************************
      
    "@
      
      Write-Output $OpeningMessage
    
    If ($AllowInsecureShellEXE)
    {
    Write-Warning "AllowInsecureShellEXE was used, if probing results in selecting a shell exe that is user writable, it will still be used.  Not wise!!"
    }
    
    <#
    TEST string
    #$PathSpecsToProbeForShellEXEString = '$env:userprofile\downloads\*.exe;$env:programfiles\powershell\*\powershell.exe;$env:windir\system32\cmd.exe;c:\windows'
    #>
    
    #Expand any literalized variable or environment variable references, also only resolves to items that exist
    Write-Host "Set-SSHDefaultShell.ps1 processing request for `"$PathSpecsToProbeForShellEXEString`""
    $ShellEXEToUse = $null
    $PathSpecsToProbeForShellEXE = $ExecutionContext.InvokeCommand.ExpandString($PathSpecsToProbeForShellEXEString).split(';') 
    #write-host "`$PathSpecsToProbeForShellEXE: $PathSpecsToProbeForShellEXE"
    $ListOfSecurePaths = "$env:programfiles","${env:ProgramFiles(x86)}","$env:windir\system32","$env:windir\syswow64"
    $ListOfSecurePathsRegExPrep = $ListOfSecurePaths | ForEach {[Regex]::Escape($ExecutionContext.InvokeCommand.ExpandString($_)) + ".*`|"}
    $ListOfSecurePathsRegExString = ($ListOfSecurePathsRegExPrep -join '').trimend("|")
    #write-host "`$ListOfSecurePathsRegExString: $ListOfSecurePathsRegExString"
    If ($PathSpecsToProbeForShellEXE.count -ge 1)
    {
    #Special Handling of "C:\Program Files\PowerShell" for versioned subfolders and EXEs with no PE header version
    $ListOfEXEObjects = @()
    [array]$SubListofEXEObjects 
    ForEach ($PathSpec in $PathSpecsToProbeForShellEXE)
    { write-host "processing $pathspec"
      $SubListOfEXEPaths = @(Resolve-Path $PathSpec -ErrorAction SilentlyContinue)
      write-host "`$SubListOfEXEPaths: $SubListOfEXEPaths"
      $SubListOfEXEPaths = @($SubListOfEXEPaths | where {[IO.Path]::GetExtension($_) -ieq '.exe'})
      If ($SubListOfEXEPaths.count -gt 0)
      {
        $SubListofEXEObjects = @(get-command $SubListOfEXEPaths)
      
        If ($PathSpec -ilike "$env:ProgramFiles\PowerShell\*")
        { #apply a sort to full file names
          $SubListOfEXEObjects = $SubListOfEXEObjects | sort-object -Property 'Definition' -Descending
        }
        else 
        {
          $SubListOfEXEObjects = $SubListOfEXEObjects | sort-object -Property FileVersionInfo.ProductVersion -Descending
        }
        $ListOfEXEObjects += $SubListOfEXEObjects
      }
    }
    
    If ($ListOfEXEObjects.count -lt 1)
    {
      Write-warning "On this system, searching $PathSpecsToProbeForShellEXEString does not result in any paths that end in .EXE, DefaultShell will not be explicitly set and ssh will use its default shell behavior or the existing registry key value."
    }
    else 
    {    
      $ListOfValidEXEObjects = @()
      If (!$AllowInsecureShellEXE)
      {
        Write-Host "Filtering out EXEs that are not on the secure path list: $ListOfSecurePaths.  To unwisely override this filtering use the AllowInsecureShellEXE switch."
        ForEach ($EXEObject in $ListOfEXEObjects)
        { #Validate EXEs are on Secure Paths
          If ($EXEObject.Definition -imatch "$ListOfSecurePathsRegExString")
          {
            Write-Host "     Valid: $($EXEObject.Definition)"
            $ListOfValidEXEObjects += $EXEObject
          }
          else 
          {
            Write-Warning "  Dropping: $($EXEObject.Definition)"
          }
        }
        $ListOfEXEObjects = $ListOfValidEXEObjects
      }
    
      If ($ListOfEXEObjects.count -ge 1)
      {
        $ShellEXEToUse = $ListOfEXEObjects | Select-Object -First 1 -Expand Definition
        Write-host "Shell to use: $ShellEXEToUse"
        If ($ShellEXEToUse)
        {
          Write-Host "Writing default shell to registry ($ShellEXEToUse)"
          $SSHRegKey = "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\OpenSSH"
          New-ItemProperty -Path $SSHRegKey -Name 'DefaultShell' -Value "$ShellEXEToUse" -PropertyType 'String' -Force | Out-Null
          If ($SSHDefaultShellCommandOption)
          {
            Write-Host "Writing default shell command option to registry ($SSHDefaultShellCommandOption)"    
            New-ItemProperty -Path $SSHRegKey -Name 'DefaultShellCommandOption' -Value "$SSHDefaultShellCommandOption" -PropertyType 'String' -Force  | Out-Null
          }
          else 
          {  #Revert to default behavior if not specified
            Remove-ItemProperty -Path $SSHRegKey -Name 'DefaultShellCommandOption' -ErrorAction 'SilentlyContinue'
          }
        }      
      }
      else {
        Write-Warning "After all filtering criteria was applied, there is no matching EXE for your search string: $PathSpecsToProbeForShellEXEString"
      }
    }
    }
    
  • tools\SetSpecialPrivileges.ps1 Show
    #Idea borrowed from https://gallery.technet.microsoft.com/scriptcenter/Grant-Revoke-Query-user-26e259b0
    $definition = @'
    using System;
    namespace MyLsaWrapper
    {
        using System.Runtime.InteropServices;
        using System.Security;    
        using System.ComponentModel;    
        using System.Security.Principal;
        using LSA_HANDLE = IntPtr;
        [StructLayout(LayoutKind.Sequential)]
        struct LSA_OBJECT_ATTRIBUTES
        {
            internal int Length;
            internal IntPtr RootDirectory;
            internal IntPtr ObjectName;
            internal int Attributes;
            internal IntPtr SecurityDescriptor;
            internal IntPtr SecurityQualityOfService;
        }
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        struct LSA_UNICODE_STRING
        {
            internal ushort Length;
            internal ushort MaximumLength;
            [MarshalAs(UnmanagedType.LPWStr)]
            internal string Buffer;
        }
        sealed class Win32Sec
        {
            [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true)]
            internal static extern uint LsaOpenPolicy(
            LSA_UNICODE_STRING[] SystemName,
            ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
            int AccessMask,
            out IntPtr PolicyHandle
            );
            [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true)]
            internal static extern uint LsaAddAccountRights(
                LSA_HANDLE PolicyHandle,
                IntPtr pSID,
                LSA_UNICODE_STRING[] UserRights,
                int CountOfRights
            );
            [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true)]
            internal static extern uint LsaRemoveAccountRights(
                LSA_HANDLE PolicyHandle,
                IntPtr pSID,
                bool AllRights,
                LSA_UNICODE_STRING[] UserRights,
                int CountOfRights
            );
            [DllImport("advapi32")]
            internal static extern int LsaNtStatusToWinError(int NTSTATUS);
            [DllImport("advapi32")]
            internal static extern int LsaClose(IntPtr PolicyHandle);
        }
        internal sealed class Sid : IDisposable
        {
            public IntPtr pSid = IntPtr.Zero;
            public System.Security.Principal.SecurityIdentifier sid = null;
            public Sid(string account)
            {
                try { sid = new SecurityIdentifier(account); }
                catch { sid = (SecurityIdentifier)(new NTAccount(account)).Translate(typeof(SecurityIdentifier)); }
                Byte[] buffer = new Byte[sid.BinaryLength];
                sid.GetBinaryForm(buffer, 0);
                pSid = Marshal.AllocHGlobal(sid.BinaryLength);
                Marshal.Copy(buffer, 0, pSid, sid.BinaryLength);
            }
            public void Dispose()
            {
                if (pSid != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pSid);
                    pSid = IntPtr.Zero;
                }
                GC.SuppressFinalize(this);
            }
            ~Sid() { Dispose(); }
        }
        public sealed class LsaWrapper : IDisposable
        {
            enum Access : int
            {
                POLICY_READ = 0x20006,
                POLICY_ALL_ACCESS = 0x00F0FFF,
                POLICY_EXECUTE = 0X20801,
                POLICY_WRITE = 0X207F8
            }
            const uint STATUS_ACCESS_DENIED = 0xc0000022;
            const uint STATUS_INSUFFICIENT_RESOURCES = 0xc000009a;
            const uint STATUS_NO_MEMORY = 0xc0000017;
            const uint STATUS_OBJECT_NAME_NOT_FOUND = 0xc0000034;
            const uint STATUS_NO_MORE_ENTRIES = 0x8000001a;
            IntPtr lsaHandle;
            public LsaWrapper() : this(null) { } // local system if systemName is null
            public LsaWrapper(string systemName)
            {
                LSA_OBJECT_ATTRIBUTES lsaAttr;
                lsaAttr.RootDirectory = IntPtr.Zero;
                lsaAttr.ObjectName = IntPtr.Zero;
                lsaAttr.Attributes = 0;
                lsaAttr.SecurityDescriptor = IntPtr.Zero;
                lsaAttr.SecurityQualityOfService = IntPtr.Zero;
                lsaAttr.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));
                lsaHandle = IntPtr.Zero;
                LSA_UNICODE_STRING[] system = null;
                if (systemName != null)
                {
                    system = new LSA_UNICODE_STRING[1];
                    system[0] = InitLsaString(systemName);
                }
                uint ret = Win32Sec.LsaOpenPolicy(system, ref lsaAttr, (int)Access.POLICY_ALL_ACCESS, out lsaHandle);
                if (ret == 0) return;
                if (ret == STATUS_ACCESS_DENIED) throw new UnauthorizedAccessException();
                if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY)) throw new OutOfMemoryException();
                throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
            }
            public void AddPrivilege(string account, string privilege)
            {
                uint ret = 0;
                using (Sid sid = new Sid(account))
                {
                    LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1];
                    privileges[0] = InitLsaString(privilege);
                    ret = Win32Sec.LsaAddAccountRights(lsaHandle, sid.pSid, privileges, 1);
                }
                if (ret == 0) return;
                if (ret == STATUS_ACCESS_DENIED) throw new UnauthorizedAccessException();
                if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY)) throw new OutOfMemoryException();
                throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
            }
            public void RemovePrivilege(string account, string privilege)
            {
                uint ret = 0;
                using (Sid sid = new Sid(account))
                {
                    LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1];
                    privileges[0] = InitLsaString(privilege);
                    ret = Win32Sec.LsaRemoveAccountRights(lsaHandle, sid.pSid, false, privileges, 1);
                }
                if (ret == 0) return;
                if (ret == STATUS_ACCESS_DENIED) throw new UnauthorizedAccessException();
                if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY)) throw new OutOfMemoryException();
                throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
            }
            public void Dispose()
            {
                if (lsaHandle != IntPtr.Zero)
                {
                    Win32Sec.LsaClose(lsaHandle);
                    lsaHandle = IntPtr.Zero;
                }
                GC.SuppressFinalize(this);
            }
            ~LsaWrapper() { Dispose(); }
            // helper functions:
            static LSA_UNICODE_STRING InitLsaString(string s)
            {
                // Unicode strings max. 32KB
                if (s.Length > 0x7ffe) throw new ArgumentException("String too long");
                LSA_UNICODE_STRING lus = new LSA_UNICODE_STRING();
                lus.Buffer = s;
                lus.Length = (ushort)(s.Length * sizeof(char));
                lus.MaximumLength = (ushort)(lus.Length + sizeof(char));
                return lus;
            }
        }
        public class LsaWrapperCaller
        {
            public static void AddPrivilege(string account, string privilege)
            {
                using (LsaWrapper lsaWrapper = new LsaWrapper())
                {
                    lsaWrapper.AddPrivilege(account, privilege);
                }
            }
            public static void RemovePrivilege(string account, string privilege)
            {
                using (LsaWrapper lsaWrapper = new LsaWrapper())
                {
                    lsaWrapper.RemovePrivilege(account, privilege);
                }
            }
        }
    }
    '@
    
    $references = @("System.Security.Principal.Windows", "Microsoft.Win32.Primitives")
    try {
        $null = [MyLsaWrapper.LsaWrapperCaller]
    }
    catch {
        try {
            $types = Add-Type $definition -ref $references -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
        }
        catch {	
    	    $types = Add-Type $definition -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
        }
    }
    
    function Add-OpenSSHPrivilege
    {
        param(
        [ValidateNotNullOrEmpty()]
        [string] $Account,
        
        [ValidateSet("SeAssignPrimaryTokenPrivilege", "SeServiceLogonRight")]
        [string] $Privilege
        )
    
        [MyLsaWrapper.LsaWrapperCaller]::AddPrivilege($Account, $Privilege)    
    }
    
    function Get-OpenSSHUserSID
    {       
        [CmdletBinding(DefaultParameterSetName='User')]
        param
            (   [parameter(Mandatory=$true, ParameterSetName="User")]
                [ValidateNotNull()]
                [System.Security.Principal.NTAccount]$User,
                [parameter(Mandatory=$true, ParameterSetName="WellKnownSidType")]
                [ValidateNotNull()]
                [System.Security.Principal.WellKnownSidType]$WellKnownSidType
            )
        try
        {   
            if($PSBoundParameters.ContainsKey("User"))
            {
                $sid = $User.Translate([System.Security.Principal.SecurityIdentifier])
            }
            elseif($PSBoundParameters.ContainsKey("WellKnownSidType"))
            {
                $sid = New-Object System.Security.Principal.SecurityIdentifier($WellKnownSidType, $null)
            }
            $sid        
        }
        catch {
            return $null
        }
    }
  • tools\VERIFICATION.txt Show
    VERIFICATION.txt is intended to assist the Chocolatey moderators and community
    in verifying that this package's contents are trustworthy.
    
    To verify:
    
    1. Download https://github.com/PowerShell/Win32-OpenSSH/releases/download/5_30_2016/OpenSSH-Win64.zip
    2. Compare OpenSSH-Win64.zip hash with bundled OpenSSH-Win64.zip hash.
    3. Download https://github.com/PowerShell/Win32-OpenSSH/releases/download/5_30_2016/OpenSSH-Win32.zip
    4. Compare OpenSSH-Win64.zip hash with bundled OpenSSH-Win32.zip hash.
    

Virus Scan Results

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.

Dependencies

This package has no dependencies.

Maintainer(s)

Software Author(s)

  • Microsoft

Copyright

Microsoft

Tags

Release Notes

Product release notes: https://github.com/PowerShell/Win32-OpenSSH/releases/tag/v0.0.24.0

Release Notes for Chocolatey Packaging:
0.0.24.0
- Fixed bug in uninstall (https://github.com/DarwinJS/ChocoPackages/issues/52)
- Uses new code from OpenSSH project for adding special privileges (is more compatible with newer Nano releases)
0.0.23.0
- None
0.0.22.0
- Fix error when uninstall runs and openssh folder is already removed: https://github.com/DarwinJS/ChocoPackages/issues/49
- Fix error using PSH 5 Package Management to install on Server 2016: https://github.com/DarwinJS/ChocoPackages/issues/47
- Added switches for Default Shell configuration - for both chocolatey and barebonesinstall.ps1
(PathSpecsToProbeForShellEXEString, SSHDefaultShellCommandOption and AllowInsecureShellEXE)
Make the latest powershell core or windows powershell the default shell:
/PathSpecsToProbeForShellEXEString:$env:programfiles\PowerShell*\pwsh.exe;$env:programfiles\PowerShell*\Powershell.exe;c:\windows\system32\windowspowershell\v1.0\powershell.exe"
-PathSpecsToProbeForShellEXEString "$env:programfiles\PowerShell*\pwsh.exe;$env:programfiles\PowerShell*\Powershell.exe;c:\windows\system32\windowspowershell\v1.0\powershell.exe"
Rules and More Examples: https://github.com/DarwinJS/ChocoPackages/blob/master/openssh/tools/Set-SSHDefaultShell.ps1

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 '"/SSHAgentFeature"'
Installs SSH Agent Service even if SSHD Server is not being installed.
Requires admin rights to configure service.
This option is automatically set when /SSHServerFeature is used.

-params '"/SSHServerFeature /SSHServerPort:3834"'
Allows the setup of the SSH server on an alternate port - sometimes done for security or to avoid conflicts with an existing service on port 22.

-params '"/OverWriteSSHDConf"'
Introduced in Version: 0.0.9.20170311
By default an existing sshdconf file will not be overwritten (previous packaging versions always overwrote)
Use this switch to overwrite an existing sshd
conf with the one from the current install media

-params '"/SSHLogLevel:VERBOSE"'
Introduced in Version: 0.0.9.20170311
Allows the setup of the SSH logging level.
Valid Options: QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, DEBUG3
On a fresh install LogLevel is set to QUIET

-params '"/TERM:xterm-new"'
Introduced in Version: 0.0.14.0
Allows the initial setup and subsequent update of the TERM system environment variable.
On a fresh install TERM is set to xterm whether or not this switch is used.

-params '"/DisableKeyPermissionsReset"'
Introduced in Version: 0.0.15.0
As of 0.0.13.0 new key permissions are required for ssh keys. By default this installer
reasserts these permissions whenever run. Used this switch if you do not want the installation
to attempt to manage key permissions. The utility script will still be installed and available
if you need to use it later to fix up permissions.

-params '"/SSHServerFeature /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 '"/SSHServerFeature /DeleteConfigAndServerKeys"' (Uninstall)
By default an uninstall does not remove config files nor server keys.

-params '"/UseNTRights"'
By default the install uses PowerShell code that works on operating systems that cannot run the 32-bit ntrights.exe (Nano, Server Core w/out WOW64).
If this code does not work for you, you can use this switch to invoke the 32-bit ntrights.exe

-params '"/PathSpecsToProbeForShellEXEString:$env:programfiles\PowerShell*\Powershell.exe;$env:windir\system32\windowspowershell\v1.0\powershell.exe"'
Introduced in Version: 0.0.22.0
A set of filespecs to probe for the latest version of a given shell exe. Wildcards can be used in the path, but not the filename.
The first filespec to result in a one or more valid hits will be choosen for the default SSH shell (newest version when there are multiple hits).
If not valid hits are located with the entire set of filespecs, the default behavior of not setting the registry key is taken (rather than an error).
Only exe's in either Program Files folder or either System32 folder (system32, syswow64) will considered safe. If the EXE is outside of these folders
you must use the /AllowInsecureShellEXE switch to have it configured.
Rules and Examples: https://github.com/DarwinJS/ChocoPackages/blob/master/openssh/tools/Set-SSHDefaultShell.ps1

-params '"/SSHDefaultShellCommandOption:/c"'
Introduced in Version: 0.0.22.0
Only used when /PathSpecsToProbeForShellEXEString is used and results in finding a valid shell executable.
Rules and Examples: https://github.com/DarwinJS/ChocoPackages/blob/master/openssh/tools/Set-SSHDefaultShell.ps1

-params '"/AllowInsecureShellEXE"'
Introduced in Version: 0.0.22.0
Only used when /PathSpecsToProbeForShellEXEString is used and results in finding a valid shell executable that is outside of the Programs Folders or system32.
Rules and Examples: https://github.com/DarwinJS/ChocoPackages/blob/master/openssh/tools/Set-SSHDefaultShell.ps1

0.0.21.0
- none
0.0.20.20170913
- added possible missing command from install-sshd.ps1 (sc.exe privs sshd SeAssignPrimaryTokenPrivilege)
0.0.20.0
- handle edge case error for Azure Custom Script Extensions and DSC cChocoInstalledPackage resource
where GetTempFileName does not find TEMP folder when running under SYSTEM account.
0.0.19.0
- sshlsa features are removed from install package as this dll is no longer required for Openssh
0.0.18.20170730
- TERM defaults to 'xterm-256color' on windows kernel 10.x and above
0.0.18.0
- updated instructions for non-chocolatey install so that they do not add the source location as "trusted"
0.0.17.0
- fixes latest opensshutils.psm1 to work on Nano
0.0.16.0
- Fixed incomplete permissions grant when using /NTRights switch.
- Fixed uninstall implementation
- Fixed uninstall and clean uninstall for Nano
- Uses version of opensshutils shipped with openssh
0.0.15.20170613
- Fixed problem for issue #35 (error with "$RunningOnNano not found").
- /DeleteConfigAndServerKeys now works.
0.0.15.20170611
- Sets permissions for user "NT SERVICE\sshd" to write to [sshfolder]\Logs
0.0.15.0
- Calls utility script FixUserFilePermissions.ps1 (included with OpenSSH) to align setup / migrate
permissions to v.0.0.15.0 standard. Permissions are reasserted at every install / upgrade.
- A chocolatey uninstall that specifies "/DeleteConfigAndServerKeys" will fail. This is only ever used
for a completely clean uninstall - not using it means that the ssh_conf and the server key files will
remain in the openssh install folder and will need to be removed manually after taking ownership of the files.
- New switch /DisableKeyPermissionsReset disables this capability if you are managing permissions separately.
0.0.14.0
- by default sets a machine environment variable TERM=xterm, customize with /TERM switch
- updated path setting code to not make unnecessary path alterations
0.0.12.0
- ssh-lsa.dll is no longer needed and no longer configured (switch /ReleaseSSHLSAForUpgrade is ignored)
- if ssh-lsa.dll is found during upgrade a delete attempt is made - if unsuccessful (file locked), ssh-lsa.dll
will be deconfigured as an authentication package and it will be delete on the next upgrade.

Version History

Version Downloads Last updated Status
Win32 OpenSSH (Universal Installer) 0.0.23.0 44113 Monday, November 20, 2017 approved
Win32 OpenSSH (Universal Installer) 0.0.22.0 61583 Sunday, October 29, 2017 approved
Win32 OpenSSH (Universal Installer) 0.0.21.0 72846 Tuesday, October 3, 2017 approved
Win32 OpenSSH (Universal Installer) 0.0.20.20170913 61962 Thursday, September 14, 2017 approved
Win32 OpenSSH (Universal Installer) 0.0.20.0 9711 Monday, September 11, 2017 approved
Win32 OpenSSH (Universal Installer) 0.0.19.0 37804 Friday, August 25, 2017 approved
Win32 OpenSSH (Universal Installer) 0.0.18.0 50287 Thursday, July 20, 2017 approved
Show More

Discussion for the Win32 OpenSSH (Universal Installer) Package

Ground rules:

  • This discussion is only about Win32 OpenSSH (Universal Installer) and the Win32 OpenSSH (Universal Installer) 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 (Universal Installer), 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