Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Perl provides several functions for list manipulation. For instance, the map() function takes an expression or block, applies it to each element in a list, and returns the list of mapped elements. If it is given a block, the block is executed with $_ assigned to each element of the list in turn. The perlfunc manpage adds:

Note that $_ is an alias to the list value, so it can be used to modify the elements of the LIST. While this is useful and supported, it can cause bizarre results if the elements of LIST are not variables. Using a regular "foreach" loop for this purpose would be clearer in most cases.

...

Code Block
bgColor#ffcccc
langperl

open( PASSWD, "<", "/etc/passwd");
 or croak "error opening /etc/passwd: stopped"
my @users = <PASSWD>;
my @shell_users = grep +(s|/bin/sh||), @users;
foreach my $user (@shell_users) {
  print "Shell User: $user";
}

However, because the grep() block removes /bin/sh from any input line that contains it, it modifies the @users list so that no user has /bin/sh!

Compliant Solution (grep())

This compliant solution does the same thing but does not modify the the @users array array.

Code Block
bgColor#ccccff
langperl

open( PASSWD, "<", "/etc/passwd");
 or croak "error opening /etc/passwd: stopped"
my @users = <PASSWD>;
my @shell_users = grep +(m|/bin/sh|), @users;
foreach my $user (@shell_users) {
  $user =~= s|/bin/sh||;
  print "Shell User: $user";
}

...

Compliant Solution (apply())

This compliant solution does the same thing but uses List::MoreUtils::apply(), which guarantees not to modify its input list.

Code Block
bgColor#ccccff
langperl
open( PASSWD, "<", "/etc/passwd") or croak "error opening /etc/passwd: stopped"
my @users = <PASSWD>;
my @shell_users = List::MoreUtils::apply { s|/bin/sh|| } @users;
foreach my $user (@shell_users) {
  print "Shell User: $user";
}

Risk Assessment

Failure to handle error codes or other values returned by functions can lead to incorrect program flow and violations of data integrity.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

EXP34-PL

medium Medium

likely Likely

low Low

P6 P18

L2 L1

Automated Detection

Tool

Diagnostic

Perl::Critic

ControlStructures::ProhibitMutatingListFunctions

Bibliography

...

...

"List Processing Side Effects," p. 114
[

...

...

...

Bar, Graham. List::Utils
[CPAN]Kennedy, Adam. List::MoreUtils
[Wall 2011]perlfunc

 

...

Image Modified Image Modified Image Modified