Jump to content

_IsUPX() - Checks if a supported file is UPX'd.


guinness
 Share

Recommended Posts

Two very quick Functions I came up with in 5 minutes to check if a file has been upx'ed. This is accomplished by reading the file or using the parameter "-t" and upx.exe. Any problems, suggestions then post below. Thanks.

Function:

; #FUNCTION# ====================================================================================================================
; Name ..........: _IsUPX
; Description ...: Checks if a supported file is UPX'd.
; Syntax ........: _IsUPX($sFilePath[, $sUPX = 'upx.exe'])
; Parameters ....: $sFilePath           - File path of the file to check, this must be supported by UPX.
; Return values .: Success - 1 or 0 if the file is UPX'd
;                   Failure - None
; Author ........: guinness & MrCreatoR
; Example .......: No
; ===============================================================================================================================
Func _IsUPX($sFilePath)
    Local Const $bStart_Address = 0x001F0, $iUPX_Header_Length = 30
    Local $hFileOpen = FileOpen($sFilePath, 0)
    If $hFileOpen = -1 Then
        Return SetError(1, 0, -1)
    EndIf
    FileSetPos($hFileOpen, $bStart_Address, 0)
    Local $sData = FileRead($hFileOpen, $iUPX_Header_Length)
    FileClose($hFileOpen)
    Return Number(StringInStr($sData, 'UPX') > 0)
EndFunc   ;==>_IsUPX

Function with UPX required:

; #FUNCTION# ====================================================================================================================
; Name ..........: _IsUPX
; Description ...: Checks if a supported file is UPX'd.
; Syntax ........: _IsUPX($sFilePath[, $sUPX = 'upx.exe'])
; Parameters ....: $sFilePath           - File path of the file to check, this must be supported by UPX.
;                  $sDirectory          - [optional] Location of the UPX executable. Default is @ScriptDir.
; Return values .: Success - 1 or 0 if the file is UPX'd
;                   Failure - -1 and sets @error to non-zero.
; Author ........: guinness
; Remarks .......: Constants.au3 should be included.
; Example .......: No
; ===============================================================================================================================
Func _IsUPX($sFilePath, $sDirectory = @ScriptDir)
    $sDirectory = StringRegExpReplace($sDirectory, '[/]+$', '')
    If FileExists($sDirectory & 'upx.exe') = 0 Then
        Return SetError(1, 0, -1)
    EndIf
    Local $iPID = Run('"' & $sDirectory & 'upx.exe' & '" -t "' & $sFilePath & '"', @ScriptDir, @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD), $sOutput = ''
    While 1
        $sOutput &= StdoutRead($iPID)
        If @error Then
            ExitLoop
        EndIf
    WEnd
    Local $aReturn = StringRegExp($sOutput, '(?is)testing ' & StringRegExpReplace($sFilePath, "^.*", "") & ' (.*?)' & @CRLF, 3)
    If @error Then
        Return 0
    EndIf
    Return Number($aReturn[0] = '[OK]')
EndFunc   ;==>_IsUPX

Updated: Thanks to Mobius for spurring me on & MrCreatoR for the Examples & improvement to the UPX Function that doesn't require UPX.

Updated:

Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Why don't you just read the header of the target file?

It would remove upx as a dependancy, although it would not help you if the author stripped (or modified) the upx header.

(An additional persistant static byte sequence exists to detect a possibly upx compressed binary)

Nice script all the same guinness. :huh2:

wtfpl-badge-1.png

Link to comment
Share on other sites

(An additional persistant static byte sequence exists to detect a possibly upx compressed binary)

That was going to be my next step check what binary sequence is consistent in all versions, so now I know all is not lost :huh2: Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

I could tell you what this sequence is (or pertubations + static components ) but you seem like the kind of person that would enjoy finding out for themselves yes?

Very true, I love a challenge.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Updated OP with a version that doesn't require UPX!

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Updated OP with a version that doesn't require UPX!

Now were cooking Dude, but...

You are just testing if the target contains a particular executable header with that code. (which will not be the same one target to another, repetetively test your code against numerous different targets that are packed (or not) with upx) she will fail.

Keep at her though, what you seek is not obvious but you are on the right (ish) track.

Ed: unecessary cussing. (even pour moi)

Edited by Mobius

wtfpl-badge-1.png

Link to comment
Share on other sites

Oh! I thought DLL's would be the same etc...

Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

No I speak not of other types of pe files (unless you are testing your code against them that is), ok perhaps when I mentioned the pe header I mislead you.

You seek the first entry point bytes which in upx is 2 bytes static and 2 bytes which are volatile per binary. (aka long) (or more pertinently when parsing with AutoIt3 it would be easier to search for this value as a quad *hint* )

Edited by Mobius

wtfpl-badge-1.png

Link to comment
Share on other sites

OK, so am I on the right track? You have to understand the only coding language I've ever used is AutoIt! I love challenges! :huh2:

And then "2 bytes which are volatile per binary" I get the feeling its maybe using this >> DllStructCreate('long[80]') because I noticed in a DLL & EXE they both had a series of 0's which were 320 characters long.

Edit: Removed old code.

Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

OK, so am I on the right track? You have to understand the only coding language I've ever used is AutoIt! I love challenges but at the same time hate looking like an idiot! :huh2:

What language(s) you are experienced in really does not matter (in the long term), You do not look like an idiot (far from it).

And then "2 bytes which are volatile per binary" I get the feeling its maybe using this >> DllStructCreate('long[80]') because I noticed in a DLL & EXE they both had a series of 0's which were 320 characters long.

guinness,

0x4D5A means 'MZ' while useful (in some situations) this is ultimately the windows pe bom header and has nothing to do with upx.

*Snipped*

Edited by Mobius

wtfpl-badge-1.png

Link to comment
Share on other sites

I used this a while ago:

$sPath = @AutoItExe
$iPacked = _FilePackedWithUPX($sPath)
ConsoleWrite($sPath & ": " & $iPacked & @LF)

$sPath = StringRegExpReplace(@AutoItExe, "\\[^\\]*$", "") & "\Aut2Exe\upx.exe"
$iPacked = _FilePackedWithUPX($sPath)
ConsoleWrite($sPath & ": " & $iPacked & @LF)

Func _FilePackedWithUPX($sFilePath)
    Local $hFile, $sRead, $bStart_Address = 0x001F0, $iUPX_Header_Len = 30
    
    $hFile = FileOpen($sFilePath, 0)
    FileSetPos($hFile, $bStart_Address, 0)
    $sRead = FileRead($hFile, $iUPX_Header_Len)
    FileClose($hFile)
    
    If StringInStr($sRead, "UPX") Then
        Return 1
    EndIf
    
    Return 0
EndFunc
Edited by MrCreatoR

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

:huh2: Thanks MrCreatoR. At least I tried! Maybe in the future I should be a little more diligent before posting in the Example sections ;)

I had a couple of Examples which I sent to Mobius to see if I was on the right track.

Edit: I will update the OP later.

Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Thanks to MrCreatoR and Mobius, I have finally updated the OP.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • 2 weeks later...

Hello guinness,

A better structured example of upx detection.

#Region Example
$_ = FileOpenDialog("",@scriptdir,"Binary (*.exe;*.dll)")
IF @error THEN EXIT
$iRet = _IsUPX($_)
If @error Then
  MsgBox(16,@scriptname,"_IsUPX Error "& @error)
Elseif $iRet Then
  MsgBox(64,@scriptname,"Upx packing detected in:"& @lf & $_)
Else
  MsgBox(48,@scriptname,"Upx packing not detected in:"& @lf & $_)
Endif
#Endregion
;
#cs
  _IsUPX bloaty but accurate structured example function.

  Focuses on the first bytes of the .code entrypoint for upx
  instead of checking section names and evidence of the upx
  version signature which are too easily modified to be used
  effectively.

  The main section table loop at the tail of the function is
  the meat of the operation and could easily be modified to
  check the section names and to more accurately calculate the
  correct instance of the .code section if you wanted to.

  Returns: 0 = Upx not detected, 1 First bytes (upx) detected.
  Errors ::
    1 = Failed to open target file.
    2 = MZ bom not found (not executable)
    3 = PE signature not found. (non Win32 pe's not supported)
#ce
;
Func _IsUPX($sFile)
Local $hFile = FileOpen($sFile,16)
If @error Then
  ;ConsoleWrite("Failed to open for reading:"& @LF & $sFile & @LF)
  Return SetError(1)
Endif
;
Local $Size = FileGetSize($sFile)
Local $BinBuff = DllStructCreate("byte["& $Size &"]")
DllStructSetData($BinBuff,1,FileRead($hFile))
FileClose($hFile)
Local $BBPtr = DllStructGetPtr($BinBuff)
; Storing the pointer again here for later use since the original is recycled.
Local $OBBPtr = $BBPtr
;
Local Const $IDH_LEN = 64   ; DllStructGetSize($IMAGE_DOS_HEADER)
Local Const $INH_LEN = 248  ; DllStructGetSize($IMAGE_NT_HEADERS)
Local Const $IFH_LEN = 20   ; DllStructGetSize($IMAGE_FILE_HEADER)
Local Const $IOH_LEN = 224  ; DllStructGetSize($IMAGE_OPT_HEADER)
Local Const $ISH_LEN = 40   ; DllStructGetSize($IMAGE_SECTION_HEADER)
;
Local $IMAGE_DOS_HEADER = DllStructCreate( _
"WORD e_magic;WORD e_cblp;WORD e_cp;WORD e_crlc;WORD e_cparhdr;WORD e_minalloc;WORD e_maxalloc;"& _
"WORD e_ss;WORD e_sp;WORD e_csum;WORD e_ip;WORD e_cs;WORD e_lfarlc;WORD e_ovno;"& _
"WORD e_res[4];WORD e_oemid;WORD e_oeminfo;WORD e_res2[10];WORD e_lfanew",$BBPtr)
;
If Not DllStructGetData($IMAGE_DOS_HEADER,"e_magic") = 23177 Then
  ;ConsoleWrite("MZ executable bom not found!"& @LF)
  Return SetError(2)
Endif
; Rotate the pointer to offset specified landing at image nt header.
$BBPtr += DllStructGetData($IMAGE_DOS_HEADER,"e_lfanew")
;
Local $IMAGE_NT_HEADERS = DllStructCreate( _
"DWORD signature;CHAR ifh["& $IFH_LEN &"];CHAR ioh["& $IOH_LEN &"]",$BBPtr)
;
If Not DllStructGetData($IMAGE_NT_HEADERS,"signature") = 17744 Then
  ;ConsoleWrite("PE signature not found!"& @LF)
  Return SetError(3)
Endif
;
Local $IMAGE_FILE_HEADER = DllStructCreate( _
"WORD machine;WORD numberofsections;DWORD timedatestamp;DWORD pointertosymboltable;DWORD numberofsymbols;"& _
"WORD SizeOfOptionalHeader;WORD characteristics",DllStructGetPtr($IMAGE_NT_HEADERS,"ifh"))
;
Local $IMAGE_OPT_HEADER = DllStructCreate( _
"WORD magic;BYTE majorlinkerversion;BYTE minorlinkerversion;DWORD sizeofcode;DWORD sizeofinitializeddata;"& _
"DWORD sizeofuninitializeddata;DWORD addressofentrypoint;DWORD baseofcode;DWORD baseofdata;DWORD imagebase;"& _
"DWORD sectionalignment;DWORD filealignment;WORD majoroperatingsystemversion;WORD minoroperatingsystemversion;"& _
"WORD majorimageversion;WORD minorimageversion;WORD majoresubsystemversion;WORD minorsubsystemversion;"& _
"DWORD win32versionvalue;DWORD sizeofimage;DWORD sizeofheaders;DWORD checksum;WORD subsystem;WORD dllcharacteristics;"& _
"DWORD sizeofstackreserve;DWORD sizeofstackcommit;DWORD sizeofheapcommit;DWORD loaderflags;DWORD numberofrvaandsizes;"& _
"DOUBLE datadirectory[16]",DllStructGetPtr($IMAGE_NT_HEADERS,"ioh"))
; Rotate pointer to first section in the table
$BBPtr += $INH_LEN
; Loop through the section tables
For $i = 1 To DllStructGetData($IMAGE_FILE_HEADER,"numberofsections")
  Local $IMAGE_SECTION_HEADER = DllStructCreate( _
  "CHAR name[8];DWORD virtualsize;DWORD virtualaddress;DWORD sizeofrawdata;DWORD pointertorawdata;DWORD pointertorelocations;"& _
  "DWORD pointertolinenumbers;WORD numberofrelocations;WORD numberoflinenumbers;DWORD characteristics",$BBPtr)
  ; The purpose of this chunk of code is simply to convert the relative virtual address into a file offset,
  ; So that we can check this offset for the upx first byte sequence '60BE' of the .code (UPX1) section.
  Local $RVA_TO_FILE_OFFSET = DllStructGetData($IMAGE_SECTION_HEADER,"pointertorawdata") + DllStructGetData($IMAGE_OPT_HEADER,"addressofentrypoint") - DllStructGetData($IMAGE_SECTION_HEADER,"virtualaddress")
  If $RVA_TO_FILE_OFFSET > 0 And  $RVA_TO_FILE_OFFSET < $Size Then
    Local $FIRSTBYTES = DllStructCreate("WORD fb",$OBBPtr + $RVA_TO_FILE_OFFSET)
    If DllStructGetData($FIRSTBYTES,"fb") = 48736 Then
    ;ConsoleWrite("Upx first bytes detected in section: "& DllStructGetData($IMAGE_SECTION_HEADER,"name") & @LF)
    Return 1
    Endif
  Endif
  ; Rotate the pointer plus the static section table element length
  $BBPtr += $ISH_LEN
Next
EndFunc

Want a version without all those Au3 structures? go

Vlad

Edited by Mobius

wtfpl-badge-1.png

Link to comment
Share on other sites

Very nice indeed Mobius! :) I have a lot to learn from this.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • 2 weeks later...

Hi Mobius,

a really nice function to detect if an executable is UPXed ;). I want to add it to SMF, but your example loads the whole exe to memory. To speed up things for large exes (e.g. 100 meg installers), is it okay to read just the header (1024 is just a plain guess :) ) and then set the file read pos accordingly?

; http://www.autoitscript.com/forum/topic/129757-isupx-checks-if-a-supported-file-is-upxed/page__view__findpost__p__906230
; By Mobius

#Region Example
$_ = FileOpenDialog("", @ScriptDir, "Binary (*.exe;*.dll)")
If @error Then Exit
$iRet = _IsUPXed($_)
If @error Then
    MsgBox(16, @ScriptName, "_IsUPXed Error " & @error)
ElseIf $iRet Then
    MsgBox(64, @ScriptName, "Upx packing detected in:" & @LF & $_)
Else
    MsgBox(48, @ScriptName, "Upx packing not detected in:" & @LF & $_)
EndIf
#EndRegion Example

;
#cs
    _IsUPXed bloaty but accurate structured example function.

    Focuses on the first bytes of the .code entrypoint for upx
    instead of checking section names and evidence of the upx
    version signature which are too easily modified to be used
    effectively.

    The main section table loop at the tail of the function is
    the meat of the operation and could easily be modified to
    check the section names and to more accurately calculate the
    correct instance of the .code section if you wanted to.

    Returns: 0 = Upx not detected, 1 First bytes (upx) detected.
    Errors ::
    1 = Failed to open target file.
    2 = MZ bom not found (not executable)
    3 = PE signature not found. (non Win32 pe's not supported)
#ce
;

;ConsoleWrite(_IsUPXed("zz_test1.exe") & @CRLF)
;ConsoleWrite(_IsUPXed("zz_test2.exe") & @CRLF)

Func _IsUPXed($sFile)
    Local $hFile2, $sData
    Local $hFile = FileOpen($sFile, 16)
    If @error Then
        ;ConsoleWrite("Failed to open for reading:"& @LF & $sFile & @LF)
        Return SetError(1)
    EndIf
    ;
    Local $Size = FileGetSize($sFile)
    ;Local $BinBuff = DllStructCreate("byte[" & $Size & "]")
    Local $BinBuff = DllStructCreate("byte[1024]")
    ;DllStructSetData($BinBuff, 1, FileRead($hFile, $Size))
    DllStructSetData($BinBuff, 1, FileRead($hFile, 1024))
    FileClose($hFile)
    Local $BBPtr = DllStructGetPtr($BinBuff)
    ; Storing the pointer again here for later use since the original is recycled.
    Local $OBBPtr = $BBPtr
    ;
    Local Const $IDH_LEN = 64 ; DllStructGetSize($IMAGE_DOS_HEADER)
    Local Const $INH_LEN = 248 ; DllStructGetSize($IMAGE_NT_HEADERS)
    Local Const $IFH_LEN = 20 ; DllStructGetSize($IMAGE_FILE_HEADER)
    Local Const $IOH_LEN = 224 ; DllStructGetSize($IMAGE_OPT_HEADER)
    Local Const $ISH_LEN = 40 ; DllStructGetSize($IMAGE_SECTION_HEADER)
    ;
    Local $IMAGE_DOS_HEADER = DllStructCreate( _
            "WORD e_magic;WORD e_cblp;WORD e_cp;WORD e_crlc;WORD e_cparhdr;WORD e_minalloc;WORD e_maxalloc;" & _
            "WORD e_ss;WORD e_sp;WORD e_csum;WORD e_ip;WORD e_cs;WORD e_lfarlc;WORD e_ovno;" & _
            "WORD e_res[4];WORD e_oemid;WORD e_oeminfo;WORD e_res2[10];WORD e_lfanew", $BBPtr)
    ;
    If Not DllStructGetData($IMAGE_DOS_HEADER, "e_magic") = 23177 Then
        ;ConsoleWrite("MZ executable bom not found!"& @LF)
        Return SetError(2)
    EndIf
    ; Rotate the pointer to offset specified landing at image nt header.
    $BBPtr += DllStructGetData($IMAGE_DOS_HEADER, "e_lfanew")
    ;
    Local $IMAGE_NT_HEADERS = DllStructCreate( _
            "DWORD signature;CHAR ifh[" & $IFH_LEN & "];CHAR ioh[" & $IOH_LEN & "]", $BBPtr)
    ;
    If Not DllStructGetData($IMAGE_NT_HEADERS, "signature") = 17744 Then
        ;ConsoleWrite("PE signature not found!"& @LF)
        Return SetError(3)
    EndIf
    ;
    Local $IMAGE_FILE_HEADER = DllStructCreate( _
            "WORD machine;WORD numberofsections;DWORD timedatestamp;DWORD pointertosymboltable;DWORD numberofsymbols;" & _
            "WORD SizeOfOptionalHeader;WORD characteristics", DllStructGetPtr($IMAGE_NT_HEADERS, "ifh"))
    ;
    Local $IMAGE_OPT_HEADER = DllStructCreate( _
            "WORD magic;BYTE majorlinkerversion;BYTE minorlinkerversion;DWORD sizeofcode;DWORD sizeofinitializeddata;" & _
            "DWORD sizeofuninitializeddata;DWORD addressofentrypoint;DWORD baseofcode;DWORD baseofdata;DWORD imagebase;" & _
            "DWORD sectionalignment;DWORD filealignment;WORD majoroperatingsystemversion;WORD minoroperatingsystemversion;" & _
            "WORD majorimageversion;WORD minorimageversion;WORD majoresubsystemversion;WORD minorsubsystemversion;" & _
            "DWORD win32versionvalue;DWORD sizeofimage;DWORD sizeofheaders;DWORD checksum;WORD subsystem;WORD dllcharacteristics;" & _
            "DWORD sizeofstackreserve;DWORD sizeofstackcommit;DWORD sizeofheapcommit;DWORD loaderflags;DWORD numberofrvaandsizes;" & _
            "DOUBLE datadirectory[16]", DllStructGetPtr($IMAGE_NT_HEADERS, "ioh"))
    ; Rotate pointer to first section in the table
    $BBPtr += $INH_LEN
    ; Loop through the section tables
    For $i = 1 To DllStructGetData($IMAGE_FILE_HEADER, "numberofsections")
        Local $IMAGE_SECTION_HEADER = DllStructCreate( _
                "CHAR name[8];DWORD virtualsize;DWORD virtualaddress;DWORD sizeofrawdata;DWORD pointertorawdata;DWORD pointertorelocations;" & _
                "DWORD pointertolinenumbers;WORD numberofrelocations;WORD numberoflinenumbers;DWORD characteristics", $BBPtr)
        ; The purpose of this chunk of code is simply to convert the relative virtual address into a file offset,
        ; So that we can check this offset for the upx first byte sequence '60BE' of the .code (UPX1) section.
        Local $RVA_TO_FILE_OFFSET = DllStructGetData($IMAGE_SECTION_HEADER, "pointertorawdata") + DllStructGetData($IMAGE_OPT_HEADER, "addressofentrypoint") - DllStructGetData($IMAGE_SECTION_HEADER, "virtualaddress")

        ;ConsoleWrite("$RVA_TO_FILE_OFFSET" & @TAB & $RVA_TO_FILE_OFFSET & @CRLF)
        If $RVA_TO_FILE_OFFSET > 0 And $RVA_TO_FILE_OFFSET < $Size Then
            ;Local $FIRSTBYTES = DllStructCreate("WORD fb", $OBBPtr + $RVA_TO_FILE_OFFSET)
            $hFile2 = FileOpen($sFile, 16)
            FileSetPos($hFile2, $RVA_TO_FILE_OFFSET, 0)
            $sData = FileRead($hFile2, 5)
            FileClose($hFile2)
            Local $FIRSTBYTES2 = DllStructCreate("WORD fb")
            DllStructSetData($FIRSTBYTES2, 1, $sData)
            ;ConsoleWrite(DllStructGetData($FIRSTBYTES2, "fb") & @CRLF)
            If DllStructGetData($FIRSTBYTES2, "fb") = 48736 Then
                ;ConsoleWrite("Upx first bytes detected in section: " & DllStructGetData($IMAGE_SECTION_HEADER, "name") & @LF)
                Return 1
            EndIf
        EndIf
        ; Rotate the pointer plus the static section table element length
        $BBPtr += $ISH_LEN
    Next
EndFunc   ;==>_IsUPXed
Link to comment
Share on other sites

Hi KaFu,

Sorry for my late response, Yes you are absolutely right ;) so I cobbled this together.

ISUPX2.au3

#Region Example
$_ = FileOpenDialog("",@scriptdir,"Binary (*.exe;*.dll)")
If @error Then Exit
$iRet = _IsUPXLargeTarget($_)
If @error Then
  MsgBox(16,@scriptname,"_IsUPX Error "& @error)
Elseif $iRet Then
  MsgBox(64,@scriptname,"Upx packing detected in:"& @lf & $_)
Else
  MsgBox(48,@scriptname,"Upx packing not detected in:"& @lf & $_)
Endif
#Endregion
;
#cs
  _IsUPXLargeTarget offset dependant example for big binaries.

  Identical in operation to my structured example.

  Returns: 0 = Upx not detected, 1 First bytes (upx) detected.
  Errors ::
    1 = Failed to open target file.
    2 = MZ bom not found (not executable)
    3 = PE signature not found. (non Win32 pe's not supported)
#ce
Func _IsUPXLargeTarget($sFile)
Local $hFile = FileOpen($sFile,16)
If @error Then
  Return SetError(1)
Endif
;
Local $Size = FileGetSize($sFile)
;
Local $Val = Number(FileRead($hFile,2))
If Not $Val = 23177 Then; MZ bom
  FileClose($hFile)
  Return SetError(2)
Endif
;
FileSetPos($hFile,60,0)
$Val = Number(FileRead($hFile,2))
Local $PEoffset = $Val
;
FileSetPos($hFile,$Val,0)
$Val = Number(FileRead($hFile,2))
If Not $Val = 17744 Then; PE sig
  FileClose($hFile)
  Return SetError(3)
Endif
;
Local Const $INH_LEN = 248
Local Const $IFH_LEN = 20
Local Const $ISH_LEN = 40
;
FileSetPos($hFile,$PEoffset +6,0)
Local $SectionCount = Number(FileRead($hFile,2))
FileSetPos($hFile,$PEoffset + 4 + $IFH_LEN + 16,0)
Local $Addressofentrypoint = Number(FileRead($hFile,4))
;
Local $CurrentOffset = $PEoffset + $INH_LEN
For $i = 1 To $SectionCount
  FileSetPos($hFile,$CurrentOffset +12,0)
  Local $Virtualaddress = Number(FileRead($hFile,4))
  FileSetPos($hFile,$CurrentOffset +20,0)
  Local $Pointertorawdata = Number(FileRead($hFile,4))
  Local $RVA2FO = $Pointertorawdata + $Addressofentrypoint - $Virtualaddress
  If $RVA2FO > 0 And $RVA2FO < $Size Then
    FileSetPos($hFile,$RVA2FO,0)
    $Val = Number(FileRead($hFile,2))
    If $Val = 48736 Then
    FileClose($hFile)
    Return 1
    Endif
  Endif
  $Currentoffset += $ISH_LEN
Next
FileClose($hFile)
Return 0
Endfunc

Thankyou KaFu for pointing out the fact that the original unstructured version I posted had more bugs than my garden. :)

Edited by Mobius

wtfpl-badge-1.png

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...