views:

91

answers:

3

I need to create a "obscuring" function which replaces clear-text password in line, before writing it to log.

It looks like this:

function pass_obscure {
      my $logline = shift;
      my $pass = "wer32pass$";   # this password is an example, the real one is received as parameter, or already stored as global value

      $logline =~ s/$pass/*********/g;

      return $logline;
}

But this, of course, doesn't work. The '$' sign in the password string is interpolated as an endline character, so there's no match, and so replacement doesn't work.

How can I resolve this?

Thanks.

A: 

ok, sorry, already resolved. The solution, of course, is to use:

  my $pattern = quotemeta $pass;
  $logline =~ s/$pattern/********/g;

Thanks anyway

Alex
+7  A: 

(Why not just keep the password out of the log line in the first place?)

Use quotemeta:

$pass = "password\$";
$logline = "password is: password\$";

print "$pass\n";
print "$logline\n";
$pass_quoted = quotemeta($pass);

$logline =~ s/$pass_quoted/********/g;

print "$logline\n";

Outputs:

password$
password is: password$
password is: ********
MikeyB
Hi MikeyThanks for the answer, I didn't see it in time.Regarding your first question - it is not up to me. I run the command, which includes password, and I log it. So before I log the command, I want to replace the password with stars. :-)Thanks
Alex
Yeah, figured there was a sensible reason :)
MikeyB
+1  A: 

In interpolated strings,

\Qquotemeta
\Llc
\llcfirst
\Uuc
\uucfirst
\E → end of the case/quote modifier

Thus this is also a solution.

$logline =~ s/\Q$pass/********/g;
ephemient