Linux Fu: Shell Script File Embedding

Linux Fu: Shell Script File Embedding

You need to package up a bunch of files, send them somewhere, and do something with them at the destination. It isn’t an uncommon scenario. The obvious answer is to create an archive — a zip or tar file, maybe — and include a shell script that you have to tell the user to run after unpacking.


That may be obvious, but it assumes a lot on the part of the remote user. They need to know how to unpack the file and they also need to know to run your magic script of commands after the unpack. However, you can easily create a shell script that contains a file — even an archive of many files — and then retrieve the file and act on it at run time. This is much simpler from the remote user’s point of view. You get one file, you execute it, and you are done.


In theory, this isn’t that hard to do, but there are a lot of details. Shell scripts are not compiled — at least, not typically — so the shell only reads what it needs to do the work. That means if your script is careful to exit, you can add as much “garbage” to the end of it as you like. The shell will never look at it, so it’s possible to store the payload there.

So Then What?


The only trick, then, is to find the end of the script and, thus, the start of the payload. Consider this file, deliver.sh:



#!/bin/bash
WORKDIR=$( mktemp -d ) #find last line +1 SCRIPT_END=$( awk ' BEGIN { err=1; } /^w*___END_OF_SHELL_SCRIPT___w*$/ { print NR+1; err=0; exit 0; } END { if (err==1) print "?"; }
' "$0" ) # check for error if [ "$SCRIPT_END" == '?' ]
then echo Can't find emb ..

Support the originator by clicking the read the rest link below.