Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $ErrorActionPreference = "SilentlyContinue"
- # Of the 312 lines contained within this script, 66 are comments to explain, and 47 are empty lines. Meaning that only 199 lines are performing impertive operations.
- function ConvertTo-HexString {
- [CmdletBinding()]
- param (
- # Value to convert
- [Parameter(Mandatory=$true, Position = 0, ValueFromPipeline=$true)]
- [object] $InputObjects,
- # Delimiter between Hex pairs
- [Parameter (Mandatory=$false)]
- [string] $Delimiter = ' ',
- # Encoding to use for text strings
- [Parameter (Mandatory=$false)]
- [ValidateSet('Ascii', 'UTF32', 'UTF7', 'UTF8', 'BigEndianUnicode', 'Unicode')]
- [string] $Encoding = 'Default'
- )
- begin {
- function Transform ([byte[]]$InputBytes) {
- [string[]] $outHexString = New-Object string[] $InputBytes.Count
- for ($iByte = 0; $iByte -lt $InputBytes.Count; $iByte++) {
- $outHexString[$iByte] = $InputBytes[$iByte].ToString('X2')
- }
- return $outHexString -join $Delimiter
- }
- ## Create list to capture byte stream from piped input.
- [System.Collections.Generic.List[byte]] $listBytes = New-Object System.Collections.Generic.List[byte]
- }
- process
- {
- if ($InputObjects -is [byte[]])
- {
- Write-Output (Transform $InputObjects)
- }
- else {
- foreach ($InputObject in $InputObjects) {
- [byte[]] $InputBytes = $null
- if ($InputObject -is [byte]) {
- ## Populate list with byte stream from piped input.
- if ($listBytes.Count -eq 0) {
- Write-Verbose 'Creating byte array from byte stream.'
- Write-Warning ('For better performance when piping a single byte array, use "Write-Output $byteArray -NoEnumerate | {0}".' -f $MyInvocation.MyCommand)
- }
- $listBytes.Add($InputObject)
- }
- elseif ($InputObject -is [byte[]])
- {
- $InputBytes = $InputObject
- }
- elseif ($InputObject -is [string])
- {
- $InputBytes = [Text.Encoding]::$Encoding.GetBytes($InputObject)
- }
- 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])
- {
- $InputBytes = [System.BitConverter]::GetBytes($InputObject)
- }
- elseif ($InputObject -is [guid])
- {
- $InputBytes = $InputObject.ToByteArray()
- }
- elseif ($InputObject -is [System.IO.FileSystemInfo])
- {
- if ($PSVersionTable.PSVersion -ge [version]'6.0') {
- $InputBytes = Get-Content $InputObject.FullName -Raw -AsByteStream
- }
- else {
- $InputBytes = Get-Content $InputObject.FullName -Raw -Encoding Byte
- }
- }
- else
- {
- ## Non-Terminating Error
- $Exception = New-Object ArgumentException -ArgumentList ('Cannot convert input of type {0} to Hex string.' -f $InputObject.GetType())
- Write-Error -Exception $Exception -Category ([System.Management.Automation.ErrorCategory]::ParserError) -CategoryActivity $MyInvocation.MyCommand -ErrorId 'ConvertHexFailureTypeNotSupported' -TargetObject $InputObject
- }
- if ($null -ne $InputBytes -and $InputBytes.Count -gt 0) {
- Write-Output (Transform $InputBytes)
- }
- }
- }
- }
- end {
- ## Output captured byte stream from piped input.
- if ($listBytes.Count -gt 0) {
- Write-Output (Transform $listBytes.ToArray())
- }
- }
- }
- #=====[ Load dynamic variables
- # Gather Computername
- $ComputerName = $env:COMPUTERNAME
- # Gather Username
- $LoggedOnUser = (qwinsta /SERVER:$ComputerName) -replace '\s{2,22}', ',' | ConvertFrom-Csv | Where-Object {$_ -like "*Acti*"} | Select-Object -ExpandProperty USERNAME
- if (!($LoggedOnUser) ) { Write-Host "No user is logged on to $ComputerName" -ForegroundColor Red ; break }
- # Gather the Team Members Full Name, instead of First.Last this will read as 'First Last'
- $dom = $env:userdomain
- $usr = $env:username
- $Fullname = ([adsi]"WinNT://$dom/$usr,user").fullname
- # Logged in team members document path
- $LoggedPath = "C:\Users\$LoggedOnUser\Documents"
- $OnePath = (Get-ChildItem $LoggedPath -recurse | Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match "OneDrive"}).FullName
- $ODPathTest = $1DPath -eq "" -or $1DPath -eq $null
- if($ODPathTest -eq $False){ $1DPath = $LoggedPath + "\" + $OnePath }
- if($ODPathTest -eq $True){ $1DPath = (Get-ChildItem "C:\Users\$LoggedOnUser" -recurse | Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match "OneDrive - "}).FullName }
- # OneDrive Service
- ## Get the dynamic service name that we need to check, store as variable.
- $OD_DSync = (Get-Service -Name "OneSyncSvc*" -Exclude "OneSyncSvc").Name
- ## Check the status if the dynamically created service, store as variable.
- $OneDriveService = (get-service $OD_DSync | select Status,Can*).Status
- ## Check with boolean logic to see if the service is running, if it isn't running then we will start the service.
- $ODS_Check = $OneDriveService -eq "Stopped"
- if($ODS_Check -eq $True){ Write-Host("OneDrive is $OneDriveService... Starting Service...") ; Start-Service -Name $OD_DSync }
- if($ODS_Check -eq $False){ Write-Host("OneDrive is $OneDriveService") }
- #=====[ Outlook encryption certification
- # Define these variables as null si that we can use them to place dynamic data into
- $ExportThumb = $null ; $ExportPath = $null
- # Set variable for the the UserDS Path within Certificates
- $UserDS_Path = "Microsoft.PowerShell.Security\Certificate::CurrentUser\UserDS"
- # Create array within our defined above variable, but only include certificates that come from our London Certificate Authority
- $UserDS_arr = get-childitem -Path $UserDS_Path -recurse | Where {$_.Issuer -like "CN=ERMLondonIssuingCA"}
- # Take the count of the number of items within the array, but define this as integer not a string
- $UserDS_Count = [float]$UserDS_arr.count
- # Set variable for the the MyCerts Path within Certificates
- $MyCert_Path = "Microsoft.PowerShell.Security\Certificate::CurrentUser\My"
- # Create array within our defined above variable, but only include certificates that come from our London Certificate Authority
- $MyCert_arr = get-childitem -Path $MyCert_Path -recurse | Where {$_.Issuer -like "CN=ERMLondonIssuingCA"}
- # Take the count of the number of items within the array, but define this as integer not a string
- $MyCert_Count = [float]$MyCert_arr.count
- # Add the total number of possible indicies so that we can ensure that the loop does not repeat forever
- $cerIndexCap = $UserDS_Count + $MyCert_Count + 1
- # Create an integer set to zero, so that we can loop the do-until for all possible indicies
- $i = 0;
- # Create array that we will use to check to see the team member has multiple certificates -- and to find the newest if this applies
- [collections.arraylist]$MultiCertArr = @()
- # Until we reach the total number of indicies, continue this loop
- Do {
- # For each item contained within the UserDS Path
- foreach ($Thumb_DS in $UserDS_arr) {
- # Find the the Cert has an exportable key
- # If the key is not exportable then this value is false then the indicies does not get added to the possible list of items to select from.
- $IsExportable = ((((get-childitem -Path $UserDS_Path -recurse | Where {$_.Thumbprint -eq $Thumb_DS.Thumbprint}).psobject.properties).Value).CspKeyContainerInfo).Exportable
- # If the key is exportable then collect its thumbprint, collect its Cert path, add these to the a query variable, and then add that query variable to our
- # multicert array.
- if($IsExportable -eq $True){
- $ExportThumb = $Thumb_DS.Thumbprint;
- $ExportPath = $UserDS_Path;
- $PKIcert = get-childitem -Path $ExportPath -recurse | Where {$_.Thumbprint -eq $ExportThumb};
- $MultiCertArr.Add($PKIcert) > $null }
- $i++
- }
- foreach ($Thumb_MY in $MyCert_arr) {
- # Find the the Cert has an exportable key
- # If the key is not exportable then this value is false then the indicies does not get added to the possible list of items to select from.
- $IsExportable = ((((get-childitem -Path $MyCert_Path -recurse | Where {$_.Thumbprint -eq $Thumb_MY.Thumbprint}).psobject.properties).Value).CspKeyContainerInfo).Exportable
- # If the key is exportable then collect its thumbprint, collect its Cert path, add these to the a query variable, and then add that query variable to our
- # multicert array.
- if($IsExportable -eq $True){
- $ExportThumb = $Thumb_MY.Thumbprint;
- $ExportPath = $MyCert_Path;
- $PKIcert = get-childitem -Path $ExportPath -recurse | Where {$_.Thumbprint -eq $ExportThumb};
- $MultiCertArr.Add($PKIcert) > $null }
- # increase the index variable by 1
- $i++
- }
- } Until ( $i -ge $cerIndexCap );
- # if multi cert array contains only a single indicies then we will use that to export the pki
- if( [float]$MultiCertArr.count -eq 1 ){ $PFXcert = $PKIcert }
- # if multi cert array contains
- if( [float]$MultiCertArr.count -eq 0 ){ Write-Host("No certificate found exportable or not") }
- # if multi cert array contains
- if( [float]$MultiCertArr.count -gt 1 ){ Write-Host("Multiple certs possible within standard criteria...retrieving the newest version of the certificate...")
- [collections.arraylist]$oldestDate = @()
- foreach ($divCert in $MultiCertArr) {
- $lateDate = ($divCert).NotAfter.ToString("yyyy")
- $oldestDate.Add($lateDate) > $null
- }
- $moTime = ($oldestDate | measure -Maximum).Maximum
- foreach ($divCert in $MultiCertArr) { $lateDate = ($divCert).NotAfter.ToString("yyyy") ; if ($lateDate -eq $moTime) { $PFXcert = $divCert } }
- }
- $PFXThumb = $PFXcert.Thumbprint
- # Using the janked method of encryption, set dynamic team memember specific variable
- # First.Last is store as a variable
- $CryptCode = $env:username
- # Store the first.last variable as an array
- $strArray = $CryptCode.ToCharArray()
- # Gather only odd variables from the array
- $strOdd = New-Object System.Collections.ArrayList
- $f=0; $strArray | % { if($f = !$f) { $strOdd.Add("$_") > $null } }
- # Gather only even variables from the array
- $strEvn = New-Object System.Collections.ArrayList
- $f=1; $strArray | % { if($f = !$f) { $strEvn.Add("$_") > $null } }
- # Split Odd variables from name array to its own array
- $strOdd = $strOdd -replace '(^\s+|\s+$)','' -replace '\s+',' '
- $strOdd = [string]::join("",($strOdd.Split("`n")))
- # Split even variables from name array to its own array
- $strEvn = $strEvn -replace '(^\s+|\s+$)','' -replace '\s+',' '
- $strEvn = [string]::join("",($strEvn.Split("`n")))
- # Combine Odd and Even variables together to set the first stage of this cipher
- $e_ehx = $strOdd + $strEvn
- # Setting the second stage of this cipher, convert the first stage into a hexadecimal.
- $hexconv = ConvertTo-HexString $e_ehx
- # Set the final stage of this cipher from hexadecimal to a secure string
- ## Each character in an individuals name will increase the length by 16 characters.
- ## Example. There are 436 characters for a 13 character name
- ## Example. There are 468 characters for a 15 character name
- $pfxEncrypt_Key = $hexconv | ConvertTo-SecureString -AsPlainText -Force
- # Script to execute a seperate PowerShell instance
- $scriptBlock = {
- Start-Sleep -Milliseconds 2500
- $title = 'Exporting your private exchange key'
- $SecWar = (Get-Process | Where-Object {$_.MainWindowTitle -eq $title}).MainWindowTitle;
- $SecWarBoo = [bool]($SecWar -eq $null);
- Do {
- $secWarID = (Get-Process | Where-Object {$_.MainWindowTitle -eq $title}).Id ; sleep 1;
- $wshell = New-Object -ComObject wscript.shell;
- $wshell.AppActivate($title) ; sleep -Milliseconds 100;
- $wshell.SendKeys('~') ; sleep -Milliseconds 3700;
- $SecWar = (Get-Process | Where-Object {$_.MainWindowTitle -eq $title}).MainWindowTitle;
- $SecWarBoo = [bool]($SecWar -eq $null);
- } Until ($SecWarBoo -eq $True);
- }
- $SaveState = $1DPath + "\" + $env:username + "_PKI.pfx"
- # If the export already exists...then inform the script runner... and then stop the script.
- if((Test-Path -Path $SaveState -PathType Leaf) -eq $false){
- # New Method
- # Attempt to try the first method of exporting the PKI
- Try{
- # First method of exporting
- # Certificate - cert:\currentuser\my
- $PFXcert | Export-PfxCertificate -FilePath $SaveState -Password $pfxEncrypt_Key
- Start-Sleep -s 4
- Write-Host("PKI exported successfully! Opening contained directory for confirmation.")
- Explorer.exe $1DPath
- } catch {
- # If the first method fails -- then we will attempt the second which requires a second script to be run to click through all relevant steps.
- Try{
- # Start a new instance of Windows PowerShell and run the script
- $powershellPath = "$env:windir\system32\windowspowershell\v1.0\powershell.exe"
- $process = Start-Process $powershellPath -NoNewWindow -ArgumentList ("-ExecutionPolicy Bypass -noninteractive -noprofile " + $scriptBlock) -PassThru
- $process.WaitForExit($waitTimeMilliseconds)
- # Second method of exporting the pki key
- certutil -user -p $pfxEncrypt_Key -exportpfx $PFXThumb $SaveState > $null
- Start-Sleep -Milliseconds 500
- Clear-Host
- Write-Host("PKI exported successfully! Opening contained directory for confirmation.")
- Explorer.exe $1DPath
- } catch {
- # Export failed -- write an error log, and write output
- Clear-Host
- $SaveState = $1DPath + "\IMPORT_PKI_FAILED.log" ; New-Item $SaveState
- Write-Host("Export failed -- log written to OneDrive. Please attempt manual export operation diticated within process.")
- }
- }
- } else {
- # File exists...halt
- Clear-Host
- Write-Host("Cannot create export of $env:username as $SaveState already exists..halting script")
- }
- sleep -seconds 3
- exit
Add Comment
Please, Sign In to add comment