Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Interpret Parameter Value at Time of Function Definition



Op 05-09-17 om 15:47 schreef Vin Shelton:
[...]
> $ aaa=bbb
> $ function t {
>     print aaa = \"$aaa\"
>   }
> $ t
> aaa = "bbb"
> $ aaa=ccc t
> aaa = "ccc"
> 
> I would like to interpret $aaa at read time, so that:
> 
>     aaa=ccc t
> 
> would print:
> 
>     aaa = "bbb"
> 
> How do I do that?

AFAIK, the only way to do this without side effects is by using 'eval':

aaa=bbb
eval "function t {
  print \"aaa = $aaa\"
}"
typeset -f t

The value of "$aaa" is now hard-coded in the function definition, as you
can see by the output of 'typeset -f t'.

Note that you have to be very careful to backslash-escape everything
except $aaa correctly so that only $aaa is interpreted at read time,
otherwise you're going to get hard-to-trace bugs.

Also, this should ONLY be done this way if $aaa is guaranteed to contain
trusted data only. If the value of $aaa can be given by other users from
the outside, you've got a code injection vulnerability, as any shell
grammar in $aaa will be interpreted and executed by 'eval'. For
instance, setting
   aaa='"; echo injection"'
would print "injection".

You can avoid the vulnerability by shell-quoting the value of $aaa
before using it, which in zsh is easy to do using the (q) parameter
expansion flag:

# ... $aaa contains some untrusted data ...
eval "function t {
  print -r \"aaa =\" ${(q)aaa}
}"
typeset -f t

The expansion ${(q)aaa} is appropriately quoted as a string using shell
grammar so it will never be interpreted as code.

This is advanced stuff, so be careful.

- Martijn



Messages sorted by: Reverse Date, Date, Thread, Author