1 little known secret of forfiles.exe, part 2

In this old post I have demonstrated how to abuse forfiles.exe to run your ‘cmd.exe’ of choice.

There is one more trick we can do with this tool.

When forfiles.exe enumerates the files it executes a default command cmd /c echo @file. It turns out that the execution of this command expands environment variables as well…

So…

If we create a file called %foo%, and make sure that there is an environmental variable called foo, we can now control the cmd /c echo @file command and force it to do some unusual stuff.

For example:

  • create a file called %foo%
  • set foo to “&calc.exe&”
  • run forfiles

– it will enumerate files in a directory, print their names, and when it will come across the %foo% file, it will also … execute calculator…

This happens because cmd /c echo @file gets expanded to cmd /c echo %foo% which in turn will be executed as “echo “&calc.exe&”“.