Cogger

pki_import.ps1

Feb 22nd, 2023 (edited)
1,107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $ErrorActionPreference = "SilentlyContinue"
  2.  
  3. function ConvertTo-HexString {
  4.     [CmdletBinding()]
  5.     param (
  6.         # Value to convert
  7.         [Parameter(Mandatory=$true, Position = 0, ValueFromPipeline=$true)]
  8.         [object] $InputObjects,
  9.         # Delimiter between Hex pairs
  10.         [Parameter (Mandatory=$false)]
  11.         [string] $Delimiter = ' ',
  12.         # Encoding to use for text strings
  13.         [Parameter (Mandatory=$false)]
  14.         [ValidateSet('Ascii', 'UTF32', 'UTF7', 'UTF8', 'BigEndianUnicode', 'Unicode')]
  15.         [string] $Encoding = 'Default'
  16.     )
  17.  
  18.     begin {
  19.         function Transform ([byte[]]$InputBytes) {
  20.             [string[]] $outHexString = New-Object string[] $InputBytes.Count
  21.             for ($iByte = 0; $iByte -lt $InputBytes.Count; $iByte++) {
  22.                 $outHexString[$iByte] = $InputBytes[$iByte].ToString('X2')
  23.             }
  24.             return $outHexString -join $Delimiter
  25.         }
  26.  
  27.         ## Create list to capture byte stream from piped input.
  28.         [System.Collections.Generic.List[byte]] $listBytes = New-Object System.Collections.Generic.List[byte]
  29.     }
  30.  
  31.     process
  32.     {
  33.         if ($InputObjects -is [byte[]])
  34.         {
  35.             Write-Output (Transform $InputObjects)
  36.         }
  37.         else {
  38.             foreach ($InputObject in $InputObjects) {
  39.                 [byte[]] $InputBytes = $null
  40.                 if ($InputObject -is [byte]) {
  41.                     ## Populate list with byte stream from piped input.
  42.                     if ($listBytes.Count -eq 0) {
  43.                         Write-Verbose 'Creating byte array from byte stream.'
  44.                         Write-Warning ('For better performance when piping a single byte array, use "Write-Output $byteArray -NoEnumerate | {0}".' -f $MyInvocation.MyCommand)
  45.                     }
  46.                     $listBytes.Add($InputObject)
  47.                 }
  48.                 elseif ($InputObject -is [byte[]])
  49.                 {
  50.                     $InputBytes = $InputObject
  51.                 }
  52.                 elseif ($InputObject -is [string])
  53.                 {
  54.                     $InputBytes = [Text.Encoding]::$Encoding.GetBytes($InputObject)
  55.                 }
  56.                 elseif ($InputObject -is [bool] -or $InputObject -is [char] -or $InputObject -is [single] -or $InputObject -is [double] -or $InputObject -is [int16] -or $InputObject -is [int32] -or $InputObject -is [int64] -or $InputObject -is [uint16] -or $InputObject -is [uint32] -or $InputObject -is [uint64])
  57.                 {
  58.                     $InputBytes = [System.BitConverter]::GetBytes($InputObject)
  59.                 }
  60.                 elseif ($InputObject -is [guid])
  61.                 {
  62.                     $InputBytes = $InputObject.ToByteArray()
  63.                 }
  64.                 elseif ($InputObject -is [System.IO.FileSystemInfo])
  65.                 {
  66.                     if ($PSVersionTable.PSVersion -ge [version]'6.0') {
  67.                         $InputBytes = Get-Content $InputObject.FullName -Raw -AsByteStream
  68.                     }
  69.                     else {
  70.                         $InputBytes = Get-Content $InputObject.FullName -Raw -Encoding Byte
  71.                     }
  72.                 }
  73.                 else
  74.                 {
  75.                     ## Non-Terminating Error
  76.                     $Exception = New-Object ArgumentException -ArgumentList ('Cannot convert input of type {0} to Hex string.' -f $InputObject.GetType())
  77.                     Write-Error -Exception $Exception -Category ([System.Management.Automation.ErrorCategory]::ParserError) -CategoryActivity $MyInvocation.MyCommand -ErrorId 'ConvertHexFailureTypeNotSupported' -TargetObject $InputObject
  78.                 }
  79.  
  80.                 if ($null -ne $InputBytes -and $InputBytes.Count -gt 0) {
  81.                     Write-Output (Transform $InputBytes)
  82.                 }
  83.             }
  84.         }
  85.     }
  86.  
  87.     end {
  88.         ## Output captured byte stream from piped input.
  89.         if ($listBytes.Count -gt 0) {
  90.             Write-Output (Transform $listBytes.ToArray())
  91.         }
  92.     }
  93. }
  94.  
  95. #=====[ Load dynamic variables
  96.  
  97. #   Gather Computername
  98.     $ComputerName = $env:COMPUTERNAME
  99.  
  100. #   Gather Username
  101.     $LoggedOnUser = (qwinsta /SERVER:$ComputerName) -replace '\s{2,22}', ',' | ConvertFrom-Csv | Where-Object {$_ -like "*Acti*"} | Select-Object -ExpandProperty USERNAME
  102.     if (!($LoggedOnUser) ) { Write-Host "No user is logged on to $ComputerName" -ForegroundColor Red ; break }
  103.  
  104. #   Gather the Team Members Full Name, instead of First.Last this will read as 'First Last'
  105.     $dom = $env:userdomain
  106.     $usr = $env:username
  107.     $Fullname = ([adsi]"WinNT://$dom/$usr,user").fullname
  108.  
  109. #   Logged in team members document path
  110.     $LoggedPath = "C:\Users\$LoggedOnUser\Documents"
  111.     $OnePath = (Get-ChildItem $LoggedPath -recurse | Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match "OneDrive"}).FullName
  112.    
  113.     $ODPathTest = $1DPath -eq "" -or $1DPath -eq $null
  114.     if($ODPathTest -eq $False){ $1DPath = $OnePath }
  115.     if($ODPathTest -eq  $True){ $1DPath = (Get-ChildItem "C:\Users\$LoggedOnUser" -recurse | Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match "OneDrive - "}).FullName }
  116.  
  117. # OneDrive Service
  118. ##  Get the dynamic service name that we need to check, store as variable.
  119.     $OD_DSync = (Get-Service -Name "OneSyncSvc*" -Exclude "OneSyncSvc").Name
  120. ##  Check the status if the dynamically created service, store as variable.
  121.     $OneDriveService = (get-service $OD_DSync | select Status,Can*).Status
  122. ##  Check with boolean logic to see if the service is running, if it isn't running then we will start the service.
  123.     $ODS_Check = $OneDriveService -eq "Stopped"
  124.     if($ODS_Check -eq $True){ Write-Host("OneDrive is $OneDriveService... Starting Service...") ; Start-Service -Name $OD_DSync }
  125.     if($ODS_Check -eq $False){  Write-Host("OneDrive is $OneDriveService") }
  126.  
  127. #   Using the janked method of encryption, set dynamic team memember specific variable
  128. #   First.Last is store as a variable
  129.     # $CryptCode = $env:username
  130.    
  131. #   Using the janked method of encryption, set dynamic team memember specific variable
  132. #   First.Last is store as a variable
  133. #   Replacement for the lines that come before this
  134.     $CryptCodeRW = whoami /UPN
  135.     $CryptArray = $CryptCodeRW.Split("@")
  136.     $CryptCode = $CryptArray[0]
  137.  
  138. #   Store the first.last variable as an array
  139.     $strArray = $CryptCode.ToCharArray()
  140.  
  141. #   Gather only odd variables from the array
  142.     $strOdd = New-Object System.Collections.ArrayList
  143.     $f=0; $strArray | % { if($f = !$f) { $strOdd.Add("$_") > $null } }
  144.  
  145. #   Gather only even variables from the array
  146.     $strEvn = New-Object System.Collections.ArrayList
  147.     $f=1; $strArray | % { if($f = !$f) { $strEvn.Add("$_") > $null } }
  148.  
  149. #   Split Odd variables from name array to its own array
  150.     $strOdd = $strOdd -replace '(^\s+|\s+$)','' -replace '\s+',' '
  151.     $strOdd = [string]::join("",($strOdd.Split("`n")))
  152.  
  153. #   Split even variables from name array to its own array
  154.     $strEvn = $strEvn -replace '(^\s+|\s+$)','' -replace '\s+',' '
  155.     $strEvn = [string]::join("",($strEvn.Split("`n")))
  156.  
  157. #   Combine Odd and Even variables together to set the first stage of this cipher
  158.     $e_ehx = $strOdd + $strEvn
  159.  
  160. #   Setting the second stage of this cipher, convert the first stage into a hexadecimal.
  161.     $hexconv = ConvertTo-HexString $e_ehx
  162.  
  163. #   Set the final stage of this cipher from hexadecimal to a secure string
  164. ##  Each character in an individuals name will increase the length by 16 characters.
  165. ##  Example. There are 436 characters for a 13 character name
  166. ##  Example. There are 468 characters for a 15 character name
  167.     $pfxEncrypt_Key = $hexconv | ConvertTo-SecureString -AsPlainText -Force
  168.  
  169. #   Create variable for the location of the OneDrive PKI.
  170.     $SaveState = $1DPath + "\" + $env:username + "_PKI.pfx"
  171. #   Test to see if the PKI exists, if it does not it will warn the technician.
  172.     $Leaf_SaveState = [bool]( Test-Path -Path $SaveState -PathType Leaf )
  173.     if($Leaf_SaveState -eq  $True){ Import-PfxCertificate -Exportable -FilePath $SaveState -CertStoreLocation Cert:\CurrentUser\My -Password $pfxEncrypt_Key }
  174.     if($Leaf_SaveState -eq $False){ Add-Type -AssemblyName System.Speech
  175.         $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer
  176.         $speak.SelectVoice('Microsoft Zira Desktop')
  177.         $speak.Speak('Warning. PKI is missing.')
  178.         $speak.Speak('Please perform the steps required to obtain a new PKI')
  179.         New-Item "$env:USERPROFILE\Desktop\Warning. PKI is missing.log" }
  180.  
  181.  
  182. exit
  183.  
Tags: powershell
Advertisement
Add Comment
Please, Sign In to add comment