r/PowerShell • u/Strex_1234 • Mar 16 '24
How to write a script that will delete itself (without possibility of recovery)
I want to create deployment script that will install all things i need and then deletes itself. The problem is that it should be unrecoverable, i thought about editing file and overwrite it but is there a better way?
2
u/touch_my_urgot_belly Mar 16 '24
You can delete the script at runtime using Remove-Item. This can be done at the end of the script itself. No need for a scheduled task
however "without possibility of recovery" is just straight up impossible if you don't secure erase the device it is stored on
0
u/Strex_1234 Mar 16 '24
Arent there apllication that do exactly that (not whole drive but the space where file is located), I thought i could overwrite the script file with zeros which should work
2
u/ovdeathiam Mar 16 '24 edited Mar 16 '24
You can do exactly that using System.IO.Streamer. The question is whether writing zeroes across the file will make it unrecoverable. In case of a hard drive and proper forensic hardware you can recover a file for a hard drive which was zeroed in one pass. It's however extremely unlikely in case of a raid and impossible in case of an SSD (unless trimming is not in place). It will act differently if you're accessing the script through local ntfs, fat32, new fat, or an smb share which is hosted on Linux. You have also a different behavior in case of VMs. What about VSS/Shadow Copy? Is that in place? If so you need to be sure that is off. What about any other third party tool?
Long story short, you need to know your environment. If you don't and want to cover all grounds, then you want an expert and such services aren't free and take time.
If you're not a script kiddie who tries to make a malicious script and cover his tracks then removing a file is sufficient. In most scenarios your user doesn't have access nor knowledge to do any kinds of recovery. If you assume they do then there's laws in place. You can use NDAs and user agreements. If you can't use those then you're most likely breaking the law yourself.
18
u/-c-row Mar 16 '24
Invoke it from Web without saving it on the disk and clean the history after execution.
Else run the script which also creates a scheduled task and the task removes the script finally.
3
Mar 16 '24
[removed] — view removed comment
8
u/-c-row Mar 16 '24
I use something similar daily and host my scripts and modules on a webserver in Azure which serves the powershell files as plain text. Works like a charm for me and makes it easy to operate on our customers systems with my own functions and modules without the need to install, update or maintain them.
2
u/socksonachicken Mar 16 '24
I use it also and every once in a while Defender will get grumpy about it. Works wonderfully though.
0
u/Nu11u5 Mar 16 '24
If you are concerned about injection in-transit or destination hijacking, using SSL resolves this.
16
u/jpbras Mar 16 '24 edited Mar 16 '24
State your objective, not the way you want to follow.
"script that will delete itself" or even "script" is what you think is the right way, "license key that i should not leave on computer" is the objective.
2. Know your environment,
I assume the computers are not yours and you can't control folder permissions and who is administrators, as if so, you don't need all this.
3. Test your hypothesis
a) If you think someone would go the extra mile to recover the file, let me tell you the easiest way was to create a DENY permission to DELETE, and so the script would not be deleted.
b) Where the script will rest, or exists, before it is executed? The script will be readable and on plain sight? Why deleted it if someone can just read it before execution?
edit: c and d where written in 4. consider alternatives, but makes more sense to be here.
c) any administrator that really wants can get that license key depending on how the license is used.
Parameter in the command line (like an msi or executable?) you can protect the license (see below inno setup example) but the administrator running procmon will see how you called the application and see the license.
d) Even if you use diskless license (getting it from the net) when you use it, running procmon any administrator will see the license when the command line is executed.
4. consider alternatives
controlled environment: script on protected folder
edit: changed paragraph order
non-controlled environment: I imagine it is a retail application, so you can't change the way the license is applied, so... if you install the application with a pen, I assume you are some kind of small MSP...
It's a viable option to request the computer name from the customer, create a inno setup installer, that checks in the pascal code, if it's running in the expected computer and procmon process is not running, and only then installs the application with the license? Other way it just exists.
Inno Setup encrypted executable. Is easy, very very easy to create a inno setup script and compile it. You can write the command to install the application and the license in the section pascal code and even with the tools to extract information from the executable, the code is a bin file.
Last advice: Deleting anything from the computer that you just executed sounds suspicious and for traceability it shouldn't be done. You can download a installer from the internet, it executes, extracts something to the temp folder and in the end it deletes the files in the temp folder, not the installer on the downloads folder. Other way is very suspicious right? So don't do this to others.
That should help you (edit: getting some base you can improve :-)).
1
u/steviefaux Mar 16 '24
Maybe a script that also creates another script file. The first one deletes itself. The job of the 2nd script file is to create a file with the same name as the last and then delete it.
So my thinking is, if they restore it, they only get the 2nd copy.
-1
u/Strex_1234 Mar 16 '24
Well my idea is to make the seconds script and overwrite all characters from first script. The new file doesn't have to be created in the same space so im not sure if it was 100% removed
1
u/steviefaux Mar 16 '24
Old and might not be valid anymore but I think if a file with the same name as the originally deleted then gets deleted. It overwrites the space where the original was.
3
u/Certain-Community438 Mar 16 '24
This is definitely a case of x:y problem.
If the actual objective is "protect license key", the solution involves storing it outside the script.
In a MSFT environment, one option would be Azure Key Vault, since you can control access to each secret using Entra ID accounts.
The script would connect to Azure, fetch the license key, then carry on.
That said, I'm not 100% sure the license key couldn't later be recovered from one or more local logs, such as Windows Installer events. But if this is a problem at all, it affects all methods, including the current USB approach.
5
u/BlackV Mar 16 '24
But why ? You are straight up wasting your time,What are you gaining, the chance of anyone trying to undelete or recover a script you deleted (with a normal delete) is so close to 0
I'd suggest, Dont store the the script on disk in the first place (i.e. store it on a network share)
You could look at a tool called sdelete, I don't know of it's still around
4
Mar 16 '24
I read the title and instantly thought "is this dude writing a virus?"
2
u/BlackV Mar 17 '24
That's what figured too
that or they don't want people to steal "their code" (And just wait till the learn about script block logging)
They mentioned licensed in another comment but you'd deleting the license file not the code
2
u/doglar_666 Mar 16 '24
Can you not host the license in a separate file on a restricted admin share? And just call the license from the share with Get-Content to populate a variable? That way it's never written to disk and a non-admin can't access it, even with the script being left on the client?
2
u/kigoh Mar 16 '24
Scheduled task has a RunOnce parameter that will make it remove itself. Else there is a registry path for the same functionality.
2
u/m_anas Mar 16 '24
You know any powershell script runs on the machine is recorded in the event log "Windows PowerShell"
So, a determined user with rights can go back, review the log, and get the script code.
Your best option is to use the "secret management" module or obfuscation.
2
u/neilkilroy Mar 16 '24
Hmmm this sounds very hacky hmmm Mr Robot comes to mind . Who are you hacking lol
1
u/sandeepverma372 Mar 16 '24
Use Azure Automation to host your script and configure all the machines as hybrid worker role. At schedule or on an ad hoc basis you can execute the sensitive scrip and there is no need to save the PS1 on the local machine.
1
u/EmersonNavarro Mar 16 '24
I would make the script create an scheduled task to delete the script after x minutes.
1
u/illsk1lls Mar 16 '24
There is an easy way to self delete in CMD scripts, the file doesnt go the the recycle bin but I’m sure you could use data recovery on the disk to recover it
youre gonna have to scramble the contents before deleting if you dont want it to be recovered OR use something like memorystream to DL and execute it without ever writing the file
1
Mar 16 '24
Make the last thing your script does open a new instance of PowerShell that waits a few seconds then deletes the script.
Start-Process PowerShell -Command "Start-Sleep -Seconds 10; Remove-Item path.ps1 -Force" or something
I guess if you worked on it you couid pass the path of the script itself to that new instance so it works from any location
1
u/The82Ghost Mar 16 '24
Store your licensekeys in a protected database and read them from there on runtime.
1
u/chiefplato Mar 16 '24
What about an ansible playbook from a remote host with the final step is history -c
1
u/cosmic_cosmosis Mar 17 '24
# Get the path of the currently running script
$scriptPath = $MyInvocation.MyCommand.Path
# Delete the script file
Remove-Item -Path $scriptPath -Force1
u/ankokudaishogun Mar 18 '24
The roughest way i can think is:
Put your sensible data in a file separated from the script.
Once the installation is completed, have the script overwrite the sensible data file N times until you are satisfied. Then you can delete it (or not, the data has been wiped out anyway)
1
u/MouseboyFPGA Mar 18 '24 edited Mar 18 '24
From what you mentioned in the thread:
Some of the Apps needs an License key that should not be left in the computer
currently you are launching the script from a pendrive
If you had the option to permanently delete the script without the possibility of recovery you could run everything concurrently
So a few things here - I'm sure you realise, as others have commented, this is not the most optimal way to perform your deployment.
If you have to work to the parameters above, you could perhaps write the Licence keys to the registry on the device in either plain text or a 'pseudo encrypted' form. Your script could then query the local registry and convert the obfuscated Licence key to a useable Licence key. You can then delete the registry key. If someone finds your script, it makes no odds as the registry key containing the licence key is deleted. Furthermore, they're in an obfuscated form making it doubly useless.
There are no doubt better / more optimal ways to do what I've mentioned, but here's a script to my capabilities
# OriginalKey1 = 12345-abcde-VWXYZ
# OriginalKey2 = 9aBzz_rrTVBS_h!_9
#### Script 1 (run from USB stick)
New-Item –Path HKCU: –Name TempKey -Force | Out-Null
New-ItemProperty -Path HKCU:\TempKey -Name "LicenceKey1" -Value "456780defgh0YZ[\]" -PropertyType "String" | Out-Null
New-ItemProperty -Path HKCU:\TempKey -Name "LicenceKey2" -Value "<dE}}buuWYEVbk!b<" -PropertyType "String" | Out-Null
#### Script 2 (run from Local Computer)
# Grab the 'encrypted' Licence Keys from the local Registry
$LicenceKeys = @(
[PSCustomObject]@{Name = "LicenceKey1" ; Value = (Get-ItemProperty –Path HKCU:\TempKey -Name LicenceKey1).LicenceKey1}
[PSCustomObject]@{Name = "LicenceKey2" ; Value = (Get-ItemProperty –Path HKCU:\TempKey -Name LicenceKey2).LicenceKey2}
)
$LicenceKeysNew = New-Object System.Collections.ArrayList
$CommonCharsASCIINumbers = (45..126) # All the characters your licence key is likely to have
$ShuffleForwardCharacters = 3 # How many characters to shift forward, i.e. if shifted forward 6 'a' becomes 'g', '4' bcomes '10', and so on
# Change this to a minus number to shift backwards. Useful to 'reverse engineer' the code yourself
$FirstChar = ($CommonCharsASCIINumbers | Select-Object -First 1)
$LastChar = ($CommonCharsASCIINumbers | Select-Object -Last 1)
# Loop through each Licence Key
ForEach ($LicenceKey in $LicenceKeys) {
$LicenceKeyTemp = New-Object System.Collections.ArrayList
$ModifiedLicenceKey = New-Object System.Collections.ArrayList
# For the Value, shift forward the number of characters mentioned
$LicenceKey.Value -Split "" | Where-Object {$_} |
ForEach-Object {
$CurrentByteChar = [Byte][Char]$_
$ShiftedByteChar = ($CurrentByteChar - $ShuffleForwardCharacters) % $LastChar
If ($CurrentByteChar -gt $LastChar) {$ShiftedByChar = $ShiftedByChar + $FirstChar}
If ($CurrentByteChar -in $CommonCharsASCIINumbers) {[Void]$LicenceKeyTemp.Add([Char]$ShiftedByteChar)} Else {[Void]$LicenceKeyTemp.Add([Char]$CurrentByteChar)}
}
# Set the modified Key Value as a Custom Object
$ModifiedLicenceKey = [PSCustomObject]@{Name = $LicenceKey.Name ; Value = ($LicenceKeyTemp -Join "")}
# Add the Custom Object to the Array
[Void]$LicenceKeysNew.Add($ModifiedLicenceKey)
}
# Remove the regisry Key
Remove-Item –Path HKCU:\TempKey -Force | Out-Null
# Here are the Licence Keys in Memory only
$LicenceKeysNew
0
u/Robba078 Mar 16 '24
Make an overatching script , that first call the sensitieve info script, and after its done, delete the sensitieve info script
0
u/Strex_1234 Mar 16 '24
The problem is that you can use program to recover it
1
u/Robba078 Mar 16 '24
Remove-item -force allows for recovery? I normallu also put these files in env:temp path
-2
6
2
u/psichodrome Mar 16 '24
I was gonna say just use -remove or similar to get rid of itself. Clearly not gonna work.
But i'm more curious about your use case?