2

I have a bash script for initializing iptables.

#!/bin/sh

EXTIF="eth0"
INTIF="eth1"

INTIP="192.168.0.1/32"
EXTIP=$(/sbin/ip addr show dev "$EXTIF" | perl -lne 'if(/inet (\S+)/){print$1;last}');

UNIVERSE="0.0.0.0/0"
INTNET="192.168.0.1/24"

/sbin/iptables-restore -v < iptables.rules

I have iptables.rules file containing something like this:

-A OUTPUT -o $EXTIF -s $UNIVERSE -d $INTNET -j REJECT

How can I pass those variables from bash script to iptables.rules or evaluate them?

Michael
  • 397
  • 1
  • 7
  • 15

3 Answers3

3

Something like this:

while read line; do eval "echo ${line}"; done < iptables.rules | /sbin/iptables-restore -v

or more nicely formatted:

while read line
  do eval "echo ${line}"
done < iptables.rules | /sbin/iptables-restore -v

This forces the variable expansion stuff. You definitely need to be sure you understand what's in those variables; I suspect that if somebody could set a variable to an arbitrary value they could use it to execute arbitrary code.

freiheit
  • 14,544
  • 1
  • 47
  • 69
1

I would not want to trust this in general execution without a lot of content tests, at which point it becomes easier to feed it through a macro processor instead of trying to substitute shell variables into it. I strongly recommend going that way instead. That said, something like this should work:

f="$(mktemp)" || exit 1
{echo '/sbin/iptables-restore <<__EOF'; cat iptables.rules; echo '__EOF'} >"$f"
. "$f"
rm "$f"
geekosaur
  • 7,175
  • 1
  • 20
  • 19
  • 1
    In Bash (note that the question is tagged `[bash]`, but the shebang is `#!/bin/sh`), you can source something on the fly without a temporary file: `source <(echo '...'; echo "$( – Dennis Williamson Mar 14 '11 at 04:26
0

If iptables.rules contains:

RULES="-A OUTPUT -o $EXTIF -s $UNIVERSE -d $INTNET -j REJECT"

And your script sources that file, then the variables will be evaluated.

#!/bin/sh

EXTIF="eth0"
INTIF="eth1"

INTIP="192.168.0.1/32"
EXTIP=$(/sbin/ip addr show dev "$EXTIF" | perl -lne 'if(/inet (\S+)/){print$1;last}');

UNIVERSE="0.0.0.0/0"
INTNET="192.168.0.1/24"
. iptables.rules

/sbin/iptables-restore -v < $RULES
toppledwagon
  • 4,245
  • 25
  • 15