How do I set the taint mode in a perl script with a '#!/usr/bin/env perl'- shebang?
Asked Answered
S

2

11

how do I set the taint mode in a perl script with a

#!/usr/bin/env perl

shebang?

Superimpose answered 27/3, 2010 at 10:48 Comment(5)
It helps if you can't predict the location of the perl binary (/usr/bin or /usr/local/bin). perlmonks.org/?node_id=716740 - I guess the question is whether you can predict the location of env...Tamtam
On my PC I use /usr/local/bin/perl and on my netbook /usr/bin/perl. So with /usr/bin/env perl I don't have to change my perl-scripts. And I suppose they will ship the next release of my OS with perl-version 5.10.1, so maybe I will use on my PC again the onboard-perl with /usr/bin/perl and there too I won't have to change my shebangs.Superimpose
Gavin, the location of env is standardised.Milo
@Milo unless you use OpenServer 5.0.6 (SCO) or Unicos 9.0.2 (Cray) ;-) en.wikipedia.org/wiki/Hash-bang#PortabilityTamtam
@Sinan, if you ever use perlbrew and have multiple Perls installed on your system, then using /usr/bin/env perl is a godsendSacellum
T
12

You can pass the PERL5OPT environment variable on the shebang line:

#!/usr/bin/env PERL5OPT=-T perl

This seems all rather backwards to me.

Another option, is to re-execute the script under taint mode if you detect it's not on:

#!/usr/bin/env perl

warn 'Taint mode is '.(${^TAINT} ? 'on' : 'off'); # For debugging

exec($^X,'-T',$0,@ARGV) unless ${^TAINT};

# do stuff under taint mode here

Obviously, this is a major startup performance hit.

Tamtam answered 27/3, 2010 at 11:23 Comment(2)
You cannot actually specify a variable in a shebang with /usr/bin/env. Doing so will cause env to execve itself in an infinite loop, never even getting to the command requested. I tested this against both Linux and FreeBSD.Villatoro
Yes - it seems to be only OS-X that currently supports the first incantation.Tamtam
N
3

Since taint mode can only be enabled via the -T flag, and env won't accept any flags in a shebang line, your best option is to run the program via perl -T script.pl rather than executing the script directly.

If you absolutely need to enforce taint mode in the shebang, you could make a taintperl script somewhere in your PATH (e.g. /usr/local/bin) with the following contents:

#!/bin/sh
/usr/bin/env perl -T

Then in your Perl script, have

#!/usr/bin/env taintperl
Nonrecognition answered 27/3, 2010 at 11:2 Comment(2)
On many OSs, you cannot use an interpreted script as a script interpreter. You would have to do this in a compiled language, e.g. CTamtam
@GavinBrock That is true for the program mentioned immediately after the #!. Here, it's /usr/bin/env, which is compiled. In turn, env doesn't care about whether taintperl is a compiled program or not.Conard

© 2022 - 2024 — McMap. All rights reserved.