Skip to content

Instantly share code, notes, and snippets.

@stnguyen90
Created December 20, 2021 17:48
Show Gist options
  • Save stnguyen90/98ef44fa5e08deda07c9e879574a5da5 to your computer and use it in GitHub Desktop.
Save stnguyen90/98ef44fa5e08deda07c9e879574a5da5 to your computer and use it in GitHub Desktop.
Apache Log4j2 Remote Code Execution (RCE) Vulnerability - CVE-2021-44228 - ESA-2021-31 emergency patch script for Windows
#
# Copied and tweaked from https://gist.github.com/neoKushan/e156810fc91765aa84857314b92bb22d to add
# backing up of jar
#
# To run it, ensure your execution policy is set correctly, paste the file anywhere you want it to check for
# log4j (This will check subfolders) and just call Remove-JndiLookup from your favourite powershell window.
#
# Note that the script isn't especially clever, running it on your machine doesn't guarantee that you're no longer
# vulnerable to log4shell, just that JndiLookup.class has been removed from any found instance of log4j-core-2.*.jar
#
# Zero warranty is provided, you use this entirely at your own risk.
#
function Remove-JndiLookup
{
Param
(
[string[]]$JarFiles,
[string] $FilenameToRemove
)
# Instantiate the .Net namespace
add-type -AssemblyName 'System.IO.Compression.filesystem'
"The number of files to be processed is: $($JarFiles.Count) -"
# List the files we're about to process, useful if the user wants to double check
# them later
foreach ($JarFile in $JarFiles)
{
"$JarFile"
}
"`nStarting patching/removal process"
$processedFiles = 0;
$skippedFiles = 0;
# Remove unwanted files
foreach ($JarFile in $JarFiles)
{
"`nBacking up $JarFile"
cp "$JarFile" "$JarFile.bak"
# Open the jar for updating (.jar files are just .zip files)
$ProcessJarFile = [io.compression.zipfile]::Open($JarFile,'Update')
"`Checking $JarFile for $FilenameToRemove"
$totalFilesInJar = ($ProcessJarFile.Entries | Where FullName -Match $FilenameToRemove).Count
if($totalFilesInJar -gt 0) {
"Deleting unwanted file $FilenameToRemove from $JarFile"
($ProcessJarFile.Entries | Where FullName -Match $FilenameToRemove).Delete()
$processedFiles++
}
else {
"File $FilenameToRemove not found inside $JarFile, this may have already been deleted."
$skippedFiles++
}
# Clean up / close the zip
$ProcessJarFile.Dispose()
}
"`n$processedFiles file(s) processed`n$skippedFiles file(s) skipped`n`nFinished."
}
(Get-ChildItem -Recurse -Path (Get-Location) -Filter 'log4j-core-2.*.jar' -File).FullName
Remove-JndiLookup -JarFiles (Get-ChildItem -Recurse -Path (Get-Location) -Filter 'log4j-core-2.*.jar' -File).FullName -FilenameToRemove 'JndiLookup.class'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment