11

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

#!/usr/bin/env perl

shebang?

sid_com
  • 21,289
  • 23
  • 89
  • 171
  • 2
    It helps if you can't predict the location of the perl binary (/usr/bin or /usr/local/bin). http://www.perlmonks.org/?node_id=716740 - I guess the question is whether you can predict the location of env... – Gavin Brock Mar 27 '10 at 16:18
  • 3
    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. – sid_com Mar 28 '10 at 14:13
  • Gavin, the location of `env` is standardised. – daxim Mar 29 '10 at 11:22
  • @daxim unless you use OpenServer 5.0.6 (SCO) or Unicos 9.0.2 (Cray) ;-) http://en.wikipedia.org/wiki/Hash-bang#Portability – Gavin Brock Apr 01 '10 at 05:26
  • 1
    @Sinan, if you ever use perlbrew and have multiple Perls installed on your system, then using `/usr/bin/env perl` is a godsend – mpeters Feb 04 '11 at 23:04

2 Answers2

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.

Gavin Brock
  • 4,879
  • 1
  • 27
  • 33
  • 3
    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. – Zed Nov 20 '14 at 21:52
  • 1
    Yes - it seems to be only OS-X that currently supports the first incantation. – Gavin Brock Jan 06 '15 at 14:30
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
rjh
  • 46,345
  • 3
  • 47
  • 60
  • 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. C – Gavin Brock Mar 27 '10 at 11:31
  • 2
    @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. – maxelost Mar 10 '16 at 23:40