Unpacking Software Livestream

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

Learn More

Chocolatey Product Spotlight

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

Learn More

Chocolatey Coding Livestream

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

Learn More

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

Webinar from
Wednesday, 17 January 2024

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

Watch On-Demand
Chocolatey Community Coffee Break

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

Watch The Replays
Chocolatey and Intune Overview

Webinar Replay from
Wednesday, 30 March 2022

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

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

Livestream from
Thursday, 9 June 2022

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

Watch On-Demand
The Future of Chocolatey CLI

Livestream from
Thursday, 04 August 2022

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

Watch On-Demand
Hacktoberfest Tuesdays 2022

Livestreams from
October 2022

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

Watch On-Demand

Downloads:

212,069

Downloads of v 2016.05.30:

12,474

Last Update:

04 Jun 2016

Package Maintainer(s):

Software Author(s):

  • Microsoft

Tags:

win32-openssh admin

Win32 OpenSSH (Microsoft Port)

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

  • 1
  • 2
  • 3

2016.05.30 | Updated: 04 Jun 2016

Downloads:

212,069

Downloads of v 2016.05.30:

12,474

Maintainer(s):

Software Author(s):

  • Microsoft

Win32 OpenSSH (Microsoft Port) 2016.05.30

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

  • 1
  • 2
  • 3

Some Checks Have Failed or Are Not Yet Complete

Not All Tests Have Passed


Validation Testing Passed


Verification Testing Passed

Details

Scan Testing Resulted in Flagged:

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

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

Details
Learn More

Deployment Method: Individual Install, Upgrade, & Uninstall

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

>

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

>

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

>

Deployment Method:

NOTE

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

1. Enter Your Internal Repository Url

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


2. Setup Your Environment

1. Ensure you are set for organizational deployment

Please see the organizational deployment guide

2. Get the package into your environment

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

3. Copy Your Script

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

See options you can pass to upgrade.

See best practices for scripting.

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

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


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

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

Exit $exitCode

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

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


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

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


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

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


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

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


4. If applicable - Chocolatey configuration/installation

See infrastructure management matrix for Chocolatey configuration elements and examples.

NOTE

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

Package Approved

This package was approved by moderator dtgm on 04 Jun 2016.

Description

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

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

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

This package supports the following parameters:

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

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

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

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


tools\chocolateyinstall.ps1

$ErrorActionPreference = 'Stop'; # stop on all errors
$toolsDir   = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$OSBits = Get-ProcessorBits

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

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

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

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

# Default the values before reading params
$SSHServerFeature = $false
$KeyBasedAuthenticationFeature = $false
$DeleteServerKeysAfterInstalled = $false

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

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

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

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

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

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

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

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

If ($SSHServerFeature -AND (!$SSHServiceInstanceExistsAndIsOurs) -AND ([bool](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 installed, but this system appears to have an instance of an SSHD service configured for another folder ($ExistingSSHDInstancePath).  You can remove the package switch /SSHServerFeature to install just the client tools, or you will need to remove that instance of SSHD to use the one that comes with this package."
}

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

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

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

}

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

#Placing these security sensitive exe files in a location secure from viruses
# (and as per project install instructions)
Install-ChocolateyZipPackage @packageArgs

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

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

Install-ChocolateyPath "$TargetFolder" 'Machine'

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

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

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

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

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

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

  Start-Service ssh-agent

  Start-Sleep -seconds 3

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

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

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

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

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

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

  If ($psversiontable.psversion -lt [version]'3.0')
  {
    write-output "PowerShell version is older than 3.0, using  ntrights.exe to grant logon as service."
    Start-Process "$TargetFolder\ntrights.exe" -ArgumentList "-u `"NT SERVICE\SSHD`" +r SeServiceLogonRight"
  }
  Else
  {
    Import-Module "$toolsdir\PoshPrivilege"
    Add-Privilege "NT SERVICE\SSHD" SeServiceLogonRight
  }

  <#."$toolsdir\ntrights.ps1"
  [MyLsaWrapper.LsaWrapperCaller]::AddPrivileges("NT SERVICE\SSHD", "SeServiceLogonRight")
  #cmd.exe /c "`"$TargetFolder\ntrights.exe`" -u `"NT SERVICE\SSHD`" +r SeAssignPrimaryTokenPrivilege"
  #>
  If (!$SSHLsaVersionChanged)
  {
    Write-Output "Starting sshd Service"
    Start-Service sshd
  }
  Else
  {
    Write-Warning "You must reboot so that key based authentication can be fully installed for the SSHD Service."
  }
}

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

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

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

$OSBits = Get-ProcessorBits

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

$filename = "$toolsdir\OpenSSH-Win$($OSBits).zip"
$TargetFolder = "$PF\OpenSSH-Win$($OSBits)"

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

#Don't remove config in case they reinstall.
If ($DeleteConfigAndServerKeys)
{
    Write-Warning "Removing all config and server keys as requested by /DeleteConfigAndServerKeys"
    Remove-Item "$TargetFolder\*" -Recurse -Force
}
Else
{
  Remove-Item "$TargetFolder\*.*" -include *.exe,*.dll,*.cmd -Recurse -Force
  Write-Warning "NOT REMOVED: Config files and any keys in `"$TargetFolder`" were NOT REMOVED - you must remove them manually or use the package uninstall parameter /DeleteConfigAndServerKeys."
}
netsh advfirewall firewall delete rule name='SSHD Port win32-openssh'

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

[Environment]::SetEnvironmentVariable("PATH",$AssembledNewPath,"Machine")
tools\ntrights.exe
md5: 416C43AEB17252EE33048BD1F277D2A5 | sha1: 085DEB77551F9F6201E5AA352B62CAD91C3005E5 | sha256: F46BAA1B6227226518E42263E9B4808F81C27D060207DF160F9AC64DEAE4F4F5 | sha512: 3155DE3FB04F1DF246D6CECFA1C89F8AE9963C18BE1CE717731FF210AB39D537BE01231002A54D4346B4116E3505F387C92DFECC18A80CE7EB99C6D33E5F1F2A
tools\ntrights.exe.ignore
 
tools\PoshPrivilege\en-US\about_PoShPrivilege.help.txt
TOPIC
    about_PoshPrivilege

SHORT DESCRIPTION

    PoshPrivilege provides a simple way to add/remove privileges to an account/group on a 
    local machine as well as enabling or disabling existing privileges which are applied 
    to a current user's process token. 

LONG DESCRIPTION

    PoshPrivilege provides a simple way to add/remove privileges to an account/group on a 
    local machine as well as enabling or disabling existing privileges which are applied 
    to a current user's process token. 

    You can also view the privileges which have been applied to users/groups via policy
    or find out what the current user's available privileges are.

    Enable/Disable Privileges
    =========================
    You can only enable or disable privileges where they are currently available on the current
    process. This means that when you run Get-Privilege -CurrentUser, only the privileges that 
    show up are the privileges that can be enabled or disabled.

    For instance, if SeDebugPrivilege is not available to enable/disable, when you run Enable-Privilege
    to enable and make use of this privilege, nothing will happen as it is not actively available. Same 
    goes for Disable-Privilege. If you want to use a particular privilege that is not available, then you
    must use the Add-Privilege function instead.

    Add/Remove Privileges
    =====================
    If there are privileges missing from your current process or you want to ensure another group has access
    to a privilege, you must use Add/Remove-Privilege to add or remove a privilege to a specific account or group.
    It is important to note that if a Group Policy Object (GPO) is applying restrictions to the user rights assignments,
    any change that you make to add or remove a privilege could potentially be overwritten once the policy refreshes.

    When you add a privilege using Add-Privilege, it is automatically enabled for use. It will not appear when you use 
    Get-Privilege -CurrentUser until you open up a new process and run the command again.

POWERSHELL COMPATIBILITY

    PoshPrivilege has been tested on PowerShell V3 and above version.

FEEDBACK

    https://github.com/proxb/PoshPrivilege
tools\PoshPrivilege\PoshPrivilege.psd1
 
tools\PoshPrivilege\PoshPrivilege.psm1
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path

#region Module Builder
$Domain = [AppDomain]::CurrentDomain
$DynAssembly = New-Object System.Reflection.AssemblyName('PrivilegeAssembly')
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) # Only run in memory
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('PrivilegeModule', $False)
#endregion Module Builder

#region Enums
#region LSA_AccessPolicy
$EnumBuilder = $ModuleBuilder.DefineEnum('LSA_AccessPolicy', 'Public', [uint32])
[void]$EnumBuilder.DefineLiteral('POLICY_AUDIT_LOG_ADMIN', [uint32] 0x00000200)
[void]$EnumBuilder.DefineLiteral('POLICY_CREATE_ACCOUNT', [uint32] 0x00000010)
[void]$EnumBuilder.DefineLiteral('POLICY_CREATE_PRIVILEGE', [uint32] 0x00000040)
[void]$EnumBuilder.DefineLiteral('POLICY_CREATE_SECRET', [uint32] 0x00000020)
[void]$EnumBuilder.DefineLiteral('POLICY_GET_PRIVATE_INFORMATION', [uint32] 0x00000004)
[void]$EnumBuilder.DefineLiteral('POLICY_LOOKUP_NAMES', [uint32] 0x00000800)
[void]$EnumBuilder.DefineLiteral('POLICY_NOTIFICATION', [uint32] 0x00001000)
[void]$EnumBuilder.DefineLiteral('POLICY_SERVER_ADMIN', [uint32] 0x00000400)
[void]$EnumBuilder.DefineLiteral('POLICY_SET_AUDIT_REQUIREMENTS', [uint32] 0x00000100)
[void]$EnumBuilder.DefineLiteral('POLICY_SET_DEFAULT_QUOTA_LIMITS', [uint32] 0x00000080)
[void]$EnumBuilder.DefineLiteral('POLICY_TRUST_ADMIN', [uint32] 0x00000008)
[void]$EnumBuilder.DefineLiteral('POLICY_VIEW_AUDIT_INFORMATION', [uint32] 0x00000002)
[void]$EnumBuilder.DefineLiteral('POLICY_VIEW_LOCAL_INFORMATION', [uint32] 0x00000001)
[void]$EnumBuilder.CreateType()
#endregion LSA_AccessPolicy
#region Privileges
$EnumBuilder = $ModuleBuilder.DefineEnum('Privileges', 'Public', [uint32])
[void]$EnumBuilder.DefineLiteral('SeAssignPrimaryTokenPrivilege',[uint32] 0x00000000)
[void]$EnumBuilder.DefineLiteral('SeAuditPrivilege',[uint32] 0x00000001)
[void]$EnumBuilder.DefineLiteral('SeBackupPrivilege',[uint32] 0x00000002)
[void]$EnumBuilder.DefineLiteral('SeBatchLogonRight',[uint32] 0x00000003)
[void]$EnumBuilder.DefineLiteral('SeChangeNotifyPrivilege',[uint32] 0x00000004)
[void]$EnumBuilder.DefineLiteral('SeCreateGlobalPrivilege',[uint32] 0x00000005)
[void]$EnumBuilder.DefineLiteral('SeCreatePagefilePrivilege',[uint32] 0x00000006)
[void]$EnumBuilder.DefineLiteral('SeCreatePermanentPrivilege',[uint32] 0x00000007)
[void]$EnumBuilder.DefineLiteral('SeCreateSymbolicLinkPrivilege',[uint32] 0x00000008)
[void]$EnumBuilder.DefineLiteral('SeCreateTokenPrivilege',[uint32] 0x00000009)
[void]$EnumBuilder.DefineLiteral('SeDebugPrivilege',[uint32] 0x0000000a)
[void]$EnumBuilder.DefineLiteral('SeImpersonatePrivilege',[uint32] 0x0000000b)
[void]$EnumBuilder.DefineLiteral('SeIncreaseBasePriorityPrivilege',[uint32] 0x0000000c)
[void]$EnumBuilder.DefineLiteral('SeIncreaseQuotaPrivilege',[uint32] 0x0000000d)
[void]$EnumBuilder.DefineLiteral('SeInteractiveLogonRight',[uint32] 0x0000000e)
[void]$EnumBuilder.DefineLiteral('SeLoadDriverPrivilege',[uint32] 0x0000000f)
[void]$EnumBuilder.DefineLiteral('SeLockMemoryPrivilege',[uint32] 0x00000010)
[void]$EnumBuilder.DefineLiteral('SeMachineAccountPrivilege',[uint32] 0x00000011)
[void]$EnumBuilder.DefineLiteral('SeManageVolumePrivilege',[uint32] 0x00000012)
[void]$EnumBuilder.DefineLiteral('SeNetworkLogonRight',[uint32] 0x00000013)
[void]$EnumBuilder.DefineLiteral('SeProfileSingleProcessPrivilege',[uint32] 0x00000014)
[void]$EnumBuilder.DefineLiteral('SeRemoteInteractiveLogonRight',[uint32] 0x00000015)
[void]$EnumBuilder.DefineLiteral('SeRemoteShutdownPrivilege',[uint32] 0x00000016)
[void]$EnumBuilder.DefineLiteral('SeRestorePrivilege',[uint32] 0x00000017)
[void]$EnumBuilder.DefineLiteral('SeSecurityPrivilege',[uint32] 0x00000018)
[void]$EnumBuilder.DefineLiteral('SeServiceLogonRight',[uint32] 0x00000019)
[void]$EnumBuilder.DefineLiteral('SeShutdownPrivilege',[uint32] 0x0000001a)
[void]$EnumBuilder.DefineLiteral('SeSystemEnvironmentPrivilege',[uint32] 0x0000001b)
[void]$EnumBuilder.DefineLiteral('SeSystemProfilePrivilege',[uint32] 0x0000001c)
[void]$EnumBuilder.DefineLiteral('SeSystemtimePrivilege',[uint32] 0x0000001d)
[void]$EnumBuilder.DefineLiteral('SeTakeOwnershipPrivilege',[uint32] 0x0000001e)
[void]$EnumBuilder.DefineLiteral('SeTcbPrivilege',[uint32] 0x0000001f)
[void]$EnumBuilder.DefineLiteral('SeTimeZonePrivilege',[uint32] 0x00000020)
[void]$EnumBuilder.DefineLiteral('SeUndockPrivilege',[uint32] 0x00000021)
[void]$EnumBuilder.DefineLiteral('SeDenyNetworkLogonRight',[uint32] 0x00000022)
[void]$EnumBuilder.DefineLiteral('SeDenyBatchLogonRight',[uint32] 0x00000023)
[void]$EnumBuilder.DefineLiteral('SeDenyServiceLogonRight',[uint32] 0x00000024)
[void]$EnumBuilder.DefineLiteral('SeDenyInteractiveLogonRight',[uint32] 0x00000025)
[void]$EnumBuilder.DefineLiteral('SeSyncAgentPrivilege',[uint32] 0x00000026)
[void]$EnumBuilder.DefineLiteral('SeEnableDelegationPrivilege',[uint32] 0x00000027)
[void]$EnumBuilder.DefineLiteral('SeDenyRemoteInteractiveLogonRight',[uint32] 0x00000028)
[void]$EnumBuilder.DefineLiteral('SeTrustedCredManAccessPrivilege',[uint32] 0x00000029)
[void]$EnumBuilder.DefineLiteral('SeIncreaseWorkingSetPrivilege',[uint32] 0x0000002a)
[void]$EnumBuilder.CreateType()
#endregion Privileges
#region TOKEN_INFORMATION_CLASS
$EnumBuilder = $ModuleBuilder.DefineEnum('TOKEN_INFORMATION_CLASS', 'Public', [uint32])
[void]$EnumBuilder.DefineLiteral('TokenUser ',[uint32] 0x00000001)
[void]$EnumBuilder.DefineLiteral('TokenGroups',[uint32] 0x00000002)
[void]$EnumBuilder.DefineLiteral('TokenPrivileges',[uint32] 0x00000003)
[void]$EnumBuilder.DefineLiteral('TokenOwner',[uint32] 0x00000004)
[void]$EnumBuilder.DefineLiteral('TokenPrimaryGroup',[uint32] 0x00000005)
[void]$EnumBuilder.DefineLiteral('TokenDefaultDacl',[uint32] 0x00000006)
[void]$EnumBuilder.DefineLiteral('TokenSource',[uint32] 0x00000007)
[void]$EnumBuilder.DefineLiteral('TokenType',[uint32] 0x00000008)
[void]$EnumBuilder.DefineLiteral('TokenImpersonationLevel',[uint32] 0x00000009)
[void]$EnumBuilder.DefineLiteral('TokenStatistics',[uint32] 0x0000000a)
[void]$EnumBuilder.DefineLiteral('TokenRestrictedSids',[uint32] 0x0000000b)
[void]$EnumBuilder.DefineLiteral('TokenSessionId',[uint32] 0x0000000c)
[void]$EnumBuilder.DefineLiteral('TokenGroupsAndPrivileges',[uint32] 0x0000000d)
[void]$EnumBuilder.DefineLiteral('TokenSessionReference',[uint32] 0x0000000e)
[void]$EnumBuilder.DefineLiteral('TokenSandBoxInert',[uint32] 0x0000000f)
[void]$EnumBuilder.DefineLiteral('TokenAuditPolicy',[uint32] 0x00000010)
[void]$EnumBuilder.DefineLiteral('TokenOrigin',[uint32] 0x00000011)
[void]$EnumBuilder.CreateType()
#endregion TOKEN_INFORMATION_CLASS
#region ProcessAccessFlags 
$EnumBuilder = $ModuleBuilder.DefineEnum('ProcessAccessFlags', 'Public', [uint32])
[void]$EnumBuilder.DefineLiteral('All', [uint32] 0x001F0FFF)
[void]$EnumBuilder.DefineLiteral('Terminate', [uint32] 0x00000001)
[void]$EnumBuilder.DefineLiteral('CreateThread', [uint32] 0x00000002)
[void]$EnumBuilder.DefineLiteral('VirtualMemoryOperation', [uint32] 0x00000008)
[void]$EnumBuilder.DefineLiteral('VirtualMemoryRead', [uint32] 0x00000010)
[void]$EnumBuilder.DefineLiteral('VirtualMemoryWrite', [uint32] 0x00000020)
[void]$EnumBuilder.DefineLiteral('DuplicateHandle', [uint32] 0x00000040)
[void]$EnumBuilder.DefineLiteral('CreateProcess', [uint32] 0x000000080)
[void]$EnumBuilder.DefineLiteral('SetQuota', [uint32] 0x00000100)
[void]$EnumBuilder.DefineLiteral('SetInformation', [uint32] 0x00000200)
[void]$EnumBuilder.DefineLiteral('QueryInformation', [uint32] 0x00000400)
[void]$EnumBuilder.DefineLiteral('QueryLimitedInformation', [uint32] 0x00001000)
[void]$EnumBuilder.DefineLiteral('Synchronize', [uint32] 0x00100000)
[void]$EnumBuilder.CreateType()
#endregion ProcessAccessFlags
#endregion Enums

#region Structs
#region TokPriv1Luid
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$STRUCT_TypeBuilder = $ModuleBuilder.DefineType('TokPriv1Luid', $Attributes, [System.ValueType], 1, 0x10)
[void]$STRUCT_TypeBuilder.DefineField('Count', [int], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('Luid', [long], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('Attr', [int], 'Public')
[void]$STRUCT_TypeBuilder.CreateType()
#endregion TokPriv1Luid
#region LUID
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$STRUCT_TypeBuilder = $ModuleBuilder.DefineType('LUID', $Attributes, [System.ValueType], 8)
[void]$STRUCT_TypeBuilder.DefineField('LowPart', [uint32], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('HighPart', [int], 'Public')
[void]$STRUCT_TypeBuilder.CreateType()
#endregion LUID
#region LARGE_INTEGER
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$STRUCT_TypeBuilder = $ModuleBuilder.DefineType('LARGE_INTEGER', $Attributes, [System.ValueType], 8)
[void]$STRUCT_TypeBuilder.DefineField('LowPart', [uint32], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('HighPart', [uint32], 'Public')
[void]$STRUCT_TypeBuilder.CreateType()
#endregion LARGE_INTEGER
#region LUID_AND_ATTRIBUTES
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$STRUCT_TypeBuilder = $ModuleBuilder.DefineType('LUID_AND_ATTRIBUTES', $Attributes, [System.ValueType], 12)
[void]$STRUCT_TypeBuilder.DefineField('Luid', [LUID], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('Attributes', [uint32], 'Public')
[void]$STRUCT_TypeBuilder.CreateType()
#endregion LUID_AND_ATTRIBUTES
#region LSA_UNICODE_STRING
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$STRUCT_TypeBuilder = $ModuleBuilder.DefineType('LSA_UNICODE_STRING', $Attributes, [System.ValueType], 8, 0x0)
[void]$STRUCT_TypeBuilder.DefineField('Length', [uint16], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('MaximumLength', [uint16], 'Public')
$ctor = [System.Runtime.InteropServices.MarshalAsAttribute].GetConstructor(@([System.Runtime.InteropServices.UnmanagedType]))
$CustomAttribute = [System.Runtime.InteropServices.UnmanagedType]::LPWStr
$CustomAttributeBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder -ArgumentList $ctor, $CustomAttribute 
$BufferField = $STRUCT_TypeBuilder.DefineField('Buffer', [string], @('Public','HasFieldMarshal'))
$BufferField.SetCustomAttribute($CustomAttributeBuilder)
[void]$STRUCT_TypeBuilder.CreateType()
#endregion LSA_UNICODE_STRING
#region LSA_OBJECT_ATTRIBUTES
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$STRUCT_TypeBuilder = $ModuleBuilder.DefineType('LSA_OBJECT_ATTRIBUTES', $Attributes, [System.ValueType], 8, 0x0)
[void]$STRUCT_TypeBuilder.DefineField('RootDirectory', [intptr], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('SecurityDescriptor', [intptr], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('SecurityQualityOfService', [intptr], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('ObjectName', [LSA_UNICODE_STRING], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('Attributes', [int], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('Length', [int], 'Public')
[void]$STRUCT_TypeBuilder.CreateType()
#endregion LSA_OBJECT_ATTRIBUTES
#region LSA_ENUMERATION_INFORMATION
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$STRUCT_TypeBuilder = $ModuleBuilder.DefineType('LSA_ENUMERATION_INFORMATION', $Attributes, [System.ValueType], 1, 0x8)
[void]$STRUCT_TypeBuilder.DefineField('Sid', [intptr], 'Public')
[void]$STRUCT_TypeBuilder.CreateType()
#endregion LSA_ENUMERATION_INFORMATION
#region TOKEN_STATISTICS
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$STRUCT_TypeBuilder = $ModuleBuilder.DefineType('TOKEN_STATISTICS', $Attributes, [System.ValueType])
[void]$STRUCT_TypeBuilder.DefineField('TokenId', [LUID], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('AuthenticationId', [LUID], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('ExpirationTime', [LARGE_INTEGER], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('TokenType', [uint32], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('ImpersonationLevel', [uint32], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('DynamicCharged', [uint32], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('DynamicAvailable', [uint32], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('GroupCount', [uint32], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('PrivilegeCount', [uint32], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('ModifiedId', [LUID], 'Public')
[void]$STRUCT_TypeBuilder.CreateType()
#endregion TOKEN_STATISTICS
#region TOKEN_PRIVILEGES
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$STRUCT_TypeBuilder = $ModuleBuilder.DefineType('TOKEN_PRIVILEGES', $Attributes, [System.ValueType])
[void]$STRUCT_TypeBuilder.DefineField('PrivilegeCount', [uint32], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('Privileges', [LUID_AND_ATTRIBUTES], 'Public')
[void]$STRUCT_TypeBuilder.CreateType()
#endregion TOKEN_PRIVILEGES
#endregion Structs

#region Initialize Type Builder
$TypeBuilder = $ModuleBuilder.DefineType('PoShPrivilege', 'Public, Class')
#endregion Initialize Type Builder

#region Methods
#region AdjustTokenPrivileges
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'AdjustTokenPrivileges', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [bool], #Method Return Type
    [Type[]] @([intptr], [bool], [TokPriv1Luid].MakeByRefType() ,[int], [intptr], [intptr]) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
)

$FieldValueArray = [Object[]] @(
    'AdjustTokenPrivileges', #CASE SENSITIVE!!
    $True,
    $True
)

$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
#endregion AdjustTokenPrivileges
#region RevertToSelf
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'RevertToSelf', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [bool], #Method Return Type
    [Type[]] @() #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
)

$FieldValueArray = [Object[]] @(
    'RevertToSelf', #CASE SENSITIVE!!
    $True,
    $True
)

$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
#endregion RevertToSelf
#region OpenProcessToken Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'OpenProcessToken', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [bool], #Method Return Type
    [Type[]] @(
        [intptr], 
        [int], 
        [intptr].MakeByRefType()
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
)

$FieldValueArray = [Object[]] @(
    'OpenProcessToken', #CASE SENSITIVE!!
    $True,
    $True
)

$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
#endregion OpenProcessToken Method
#region GetCurrentProcess
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'GetCurrentProcess', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [intptr], #Method Return Type
    [Type[]] @() #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
)

$FieldValueArray = [Object[]] @(
    'GetCurrentProcess', #CASE SENSITIVE!!
    $True,
    $True
)

$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('kernel32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
#endregion GetCurrentProcess Method
#region LookupPrivilegeValue Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'LookupPrivilegeValue', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [bool], #Method Return Type
    [Type[]] @(
        [string],              #lpSystemName
        [string],              #lpName
        [long].MakeByRefType() #lpLuid
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
)

$FieldValueArray = [Object[]] @(
    'LookupPrivilegeValue', #CASE SENSITIVE!!
    $True
)

$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
#endregion LookupPrivilegeValue Method
#region LsaAddAccountRights Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'LsaAddAccountRights', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [uint32], #Method Return Type
    [Type[]] @(
        [intptr],   #PolicyHandle
        [intptr],   #AccountSID
        [LSA_UNICODE_STRING[]], #UserRights
        [int]    #CountofRights
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
    [Runtime.InteropServices.DllImportAttribute].GetField('CharSet')
)

$FieldValueArray = [Object[]] @(
    'LsaAddAccountRights', #CASE SENSITIVE!!
    $True,
    $True,
    [System.Runtime.InteropServices.CharSet]::Auto
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray    
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion LsaAddAccountRights Method
#region LsaRemoveAccountRights Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'LsaRemoveAccountRights', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [uint32], #Method Return Type
    [Type[]] @(
        [intptr],               #PolicyHandle
        [intptr],               #AccountSID
        [bool],                 #AllRights
        [LSA_UNICODE_STRING[]], #UserRights
        [int]                   #CountofRights
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
    [Runtime.InteropServices.DllImportAttribute].GetField('CharSet')
)

$FieldValueArray = [Object[]] @(
    'LsaRemoveAccountRights', #CASE SENSITIVE!!
    $True,
    $True,
    [System.Runtime.InteropServices.CharSet]::Unicode
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray    
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion LsaRemoveAccountRights Method
#region LsaOpenPolicy Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'LsaOpenPolicy', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [uint32], #Method Return Type
    [Type[]] @(
        [LSA_UNICODE_STRING].MakeByRefType(), #SystemName
        [LSA_OBJECT_ATTRIBUTES].MakeByRefType(), #Object
        [uint32],
        [intptr].MakeByRefType()
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
)

$FieldValueArray = [Object[]] @(
    'LsaOpenPolicy', #CASE SENSITIVE!!
    $True,
    $True,
    $True
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion LsaOpenPolicy Method
#region LsaNTStatusToWinError Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'LsaNtStatusToWinError', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [uint64], #Method Return Type
    [Type[]] @(
        [uint16]   #Status
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
)

$FieldValueArray = [Object[]] @(
    'LsaNtStatusToWinError', #CASE SENSITIVE!!
    $True,
    $True,
    $True
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion LsaNTStatusToWinError Method
#region LsaClose Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'LsaClose', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [uint64], #Method Return Type
    [Type[]] @(
        [intptr]   #ObjectHandle
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
)

$FieldValueArray = [Object[]] @(
    'LsaClose', #CASE SENSITIVE!!
    $True,
    $True,
    $True
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion LsaClose Method
#region FreeSid Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'FreeSid', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [intptr], #Method Return Type
    [Type[]] @(
        [intptr]   #pSID
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
)

$FieldValueArray = [Object[]] @(
    'FreeSid', #CASE SENSITIVE!!
    $True,
    $True,
    $True
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion FreeSid Method
#region ConvertStringSIDToSID Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'ConvertStringSidToSid', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [bool], #Method Return Type
    [Type[]] @(
        [string],                #StringSID
        [intptr].MakeByRefType() #ptrSID
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
)

$FieldValueArray = [Object[]] @(
    'ConvertStringSidToSid', #CASE SENSITIVE!!
    $True,
    $False,
    $True
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion ConvertStringSIDToSID Method
#region LsaEnumerateAccountsWithUserRight Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'LsaEnumerateAccountsWithUserRight', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [uint32], #Method Return Type
    [Type[]] @(
        [intptr], 
        [LSA_UNICODE_STRING[]], 
        [intptr].MakeByRefType(),
        [int].MakeByRefType()
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('CharSet')
)

$FieldValueArray = [Object[]] @(
    'LsaEnumerateAccountsWithUserRight', #CASE SENSITIVE!!
    $True,
    [System.Runtime.InteropServices.CharSet]::Unicode
)

$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
#endregion LsaEnumerateAccountsWithUserRight Method
#region ConvertSidToStringSid Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'ConvertSidToStringSid', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [bool], #Method Return Type
    [Type[]] @(
        [intptr],                #pSID
        [string].MakeByRefType() #sSID
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
)

$FieldValueArray = [Object[]] @(
    'ConvertSidToStringSid', #CASE SENSITIVE!!
    $True,
    $False,
    $True
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion ConvertSidToStringSid Method
#region LsaFreeMemory Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'LsaFreeMemory', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [uint32], #Method Return Type
    [Type[]] @(
        [intptr] #pBuffer
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
)

$FieldValueArray = [Object[]] @(
    'LsaFreeMemory', #CASE SENSITIVE!!
    $True,
    $True,
    $True
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion LsaFreeMemory Method
#region LsaClose Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'LsaClose', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [uint32], #Method Return Type
    [Type[]] @(
        [intptr] #ObjetHandle
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
)

$FieldValueArray = [Object[]] @(
    'LsaClose', #CASE SENSITIVE!!
    $True,
    $True,
    $True
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion LsaClose Method
#region GetTokenInformation Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'GetTokenInformation', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [bool], #Method Return Type
    [Type[]] @(
        [intptr],                  #TokenHandle
        [TOKEN_INFORMATION_CLASS], #TokenInformationClass
        [intptr],                  #TokenInformation
        [uint32],                  #TokenInformationLength
        [uint32].MakeByRefType()   #ReturnLength
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
)

$FieldValueArray = [Object[]] @(
    'GetTokenInformation', #CASE SENSITIVE!!
    $True,
    $True,
    $True
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion GetTokenInformation Method
#region LookupPrivilegeName Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'LookupPrivilegeName', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [bool], #Method Return Type
    [Type[]] @(
        [string],                    #lpSystemName
        [intptr],                    #lpLUID
        [System.Text.StringBuilder], #lpName
        [int].MakeByRefType()        #TokenInformationLength
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
)

$FieldValueArray = [Object[]] @(
    'LookupPrivilegeName', #CASE SENSITIVE!!
    $True,
    $False,
    $True
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion LookupPrivilegeName Method
#region LookupPrivilegeNameW Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'LookupPrivilegeNameW', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [bool], #Method Return Type
    [Type[]] @(
        [intptr],
        [intptr],
        [intptr],
        [uint32].MakeByRefType()
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
)

$FieldValueArray = [Object[]] @(
    'LookupPrivilegeNameW', #CASE SENSITIVE!!
    $True,
    $True,
    $True
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion LookupPrivilegeNameW Method
#region OpenProcess Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'OpenProcess', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [intptr], #Method Return Type
    [Type[]] @(
        [ProcessAccessFlags], #ProcessAccess
        [bool],               #InheritHandle
        [int]                 #processID
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
)

$FieldValueArray = [Object[]] @(
    'OpenProcess', #CASE SENSITIVE!!
    $True,
    $True,
    $True
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('kernel32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion OpenProcess Method
#region CloseHandle Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'CloseHandle', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [bool], #Method Return Type
    [Type[]] @(
        [intptr] #Handle
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
)

$FieldValueArray = [Object[]] @(
    'CloseHandle', #CASE SENSITIVE!!
    $True,
    $True,
    $True
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('kernel32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion CloseHandle Method
#region LookupPrivilegeDisplayName Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
    'LookupPrivilegeDisplayName', #Method Name
    [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
    [bool], #Method Return Type
    [Type[]] @(
        [string],                    #SystemName
        [string],                    #PrivilegeName
        [System.Text.StringBuilder], #DisplayName
        [uint32].MakeByRefType(),    #cbDisplayName
        [uint32].MakeByRefType()     #LanguageID
    ) #Method Parameters
)

$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
    [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
    [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
    [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
    [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig'),
    [Runtime.InteropServices.DllImportAttribute].GetField('CharSet')
)

$FieldValueArray = [Object[]] @(
    'LookupPrivilegeDisplayName', #CASE SENSITIVE!!
    $True,
    $False,
    $True,
    [System.Runtime.InteropServices.CharSet]::Unicode
)

$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
    $DllImportConstructor,
    @('advapi32.dll'),
    $FieldArray,
    $FieldValueArray
)

$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion LookupPrivilegeDisplayName Method
#endregion Methods

#region Create Type
[void]$TypeBuilder.CreateType()
#endregion Create Type

#region Load Public Functions
Try {
    Get-ChildItem "$ScriptPath\Scripts" -Filter *.ps1 | Select -Expand FullName | ForEach {
        $Function = Split-Path $_ -Leaf
        . $_
    }
} Catch {
    Write-Warning ("{0}: {1}" -f $Function,$_.Exception.Message)
    Continue
}
#endregion Load Public Functions

#region Private Functions
Function AddSignedIntAsUnsigned {
    ##Source function from Matt Graeber and Joe Balek
    [cmdletbinding()]
	Param(
	[Parameter(Position = 0, Mandatory = $true)]
	[Int64]
	$Value1,
		
	[Parameter(Position = 1, Mandatory = $true)]
	[Int64]
	$Value2
	)
		
	[Byte[]]$Value1Bytes = [BitConverter]::GetBytes($Value1)
	[Byte[]]$Value2Bytes = [BitConverter]::GetBytes($Value2)
	[Byte[]]$FinalBytes = [BitConverter]::GetBytes([UInt64]0)

	if ($Value1Bytes.Count -eq $Value2Bytes.Count)
	{
		$CarryOver = 0
		for ($i = 0; $i -lt $Value1Bytes.Count; $i++)
		{
			#Add bytes
			[UInt16]$Sum = $Value1Bytes[$i] + $Value2Bytes[$i] + $CarryOver

			$FinalBytes[$i] = $Sum -band 0x00FF
				
			if (($Sum -band 0xFF00) -eq 0x100)
			{
				$CarryOver = 1
			}
			else
			{
				$CarryOver = 0
			}
            Write-Verbose "Carryover: $($CarryOver)"
		}
	}
	else
	{
		Throw "Cannot add bytearrays of different sizes"
	}
		
	return [BitConverter]::ToInt64($FinalBytes, 0)
}
Function GetPrivilegeDisplayName {
    Param ([Privileges]$Privilege)
    [uint32]$DisplayName = 150
    [uint32]$LanguageId = 0
    $StringBuilder = New-Object System.Text.StringBuilder
    [void]$StringBuilder.EnsureCapacity($DisplayName)
    $return=[PoshPrivilege]::LookupPrivilegeDisplayName(
        $env:COMPUTERNAME,
        $Privilege,
        $StringBuilder,
        [ref]$DisplayName,
        [ref]$LanguageId
    )
    If ($return) {
        $StringBuilder.ToString()
    }
}
#endregion Private Functions

#region Aliases
New-Alias -Name gppv -Value Get-Privilege
New-Alias -Name appv -Value Add-Privilege
New-Alias -Name rppv -Value Remove-Privilege
New-Alias -Name eppv -Value Enable-Privilege
New-Alias -Name dppv -Value Disable-Privilege
#endregion Aliases

#region Load Type and Format Files
Update-FormatData "$ScriptPath\TypeData\PoShPrivilege.Format.ps1xml"
#endregion Load Type and Format Files

Export-ModuleMember -Alias * -Function '*-Privilege'
tools\PoshPrivilege\Scripts\Add-Privilege.ps1
Function Add-Privilege {
    <#
        .SYNOPSIS
            Adds a specified privilege for a user or group

        .DESCRIPTION
            Adds a specified privilege for a user or group. This will remain until
            removed using Remove-Privilege or a policy is refreshed.

        .PARAMETER AccountName            
            The user or group which will have the privilege added for.
        
        .PARAMETER Privilege            
            Specific privilege/s to add on the local machine
        
        .NOTES
            Name: Add-Privilege
            Author: Boe Prox
            Version History:
                1.0 - Initial Version        

        .EXAMPLE
        Add-Privilege -AccountName Domain\SomeUser -Privilege SeBackupPrivilege

        Description
        -----------
        Adds the SeBackupPrivilege privilege for Domain\SomeUser
        
    #>
    [cmdletbinding(
        SupportsShouldProcess = $True
    )]
    Param (
        [parameter()]
        [string]$AccountName = ("{0}\{1}" -f ($env:USERDOMAIN, $env:USERNAME)),
        [parameter(Mandatory=$True)]
        [Privileges[]]$Privilege
    )
    #No point going through everything if just using -WhatIf
    If ($PSCmdlet.ShouldProcess($AccountName,"Add Privilege(s): $($Privilege -join ', ')")) {
        #region ConvertSIDStringToSID
        Write-Verbose "Gathering SID information"
        $AccountSID = ([System.Security.Principal.NTAccount]$AccountName).Translate([System.Security.Principal.SecurityIdentifier])
        $SID = [intptr]::Zero
        [void][PoshPrivilege]::ConvertStringSidToSid($AccountSID, [ref]$SID)
        #endregion ConvertSIDStringToSID

        #region LsaOpenPolicy
        $Computer = New-Object LSA_UNICODE_STRING
        $Computer.Buffer = $env:COMPUTERNAME
        $Computer.Length = ($Computer.buffer.length * [System.Text.UnicodeEncoding]::CharSize)
        $Computer.MaximumLength = (($Computer.buffer.length+1) * [System.Text.UnicodeEncoding]::CharSize)
        $PolicyHandle = [intptr]::Zero
        $ObjectAttributes = New-Object LSA_OBJECT_ATTRIBUTES
        [uint32]$Access = [LSA_AccessPolicy]::POLICY_CREATE_ACCOUNT -BOR [LSA_AccessPolicy]::POLICY_LOOKUP_NAMES
        Write-Verbose "Opening policy handle"
        $NTStatus = [PoshPrivilege]::LsaOpenPolicy(
            [ref]$Computer,
            [ref]$ObjectAttributes,
            $Access,
            [ref]$PolicyHandle
        )

        #region winErrorCode
        If ($NTStatus -ne 0) {
            $Win32ErrorCode = [PoshPrivilege]::LsaNtStatusToWinError($return)
            Write-Warning $(New-Object System.ComponentModel.Win32Exception -ArgumentList $Win32ErrorCode)
            BREAK
        }
        #endregion winErrorCode
        #endregion LsaOpenPolicy

        #region LsaAddAccountRights'
        ForEach ($Priv in $Privilege) {
            $PrivilegeName = [privileges]::$Priv
            $_UserRights = New-Object LSA_UNICODE_STRING
            $_UserRights.Buffer = $Priv.ToString()
            $_UserRights.Length = ($_UserRights.Buffer.length * [System.Text.UnicodeEncoding]::CharSize)
            $_UserRights.MaximumLength = ($_UserRights.Length + [System.Text.UnicodeEncoding]::CharSize)
            $UserRights = New-Object LSA_UNICODE_STRING[] -ArgumentList 1
            $UserRights[0] = $_UserRights
            Write-Verbose "Adding Privilege: $($PrivilegeName.ToString())"
            $NTStatus = [PoshPrivilege]::LsaAddAccountRights(
                $PolicyHandle,
                $SID,
                $UserRights,
                1    
            )

            #region winErrorCode
            If ($NTStatus -ne 0) {
                $Win32ErrorCode = [PoshPrivilege]::LsaNtStatusToWinError($return)
                Write-Warning $(New-Object System.ComponentModel.Win32Exception -ArgumentList $Win32ErrorCode)
                BREAK
            }
        }
        #endregion winErrorCode

        #endregion LsaAddAccountRights

        #region Cleanup
    
        #region Close Policy Handle
        [void][PoshPrivilege]::LsaClose($PolicyHandle)
        #endregion Close Policy Handle

        #region Clear Pointers
        [void][System.Runtime.InteropServices.Marshal]::FreeHGlobal($SID)
        #endregion Clear Pointers

        #endregion Cleanup
    }
}
tools\PoshPrivilege\Scripts\Disable-Privilege.ps1
Function Disable-Privilege {
    <#
        .SYNOPSIS
            Disables specific privilege or privileges on the current process.

        .DESCRIPTION
            Disables specific privilege or privileges on the current process.
        
        .PARAMETER Privilege            
            Specific privilege/s to enable on the current process
        
        .NOTES
            Name: Enable-Privilege
            Author: Boe Prox
            Version History:
                1.0 - Initial Version

        .EXAMPLE
        Disable-Privilege -Privilege SeBackupPrivilege

        Description
        -----------
        Disables the SeBackupPrivilege on the existing process

        .EXAMPLE
        Disable-Privilege -Privilege SeBackupPrivilege, SeRestorePrivilege, SeTakeOwnershipPrivilege

        Description
        -----------
        Disables the SeBackupPrivilege,  SeRestorePrivilege and SeTakeOwnershipPrivilege on the existing process
        
    #>
    [cmdletbinding(
        SupportsShouldProcess = $True
    )]
    Param (
        [parameter(Mandatory = $True)]
        [Privileges[]]$Privilege
    )    
    If ($PSCmdlet.ShouldProcess("Process ID: $PID", "Disable Privilege(s): $($Privilege -join ', ')")) {
        #region Constants
        $SE_PRIVILEGE_ENABLED = 0x00000002
        $SE_PRIVILEGE_DISABLED = 0x00000000
        $TOKEN_QUERY = 0x00000008
        $TOKEN_ADJUST_PRIVILEGES = 0x00000020
        #endregion Constants

        $TokenPriv = New-Object TokPriv1Luid
        $HandleToken = [intptr]::Zero
        $TokenPriv.Count = 1
        $TokenPriv.Attr = $SE_PRIVILEGE_DISABLED
    
        #Open the process token
        $Return = [PoshPrivilege]::OpenProcessToken(
            [PoshPrivilege]::GetCurrentProcess(),
            ($TOKEN_QUERY -BOR $TOKEN_ADJUST_PRIVILEGES), 
            [ref]$HandleToken
        )    
        If (-NOT $Return) {
            Write-Warning "Unable to open process token! Aborting!"
            Break
        }
        ForEach ($Priv in $Privilege) {
            $PrivValue = $Null
            $TokenPriv.Luid = 0
            #Lookup privilege value
            $Return = [PoshPrivilege]::LookupPrivilegeValue($Null, $Priv, [ref]$PrivValue) 
            If ($Return) {
                $TokenPriv.Luid = $PrivValue
                #Adjust the process privilege value
                $return = [PoshPrivilege]::AdjustTokenPrivileges(
                    $HandleToken, 
                    $False, 
                    [ref]$TokenPriv, 
                    [System.Runtime.InteropServices.Marshal]::SizeOf($TokenPriv), 
                    [IntPtr]::Zero, 
                    [IntPtr]::Zero
                )
                If (-NOT $Return) {
                    Write-Warning "Unable to disable privilege <$priv>! "
                }
            }
        }
    }
}
tools\PoshPrivilege\Scripts\Enable-Privilege.ps1
Function Enable-Privilege {
    <#
        .SYNOPSIS
            Enables specific privilege or privileges on the current process.

        .DESCRIPTION
            Enables specific privilege or privileges on the current process.
        
        .PARAMETER Privilege            
            Specific privilege/s to enable on the current process
        
        .NOTES
            Name: Enable-Privilege
            Author: Boe Prox
            Version History:
                1.0 - Initial Version

        .EXAMPLE
        Enable-Privilege -Privilege SeBackupPrivilege

        Description
        -----------
        Enables the SeBackupPrivilege on the existing process

        .EXAMPLE
        Enable-Privilege -Privilege SeBackupPrivilege, SeRestorePrivilege, SeTakeOwnershipPrivilege

        Description
        -----------
        Enables the SeBackupPrivilege,  SeRestorePrivilege and SeTakeOwnershipPrivilege on the existing process
        
    #>
    [cmdletbinding(
        SupportsShouldProcess = $True
    )]
    Param (
        [parameter(Mandatory = $True)]
        [Privileges[]]$Privilege
    )    
    If ($PSCmdlet.ShouldProcess("Process ID: $PID", "Enable Privilege(s): $($Privilege -join ', ')")) {
        #region Constants
        $SE_PRIVILEGE_ENABLED = 0x00000002
        $SE_PRIVILEGE_DISABLED = 0x00000000
        $TOKEN_QUERY = 0x00000008
        $TOKEN_ADJUST_PRIVILEGES = 0x00000020
        #endregion Constants

        $TokenPriv = New-Object TokPriv1Luid
        $HandleToken = [intptr]::Zero
        $TokenPriv.Count = 1
        $TokenPriv.Attr = $SE_PRIVILEGE_ENABLED
    
        #Open the process token
        $Return = [PoshPrivilege]::OpenProcessToken(
            [PoshPrivilege]::GetCurrentProcess(),
            ($TOKEN_QUERY -BOR $TOKEN_ADJUST_PRIVILEGES), 
            [ref]$HandleToken
        )    
        If (-NOT $Return) {
            Write-Warning "Unable to open process token! Aborting!"
            Break
        }
        ForEach ($Priv in $Privilege) {
            $PrivValue = $Null
            $TokenPriv.Luid = 0
            #Lookup privilege value
            $Return = [PoshPrivilege]::LookupPrivilegeValue($Null, $Priv, [ref]$PrivValue)             
            If ($Return) {
                $TokenPriv.Luid = $PrivValue
                #Adjust the process privilege value                
                $return = [PoshPrivilege]::AdjustTokenPrivileges(
                    $HandleToken, 
                    $False, 
                    [ref]$TokenPriv, 
                    [System.Runtime.InteropServices.Marshal]::SizeOf($TokenPriv), 
                    [IntPtr]::Zero, 
                    [IntPtr]::Zero
                )
                If (-NOT $Return) {
                    Write-Warning "Unable to enable privilege <$priv>! "
                }
            }
        }
    }
}
tools\PoshPrivilege\Scripts\Get-Privilege.ps1
Function Get-Privilege {
    <#
        .SYNOPSIS
            Gets all privileges on a local or remote system.

        .DESCRIPTION
            Gets the currently applied privileges or current user privileges.
        
        .PARAMETER Privilege            
            Specific privilege/s to view.

        .PARAMETER Computername
            View privileges on a remote system

        .PARAMETER CurrentUser
            View the currently applied privileges for the current user
        
        .NOTES
            Name: Get-Privilege
            Author: Boe Prox
            Version History:
                1.0 - Initial Version

        .EXAMPLE
            Get-Privilege

            Computername         Privilege                        Accounts
            ------------         ---------                        --------
            BOE-PC               SeAssignPrimaryTokenPrivilege    {IIS APPPOOL\.NET v4.5 Cl...
            BOE-PC               SeAuditPrivilege                 {IIS APPPOOL\.NET v4.5 Cl...
            BOE-PC               SeBackupPrivilege                {BUILTIN\Backup Operators...
            BOE-PC               SeBatchLogonRight                {BUILTIN\IIS_IUSRS, BUILT...
            BOE-PC               SeChangeNotifyPrivilege          {Window Manager\Window Ma...
            BOE-PC               SeCreateGlobalPrivilege          {NT AUTHORITY\SERVICE, BU...
            BOE-PC               SeCreatePagefilePrivilege        {BUILTIN\Administrators}
            BOE-PC               SeCreatePermanentPrivilege       {}
            BOE-PC               SeCreateSymbolicLinkPrivilege    {BUILTIN\Administrators}
            ...

            Description
            -----------
            Enables the SeBackupPrivilege on the existing process

        .EXAMPLE
            Get-Privilege -CurrentUser

            Privilege                        Description                              Enabled
            ---------                        -----------                              -------
            SeLockMemoryPrivilege            Lock pages in memory                     False
            SeIncreaseQuotaPrivilege         Adjust memory quotas for a process       False
            SeTcbPrivilege                   Act as part of the operating system      False
            SeSecurityPrivilege              Manage auditing and security log         False
            SeTakeOwnershipPrivilege         Take ownership of files or other objects False
            SeLoadDriverPrivilege            Load and unload device drivers           False
            SeSystemProfilePrivilege         Profile system performance               False
            SeSystemtimePrivilege            Change the system time                   False
            SeProfileSingleProcessPrivilege  Profile single process                   False
            SeIncreaseBasePriorityPrivilege  Increase scheduling priority             False
            SeCreatePagefilePrivilege        Create a pagefile                        False
            SeBackupPrivilege                Back up files and directories            False
            SeRestorePrivilege               Restore files and directories            False
            SeShutdownPrivilege              Shut down the system                     False
            SeDebugPrivilege                 Debug programs                           True
            SeSystemEnvironmentPrivilege     Modify firmware environment values       False
            SeChangeNotifyPrivilege          Bypass traverse checking                 True
            SeRemoteShutdownPrivilege        Force shutdown from a remote system      False
            SeUndockPrivilege                Remove computer from docking station     False
            SeManageVolumePrivilege          Perform volume maintenance tasks         False
            SeImpersonatePrivilege           Impersonate a client after authentica... True
            SeCreateGlobalPrivilege          Create global objects                    True
            SeIncreaseWorkingSetPrivilege    Increase a process working set           False
            SeTimeZonePrivilege              Change the time zone                     False
            SeCreateSymbolicLinkPrivilege    Create symbolic links                    False

            Description
            -----------
            Displays currently applied privileges for current user.

        .EXAMPLE
            Get-Privilege -Privilege SeDebugPrivilege

            Computername         Privilege                        Accounts
            ------------         ---------                        --------
            BOE-PC               SeDebugPrivilege                 {}

        Description
        -----------
        Shows all accounts/groups that have been given SeDebugPrivilege

        .OutputType
            PSPrivilege.Privilege
            PSPrivilege.CurrentUserPrivilege
    #>
    #REQUIRES -Version 3.0
    [OutputType('PSPrivilege.Privilege','PSPrivilege.CurrentUserPrivilege')]
    [cmdletbinding(
        DefaultParameterSetName = 'Default'
    )]
    Param (
        [parameter(ParameterSetName='Default')]
        [Privileges[]]$Privilege,
        [parameter(ParameterSetName='Default')]
        [string]$Computername = $Env:Computername  ,
        [parameter(ParameterSetName='CurrentUser')]
        [switch]$CurrentUser
    )
    Switch ($PSCmdlet.ParameterSetName) {
        'CurrentUser' {
            $Process = Get-Process -Id $PID
            $PROCESS_QUERY_INFORMATION = [ProcessAccessFlags]::QueryInformation

            $TOKEN_ALL_ACCESS = [System.Security.Principal.TokenAccessLevels]::AllAccess
            $hProcess = [PoShPrivilege]::OpenProcess(
                $PROCESS_QUERY_INFORMATION, 
                $True, 
                $Process.Id
            )
            Write-Debug "ProcessHandle: $($hProcess)"

            $hProcessToken = [intptr]::Zero
            [void][PoShPrivilege]::OpenProcessToken(
                $hProcess, 
                $TOKEN_ALL_ACCESS, 
                [ref]$hProcessToken
            )
            Write-Debug "ProcessToken: $($hProcessToken)"
            [void][PoShPrivilege]::CloseHandle($hProcess)

            [UInt32]$TokenPrivSize = 1000
            [IntPtr]$TokenPrivPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TokenPrivSize)
            [uint32]$ReturnLength = 0
            [void][PoShPrivilege]::GetTokenInformation(
                $hProcessToken,
                [TOKEN_INFORMATION_CLASS]::TokenPrivileges,
                $TokenPrivPtr,
                $TokenPrivSize,
                [ref]$ReturnLength
            )

            $TokenPrivileges = [System.Runtime.InteropServices.Marshal]::PtrToStructure($TokenPrivPtr, [Type][TOKEN_PRIVILEGES])
            [IntPtr]$PrivilegesBasePtr = [IntPtr](AddSignedIntAsUnsigned $TokenPrivPtr ([System.Runtime.InteropServices.Marshal]::OffsetOf(
                [Type][TOKEN_PRIVILEGES], "Privileges"
            )))
            $LuidAndAttributeSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][LUID_AND_ATTRIBUTES])
            for ($i=0; $i -lt $TokenPrivileges.PrivilegeCount; $i++) {
                $LuidAndAttributePtr = [IntPtr](AddSignedIntAsUnsigned $PrivilegesBasePtr ($LuidAndAttributeSize * $i))
                $LuidAndAttribute = [System.Runtime.InteropServices.Marshal]::PtrToStructure($LuidAndAttributePtr, [Type][LUID_AND_ATTRIBUTES])
                [UInt32]$PrivilegeNameSize = 60
                $PrivilegeNamePtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PrivilegeNameSize)
                $PLuid = $LuidAndAttributePtr
                [void][PoShPrivilege]::LookupPrivilegeNameW(
                    [IntPtr]::Zero, 
                    $PLuid, 
                    $PrivilegeNamePtr, 
                    [Ref]$PrivilegeNameSize
                )
                $PrivilegeName = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($PrivilegeNamePtr)
                $Enabled = $False
                If ($LuidAndAttribute.Attributes -ne 0) {
                    $Enabled = $True
                }
                $Object = [pscustomobject]@{
                    Computername = $env:COMPUTERNAME
                    Account = "{0}\{1}" -f ($env:USERDOMAIN, $env:USERNAME)
                    Privilege = $PrivilegeName
                    Description = GetPrivilegeDisplayName -Privilege $PrivilegeName
                    Enabled = $Enabled
                }
                $Object.pstypenames.insert(0,'PSPrivilege.CurrentUserPrivilege')
                $Object
            }
        }
        Default {
            If (-NOT $PSBoundParameters.ContainsKey('Privilege')) {
                $Privilege = [Privileges].GetEnumNames()
            }

            #region LsaOpenPolicy
            $Computer = New-Object LSA_UNICODE_STRING
            $Computer.Buffer = $Computername
            $Computer.Length = ($Computer.buffer.length * [System.Text.UnicodeEncoding]::CharSize)
            $Computer.MaximumLength = (($Computer.buffer.length+1) * [System.Text.UnicodeEncoding]::CharSize)
            $PolicyHandle = [intptr]::Zero
            $ObjectAttributes = New-Object LSA_OBJECT_ATTRIBUTES
            [uint32]$Access = [LSA_AccessPolicy]::POLICY_VIEW_LOCAL_INFORMATION -BOR [LSA_AccessPolicy]::POLICY_LOOKUP_NAMES
            Write-Verbose "Opening policy handle"
            [void][PoShPrivilege]::LsaOpenPolicy(
                [ref]$Computer,
                [ref]$ObjectAttributes,
                $Access,
                [ref]$PolicyHandle
            )
            #endregion LsaOpenPolicy

            #region LsaEnumerateAccountsWithUserRight
            ForEach ($Priv in $Privilege) {
                $UserRight = New-Object LSA_UNICODE_STRING
                $UserRight.Buffer = $Priv.ToString()
                $UserRight.Length = ($UserRight.Buffer.Length * [System.Text.UnicodeEncoding]::CharSize)
                $UserRight.MaximumLength = (($UserRight.buffer.length+1) * [System.Text.UnicodeEncoding]::CharSize)
                $EnumerationBuffer = [intptr]::Zero
                [uint32]$Count = 0 
                Write-Verbose "Gathering enumerating accounts with user right"               
                $NTStatus = [PoShPrivilege]::LsaEnumerateAccountsWithUserRight(
                    $PolicyHandle,
                    $UserRight,
                    [ref]$EnumerationBuffer,
                    [ref]$Count
                )
                $Accounts = New-Object System.Collections.Arraylist
                If ($NTStatus -eq 0) {
                    $LSAInfo = [intptr]::Zero
                    $StructSize = [System.Runtime.InteropServices.Marshal]::SizeOf([type][LSA_ENUMERATION_INFORMATION])    
                    Write-Debug "StructSize: $($StructSize)"
                    Write-Verbose "Gathering privilege information"
                    For ($i=0; $i -lt $Count; $i++) {
                        Write-Debug "Iteration: $($i)"
                        $EnumerationItem = [intptr]($EnumerationBuffer.ToInt64() + ([long]$StructSize*[long]$i))
                        $Sid = [System.Runtime.InteropServices.Marshal]::PtrToStructure(
                            $EnumerationItem,
                            [type][LSA_ENUMERATION_INFORMATION]
                        )
                        [string]$SIDString = [string]::Empty
                        [void][PoShPrivilege]::ConvertSidToStringSid($Sid.sid, [ref]$SIDString)
                        Try {
                            $Account = ([system.security.principal.securityidentifier]$SIDString).Translate([System.Security.Principal.NTAccount]).Value
                        } Catch {
                            $Account = $SIDString
                        }
                        [void]$Accounts.Add($Account)
                    }
                }  
                $Object = [pscustomobject]@{
                    Computername = $Computername
                    Privilege = $Priv.ToString()
                    Description = GetPrivilegeDisplayName -Privilege $Priv.ToString()
                    Accounts = $Accounts
                }
                $Object.pstypenames.insert(0,'PSPrivilege.Privilege')
                $Object
            }
            #endregion LsaEnumerateAccountsWithUserRight

            #region Close Policy Handle
            Write-Verbose "Closing policy handle"
            [void][PoShPrivilege]::LsaClose($PolicyHandle)
            $PolicyHandle = [intptr]::Zero
            #region Close Policy Handle
        }
    }
}
tools\PoshPrivilege\Scripts\Remove-Privilege.ps1
Function Remove-Privilege {
    <#
        .SYNOPSIS
            Removes a specified privilege for a user or group

        .DESCRIPTION
            Removes a specified privilege for a user or group. This will remain until
            re-added using Add-Privilege or a policy is refreshed.

        .PARAMETER AccountName            
            The user or group which will have the privilege removed.
        
        .PARAMETER Privilege            
            Specific privilege/s to remove from the local machine
        
        .NOTES
            Name: Remove-Privilege
            Author: Boe Prox
            Version History:
                1.0 - Initial Version

        .EXAMPLE
        Remove-Privilege -AccountName Domain\SomeUser -Privilege SeBackupPrivilege

        Description
        -----------
        Removes the SeBackupPrivilege privilege for Domain\SomeUser on the local machine
        
    #>
    [cmdletbinding(
        SupportsShouldProcess = $True
    )]
    Param (
        [parameter(Mandatory=$True)]
        [string]$AccountName,
        [parameter(Mandatory=$True)]
        [Privileges[]]$Privilege
    )
    #No point going through everything if just using -WhatIf
    If ($PSCmdlet.ShouldProcess($AccountName,"Remove Privilege(s): $($Privilege -join ', ')")) {
        #region SID Information
        Write-Verbose "Gathering SID information"
        $AccountSID = ([System.Security.Principal.NTAccount]$AccountName).Translate([System.Security.Principal.SecurityIdentifier])
        $ByteBuffer = New-Object Byte[] -ArgumentList $AccountSID.BinaryLength
        $AccountSID.GetBinaryForm($ByteBuffer,0)
        $SIDPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($AccountSID.BinaryLength)
        [System.Runtime.InteropServices.Marshal]::Copy(
            $ByteBuffer, 
            0, 
            $SIDPtr, 
            $AccountSID.BinaryLength
        )
        #endregion SID Information

        #region LsaOpenPolicy
        $Computer = New-Object LSA_UNICODE_STRING
        $Computer.Buffer = $env:COMPUTERNAME
        $Computer.Length = ($Computer.buffer.length * [System.Text.UnicodeEncoding]::CharSize)
        $Computer.MaximumLength = (($Computer.buffer.length+1) * [System.Text.UnicodeEncoding]::CharSize)
        $PolicyHandle = [intptr]::Zero
        $ObjectAttributes = New-Object LSA_OBJECT_ATTRIBUTES
        [uint32]$Access = [LSA_AccessPolicy]::POLICY_CREATE_ACCOUNT -BOR [LSA_AccessPolicy]::POLICY_LOOKUP_NAMES
        Write-Verbose "Opening policy handle"
        $NTStatus = [PoShPrivilege]::LsaOpenPolicy(
            [ref]$Computer,
            [ref]$ObjectAttributes,
            $Access,
            [ref]$PolicyHandle
        )

        #region winErrorCode
        If ($NTStatus -ne 0) {
            $Win32ErrorCode = [PoShPrivilege]::LsaNtStatusToWinError($return)
            Write-Warning $(New-Object System.ComponentModel.Win32Exception -ArgumentList $Win32ErrorCode)
            BREAK
        }
        #endregion winErrorCode
        #endregion LsaOpenPolicy

        #region LsaAddAccountRights
        ForEach ($Priv in $Privilege) {
            $PrivilegeName = [privileges]::$Priv
            $_UserRights = New-Object LSA_UNICODE_STRING
            $_UserRights.Buffer = $Priv.ToString()
            #SF edts: replaced the two below lines to fix the buffer size
            $_UserRights.Length = ($_UserRights.Buffer.length * [System.Text.UnicodeEncoding]::CharSize)
            $_UserRights.MaximumLength = ($_UserRights.Length + [System.Text.UnicodeEncoding]::CharSize)
            $UserRights = New-Object LSA_UNICODE_STRING[] -ArgumentList 1
            $UserRights[0] = $_UserRights
           Write-Verbose "Removing Privilege: $($PrivilegeName.ToString())"
            $NTStatus = [PoShPrivilege]::LsaRemoveAccountRights(
                $PolicyHandle,
                $SIDPtr,
                $false, #SF edit: originally was true which would delete all privs and the account
                $UserRights,
                1    
            )

            #region winErrorCode
            If ($NTStatus -ne 0) {
                $Win32ErrorCode = [PoShPrivilege]::LsaNtStatusToWinError($return) 
                Write-Warning $(New-Object System.ComponentModel.Win32Exception -ArgumentList $Win32ErrorCode)
                BREAK
            }
        }
        #endregion winErrorCode

        #endregion LsaAddAccountRights

        #region Cleanup
    
        #region Close Policy Handle
        Write-Verbose "Closing policy handle"
        [void][PoShPrivilege]::LsaClose($PolicyHandle)
        #endregion Close Policy Handle

        #region Clear Pointers
        Write-Verbose "Clearing SID pointers"
        [void][System.Runtime.InteropServices.Marshal]::FreeHGlobal($SIDPtr)
        #endregion Clear Pointers

        #endregion Cleanup
    }
}
tools\PoshPrivilege\TypeData\PoShPrivilege.Format.ps1xml
 

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

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

Chocolatey Pro provides runtime protection from possible malware.

Add to Builder Version Downloads Last Updated Status
Win32 OpenSSH (Microsoft Port) 2016.05.30.20160908 24357 Saturday, September 10, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.05.30.20160902 12412 Saturday, September 3, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.05.30.20160827 9023 Saturday, August 27, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.05.30.20160807 6162 Thursday, August 11, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.05.30 12474 Saturday, June 4, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.05.15 617 Wednesday, May 18, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.04.05 115787 Wednesday, April 6, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.03.19 876 Sunday, March 20, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.02.25.20150315 639 Tuesday, March 15, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.02.25.20150310 636 Thursday, March 10, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2016.02.25 729 Sunday, February 28, 2016 Approved
Win32 OpenSSH (Microsoft Port) 2015.12.22 701 Monday, February 15, 2016 Approved
Win32 OpenSSH (Microsoft Port) 0.0.0.9 483 Sunday, September 18, 2016 Approved

Package does not rely on ntrights nor psexec which do not work on Windows Nano. (Still have to eliminate psexec.exe for full compatibility)
Package explicity sets log level to QUIET because on some systems the current version of sshd repeatedly logs the same line at a rate of about 1 GB / 2 hours with default log settings.
Package incorporates securing of the server keys using the SSH agent as per the product release notes below.
Product release notes: https://github.com/PowerShell/Win32-OpenSSH/releases/tag/5_15_2016
https://github.com/PowerShell/Win32-OpenSSH/releases/tag/5_30_2016


This package has no dependencies.

Discussion for the Win32 OpenSSH (Microsoft Port) Package

Ground Rules:

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