Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are these awk commands vulnerable to code injection?

I was unsure on how to correctly script a particular awk command which uses a shell variable, when I read the answers to How do I use shell variables in an awk script?.

The accepted answer demonstrates how interpolating a shell variable in an awkcommand would be prone to malicious code injection, and while I was able to reproduce the demo, I could not find the same problem with either of the following two commands:

#HWLINK=enp10s0
ip -o route | awk '/'$HWLINK'/ && ! /default/ {print $1}'
ip -o route | awk "/$HWLINK/"' && ! /default/ {print $1}'

So, the main question is if any of these (or both) is vulnerable.

A secondary question would be which form is preferred. I tried ip -o route | awk -v hwlink="$HWLINK" '/hwlink/ && ! /default/ {print $1}' but that doesn't work.

p.s. this is a refactoring; the original command was ip -o route | grep $HWLINK | grep -v default | awk '{print $1}'.

like image 561
Marc.2377 Avatar asked Mar 21 '26 21:03

Marc.2377


2 Answers

Your idea was right about letting the shell variables getting interpolated inside awk could let malicious code injection. As rightly pointed use the -v syntax, but your attempt fails because the pattern match with variable doesn't work in the form /../, use the direct ~ match

ip -o route | awk -v hwlink="$HWLINK" '$0 ~ hwlink && ! /default/ {print $1}'

Recommended way to sanitize your variables passed to awk would be to use the ARGV array or ENVIRON variable. Variables passed this way don't undergo expansion done by the shell

value='foo\n\n'
awk 'BEGIN {var=ARGV[1]; delete ARGV[1]}' "$value"

If you printed the value of var inside the awk it would be a literal foo\n\n and not the multi-line string which usually happens when the shell expands it.

like image 83
Inian Avatar answered Mar 24 '26 13:03

Inian


Sure, both are vulnerable, the first a bit less so.

This breaks your second line:

HWLINK="/{}BEGIN{print \"Your mother was a hamster and your father smelt of elderberries\"}/"

The only reason it doesn't break your first line is, in order to be able to be injected into the first line it must not contain spaces.

HWLINK="/{}BEGIN{print\"Your_mother_was_a_hamster_and_your_father_smelt_of_elderberries\"}/"

I see you already got the correct syntax to use :)

like image 25
Amadan Avatar answered Mar 24 '26 12:03

Amadan