Is safe make a webform, where the user can enter sed command, like:
s/\(.*\) *\(.*)/\2:\1/;s/$/end of line/;s/this/that/g
after the form submit i want execute the sed command like:
sed '<<string from the form>>' < FILE1 >FILE2
Is this safe? What is the correct way executing user-supplied sed commands from the security standpoint? What i need to check or how to prepare the sed command?
adding the calling mode – mean something like this – so will not run via shell…
use 5.014;
use warnings;
use autodie;
use FileHandle;
use IPC::Open2;
use File::Slurp;
my $sedcommand = 's/a/QQ/g';
my $input = read_file('inputfile.txt');
my $out = sed_edit($sedcommand, $input);
say $out;
sub sed_edit {
my($command, $text) = @_;
my($fromsed, $tosed);
my $pid = open2($fromsed, $tosed, "sed", "$command" );
print $tosed $text;
close($tosed);
my $result = <$fromsed>;
close($fromsed);
waitpid($pid, 0);
return($result);
}
If a user can enter anything they want in the string and you pass that string unmodified to the shell so it can insert it into the
sedcommand line you have there, then no, it is not safe. (Actually, it’s difficult to say for certain without knowing more implementation details. But the likely answer is: Not safe.)There are probably ways to make this safe, but doing so would involve getting into a lot of implementation details.
That said, the very first step would probably be to figure out what the appropriate characters the user should be allowed to enter are, and put in checking to make sure they only entered a string with those characters before doing anything with it.
That is a first step, but it is probably not the last step.