PowerShell: Allow Log On To Remote Desktop Service

# editWindowsSecurity.ps1
# Version 0.0.1
# Notes:
# - This has NOT been thoroughly tested. Microsoft Windows version variances may render this script ineffective
# - need to add a routine to translate SID into principle name as part of the matching sequence
#
# WARNING: Do Not Use Mis-use This as It Can Brick Your Windows!
# No implied or express warranties shall be assumed. Caveat Emptor!


function editWindowsSecurity{
  param(
    $principle="Remote Desktop Users",
    $privilege="SeRemoteInteractiveLogonRight",
    $operation='add' # or 'remove'
  )

  $originalSecurity='C:\originalSecurity.inf'
  $newSecurity='C:\newSecurity.inf'
  $originalDb='c:\windows\security\database\secedit.sdb'
  $securityDb='C:\originalSecurity.sdb'
  $log='C:\security.log'

  try{
    $null=get-process mmc -ea Ignore|stop-process
    cp $originalDb $securityDb -ea Stop
  }catch{
    write-warning $_
    return $false
  }
  #secedit /export /db $securityDb /mergedpolicy /cfg $originalSecurity /log $log /quiet

  $null=secedit /export /areas USER_RIGHTS /cfg $originalSecurity
  $null="[Unicode]`r`nUnicode=yes`r`n`r`n[Version]`r`nsignature=`"`$CHICAGO`$`"`r`nrevision=1`r`n`r`n[Privilege Rights]"|Out-File $newSecurity -Force -WhatIf:$false 
  $originalRights=Get-Content $originalSecurity
  $applyChanges=$false

  if($operation -eq 'add'){
    write-host "Adding $principle to $privilege..."
    foreach($line in $originalRights){ 
        if($line -like "$privilege`*"){
            write-host "Before: $line"
            $line=$line+",$principle"
            write-host "After: $line"
            $line|Out-File $newSecurity -Append -WhatIf:$false
            $applyChanges=$true
        }
    }
  }elseif($operation -eq 'remove'){
    write-host "Removing $principle from $privilege..."
    $security=$originalRights|?{$_ -match "^$privilege"}
    if($security){
      $list=[regex]::match($security,'=\s(.*)').captures.groups[1].value
      $newList=($list -split ','|?{$_ -notmatch "$principle"}) -join ','
      $line="$privilege = $newList"
      if($line -ne $security){
        write-host "Before: $security`r`nAfter:$line"
        $line|Out-File $newSecurity -Append -WhatIf:$false
        $applyChanges=$true
      }else{
        write-host "No changes."
      }
    }
  }else{
    write-warning "Please specify operation type as either ADD or REMOVE"
  }

  if($applyChanges){
    try{
      $output=SECEDIT /configure /db $securityDb /cfg $newSecurity /log $log
      write-host $output
    }catch{
      write-warning $_
      return $false
    }    
  }  
  #Remove-Item $originalSecurity -Force -WhatIf:$false
  #Remove-Item $newSecurity -Force -WhatIf:$false
}

Leave a Reply

Your email address will not be published. Required fields are marked *