Threat Level: green Handler on Duty: Xavier Mertens

SANS ISC: Changing BAT Files On The Fly SANS ISC InfoSec Forums

Watch ISC TV. Great for NOCs, SOCs and Living Rooms: https://isctv.sans.edu

Sign Up for Free!   Forgot Password?
Log In or Sign Up for Free!
Changing BAT Files On The Fly

I often use Windows BAT files, simple ones, to execute a series of commands. And over the years, I learned not to change these BAT files while they were executing, because cmd.exe would "notice" those changes when it has to execute the next command in the BAT file, and read the changed file, leading to undesired results.

But recently, I started to use this to my advantage: change commands in a BAT file while it is executing, without undesired results.

The trick is to only change the commands that still have to be executed. Don't touch the commands that have already executed, and certainly, don't make them shorter or longer.

Although I have not reversed cmd.exe be sure of what I experience, it seems like cmd.exe does not read a BAT all at once, but that it has a filepointer into the BAT file it is processing, and reads the next line to execute after the current line finishes executing.

If you remove bytes before the filepointer (e.g., by changing commands before the current command to make them shorter, or removing commands), the filepointer will no longer point to the beginning of the next line to execute.

Same if you add bytes before the filepointer.

The trick is to change commands after the filepointer, e.g., change commands that have yet to be executed, while leaving the rest of the BAT file intact.

 

Didier Stevens
Senior handler
Microsoft MVP
blog.DidierStevens.com

DidierStevens

597 Posts
ISC Handler
Aug 2nd 2021
I noticed this effect some time ago. And as a proof of concept I used the effect with a GOTO used to re-execute a changed bat file. It seems like this could make an excellent malware trick so I (rashly) presumed all you pros knew about this. In the test I changed the entire bat file after the label for the goto statement and the absolute location of the goto statement in the file. I used goto again to step around the unchanged goto line.

(Some time ago was on the order of 30 to 40 years ago (3.1.1 days). That discovery cost my employer a day's work as I explored it and its implications before going back to the software development for which I was being paid.)
{o.o}
JD

13 Posts
Wow, just like Linux shell scripts!
Paul Szabo

14 Posts
Pros are just like non-pros: they don't know everything. :-)
DidierStevens

597 Posts
ISC Handler

Sign Up for Free or Log In to start participating in the conversation!