Datasets:
language large_string | page_id int64 | page_url large_string | chapter int64 | section int64 | rule_id large_string | title large_string | intro large_string | noncompliant_code large_string | compliant_solution large_string | risk_assessment large_string | breadcrumb large_string |
|---|---|---|---|---|---|---|---|---|---|---|---|
perl | 88,890,518 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890518 | 3 | 2 | DCL00-PL | Do not use subroutine prototypes | Perl provides a simple mechanism for specifying subroutine argument types called prototypes. Prototypes appear to indicate the number and types of arguments that a function takes. For instance, this function appears to require two arguments, the first being a scalar, and the second being a list:
#ffcccc
perl
sub functi... | sub function ($@) {
my ($item, @list) = @_;
print "item is $item\n";
my $size = $#list + 1;
print "List has $size elements\n";
foreach my $element (@list) {
print "list contains $element\n";
}
}
my @elements = ("Tom", "Dick", "Harry");
function( @elements);
item is 3
List has 0 elements
## Noncompli... | sub function {
my ($item, @list) = @_;
print "item is $item\n";
my $size = $#list + 1;
print "List has $size elements\n";
foreach my $element (@list) {
print "list contains $element\n";
}
}
my @elements = ("Tom", "Dick", "Harry");
function( @elements);
item is Tom
List has 2 elements
list contains Di... | ## Risk Assessment
Subroutine prototypes do not provide compile-time type safety and can cause surprising program behavior.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
DCL00-PL
Low
Likely
Low
P9
L2 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL) |
perl | 88,890,482 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890482 | 3 | 2 | DCL01-PL | Do not reuse variable names in subscopes | Do not use the same variable name in two scopes where one scope is contained in another. For example,
A lexical variable should not share the name of a package variable if the lexical variable is in a subscope of the global variable.
A block should not declare a lexical variable with the same name as a lexical variable... | $errmsg = "Global error";
sub report_error {
my $errmsg = shift(@_);
# ...
print "The error is $errmsg\n";
};
report_error("Local error");
## Noncompliant Code Example
This noncompliant code example declares the
errmsg
identifier at file scope and reuses the same identifier to declare a string that is private ... | $global_error_msg = "Global error";
sub report_error {
my $local_error_msg = shift(@_);
# ...
print "The error is $local_error_msg\n";
};
report_error("Local error");
## Compliant Solution
## This compliant solution uses different, more descriptive variable names.
#ccccff
perl
$global_error_msg = "Global error... | ## Risk Assessment
Hiding variables in enclosing scopes can lead to surprising results.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
DCL01-PL
Low
Probable
Medium
P4
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL) |
perl | 88,890,481 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890481 | 3 | 2 | DCL02-PL | Any modified punctuation variable should be declared local | Perl has a large number of punctuation variables. They control the behavior of various operations in the Perl interpreter. Although they are initially set to reasonable default values, any Perl code has the ability to change their values for its own internal purposes. If a program modifies one of these variables, it is... | sub count_virtual_users {
my $result = 0;
$/ = ":";
open( PASSWD, "<", "/etc/passwd");
while (<PASSWD>) {
@items = split "\n";
foreach (@items) {
if ($_ eq "/usr/bin/false") {
$result++;
}
}
}
$result;
}
## Noncompliant Code Example
This noncompliant code example shows a sub... | sub count_virtual_users {
my $result = 0;
local $/ = ":";
open( PASSWD, "<", "/etc/passwd");
while (<PASSWD>) {
@items = split "\n";
foreach (@items) {
if ($_ eq "/usr/bin/false") {
$result++;
}
}
}
$result;
}
## Compliant Solution
This compliant solution again produces the ... | ## Risk Assessment
Modifying punctuation variables without declaring them local can corrupt data and create unexpected program behavior.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
DCL02-PL
Low
Probable
Medium
P4
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL) |
perl | 88,890,495 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890495 | 3 | 2 | DCL03-PL | Do not read a foreach iterator variable after the loop has completed | Perl's foreach loop will iterate over a list, assigning each value to
$_
. But if another variable is provided, it assigns the list elements to that variable instead. According to the
perlsyn
manpage, the foreach loop may be invoked with the
foreach
keyword or the
for
keyword. The foreach loop always localizes its iter... | my $value;
my @list = (1, 2, 3);
for $value (@list) {
if ($value % 2 == 0) {
last;
}
}
print "$value is even\n";
is even.
## Noncompliant Code Example
## This noncompliant code example iterates through a list, stopping when it finds an even number.
#ffcccc
perl
my $value;
my @list = (1, 2, 3);
for $value (... | my @list = (1, 2, 3);
for my $value (@list) {
if ($value % 2 == 0) {
print "$value is even\n";
last;
}
}
my @list = (1, 2, 3);
my $value;
for my $v (@list) {
if ($v % 2 == 0) {
$value = $v;
last;
}
}
print "$value is still even\n";
my @list = (1, 2, 3);
for ($value = 1; $value < 4; $value+... | ## Risk Assessment
Failure to localize iterators can lead to unexpected results.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
DCL03-PL
low
unlikely
low
P3
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL) |
perl | 88,890,491 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890491 | 3 | 2 | DCL04-PL | Always initialize local variables | When a package variable is declared
local
, it is often assumed that the package variable's contents are duplicated and stored in the local variable. This is not so; the local variable is set to
undef
, just like any other uninitialized variable. Consequently, local variables must be initialized. They may be initialize... | $passwd_required = 1;
# ...
sub authenticate_user {
local $passwd_required;
if (defined $passwd_required) {
print "Please enter a password\n";
# ... get and validate password
} else {
print "No password necessary\n";
}
}
authenticate_user();
## Noncompliant Code Example
This noncompliant code ex... | $passwd_required = 1;
# ...
sub authenticate_user {
local $passwd_required = $passwd_required;
if (defined $passwd_required) {
print "Please enter a password\n";
# ... get and validate password
} else {
print "No password necessary\n";
}
}
authenticate_user();
## Compliant Solution
This complian... | ## Risk Assessment
Uninitialized variables can cause surprising program behavior.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
DCL04-PL
Low
Probable
Medium
P4
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL) |
perl | 88,890,489 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890489 | 3 | 2 | DCL05-PL | Prohibit Perl4 package names | Perl 4 used
'
as a package name separator when importing packages. Perl 5 provides the same feature but uses
::
to separate package names. Use colons rather than single quotation marks to separate packages. | require DBI'SQL'Nano;
## Noncompliant Code Example
This noncompliant code example uses the Perl 4
'
syntax to import an external package. This code does successfully require the package, but because Perl 5 is over 15 years old, the Perl 4 syntax has largely been forgotten. Consequently, the code can be seen as confusi... | require DBI::SQL::Nano;
## Compliant Solution
## This compliant solution uses Perl 5's::syntax to import an external package:
#ccccff
perl
require DBI::SQL::Nano; | ## Risk Assessment
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
DCL05-PL
Low
Improbable
Low
P6
L2 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL) |
perl | 88,890,558 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890558 | 2 | 2 | DCL30-PL | Do not import deprecated modules | Over time, modules in Perl can become obsolete, or superseded by newer modules. Furthermore, d
espite being over 15 years old, Perl 5 continues to grow. Much of this growth comes from Perl's practice of assimilating popular CPAN modules into the core language. Modules that are not part of the core Perl language must b... | use UNIVERSAL qw(can); # deprecated
# ...
sub doit {
my ($func) = @_;
if (can($self, $func)) {
$self->$func();
}
# ...
}
## Noncompliant Code Example (Universal::can())
This noncompliant code example tries to see if an object supports a method. The
Universal::can()
method provides this capability. It w... | # use UNIVERSAL qw(can); # deprecated
# ...
sub doit {
my ($func) = @_;
if ($self->can($func)) {
$self->$func();
}
# ...
}
## Compliant Solution
## This compliant solution usesUniversal::can()without explicitly importing it.
#ccccff
perl
# use UNIVERSAL qw(can); # deprecated
# ...
sub doit {
my ($func... | ## Risk Assessment
Using deprecated or obsolete classes or methods in program code can lead to erroneous behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL30-PL
Medium
Likely
Yes
No
P12
L1 | SEI CERT Perl Coding Standard > 2 Rules > Rule 02. Declarations and Initialization (DCL) |
perl | 88,890,556 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890556 | 2 | 2 | DCL31-PL | Do not overload reserved keywords or subroutines | Perl has a large number of built-in functions; they are described on the
perlfunc
manpage [
Wall 2011
]. Perl also has a handful of reserved keywords such as
while
; they are described on the
perlsyn
manpage [
Wall 2011
].
Do not use an identifier for a subroutine that has been reserved for a built-in function or keywo... | sub open {
my ($arg1, $arg2, $arg3) = @_;
print "arg1 = $arg1\n";
print "arg2 = $arg2\n";
print "arg3 = $arg3\n";
}
open( my $input, "<", "foo.txt"); # What does this do?
## Noncompliant Code Example
## This noncompliant code example codes a subroutine calledopen(), which clashes with theopen()built-in fu... | sub my_open {
my ($arg1, $arg2, $arg3) = @_;
print "arg1 = $arg1\n";
print "arg2 = $arg2\n";
print "arg3 = $arg3\n";
}
my_open( my $input, "<", "foo.txt");
## Compliant Solution
## This compliant solution uses a different name for its subroutine; consequently, it behaves as expected.
#ccccff
perl
sub my_open ... | ## Risk Assessment
Using reserved keywords can lead to unexpected program behavior and surprising results.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL31-PL
Low
Probable
Yes
No
P4
L3 | SEI CERT Perl Coding Standard > 2 Rules > Rule 02. Declarations and Initialization (DCL) |
perl | 88,890,513 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890513 | 2 | 2 | DCL33-PL | Declare identifiers before using them | Perl provides the
my()
and
our()
functions specifically for declaring variables.
However, Perl allows any variable to be referenced, even if it is not declared or initialized. If an uninitialized value is requested, Perl supplies a default
undef
value. Depending on the context, the
undef
value may be interpreted as 0,
... | my $result = compute_number();
print "The result is $reuslt\n"; # oops!
The result is
## Noncompliant Code Example
## This noncompliant code example contains a typo in itsprintstatement.
#ffcccc
perl
my $result = compute_number();
print "The result is $reuslt\n"; # oops!
It causes the program to print the followi... | my $result = compute_number();
print "The result is $result\n";
## Compliant Solution
## This compliant solution corrects the typo, causing the program to correctly print the result ofcompute_number().
#ccccff
perl
my $result = compute_number();
print "The result is $result\n"; | ## Risk Assessment
Using undeclared variables usually can lead to incorrect results and surprising program behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL33-PL
Low
Probable
Yes
Yes
P6
L2 | SEI CERT Perl Coding Standard > 2 Rules > Rule 02. Declarations and Initialization (DCL) |
perl | 88,890,515 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890515 | 3 | 3 | EXP00-PL | Do not return undef | Perl expressions can be interpreted in either scalar or list context, depending on the syntactic placement of the expression. Many functions are designed to return only a scalar or only a list. Many built-in functions can be called in both contexts, and they may return differing values for each. Furthermore, any functi... | sub read_users {
open( my $filehandle, "<", "/etc/shadow")
or return undef;
my @users = <$filehandle>;
return @users;
}
# ...
if (my @users = read_users($filename)) {
print "Your system has $#users users\n";
# process users
} else {
croak "Cannot read shadow file";
}
Your system has 0 users
## Nonco... | sub read_users {
open( my $filehandle, "<", "/etc/shadow")
or return;
my @users = <$filehandle>;
return @users;
}
## Compliant Solution
This compliant solution uses a blank
return
rather than returning
undef
. Because a blank return is always interpreted as false in list or scalar context, the program will p... | ## Risk Assessment
Improper interpretation of
return undef
can lead to incorrect program flow.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
EXP00-PL
Low
Unlikely
Low
P3
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP) |
perl | 88,890,490 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890490 | 3 | 3 | EXP01-PL | Do not depend on the return value of functions that lack a return statement | All Perl subroutines may be used in an expression as if they returned a value, but Perl subroutines are not required to have an explicit return statement. If control exits a subroutine by some means other than an explicit return statement, then the value actually returned is the last value computed within the subroutin... | package Bank;
# ...
sub deposit {
my ($amount, $account, $pin) = @_;
my $good_pin = _get_pin( $account);
if ($pin == $good_pin) {
my $balance = _get_balance( $account);
_set_balance( $account, $amount + $balance);
} else {
my $failed = $good_pin;
}
}
## Noncompliant Code Example
## This noncompl... | sub deposit {
my ($amount, $account, $pin) = @_;
my $good_pin = _get_pin( $account);
if ($pin == $good_pin) {
my $balance = _get_balance( $account);
_set_balance( $account, $amount + $balance);
} else {
my $failed = $good_pin;
}
return;
}
## Compliant Solution
This compliant solution adds a tri... | ## Risk Assessment
An attempt to read the return value of a function that did not return any value can cause data encapsulated by the function to leak.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
EXP01-PL
Medium
Likely
Low
P18
L1 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP) |
perl | 88,890,552 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890552 | 3 | 3 | EXP03-PL | Do not diminish the benefits of constants by assuming their values in expressions | If a constant value is given for an identifier, do not diminish the maintainability of the code in which it is used by assuming its value in expressions. Simply giving the constant a name is not enough to ensure modifiability; you must be careful to always use the name, and remember that the value can change. | our $BufferSize = 512;
# ...
my $nblocks = 1 + (($nbytes - 1) >> 9); # because $BufferSize = 512 = 2^9
## Noncompliant Code Example
This noncompliant example first provides a constant value
$BufferSize
set to 512. This constant can later be used to buffer data read in from a file. But the code example defeats the pu... | my $nblocks = 1 + (($nbytes - 1) / $BufferSize;
## Compliant Solution
## This compliant solution uses the identifier assigned to the constant value in the expression.
#ccccff
perl
my $nblocks = 1 + (($nbytes - 1) / $BufferSize; | ## Risk Assessment
Assuming the value of an expression diminishes the maintainability of code and can produce unexpected behavior under any circumstances in which the constant changes.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
EXP03-PL
low
unlikely
medium
P2
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP) |
perl | 88,890,551 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890551 | 3 | 3 | EXP04-PL | Do not mix the early-precedence logical operators with late-precedence logical operators | Perl provides three logical operators:
&&
,
||
, and
!
, and they have the same meaning as in C.
Perl also provides three alternative logical operators:
and
,
or
, and
not
. They have the same meanings as
&&
,
||
, and
!
. They have much lower binding precedence, which makes them useful for control flow [
Wall 2011
]. ... | if (not -f $file) {
if (not -f $file || -w $file) {
if (not (-f $file || -w $file)) {
if ((not -f $file) || -w $file) {
## Noncompliant Code Example
This noncompliant code example checks a file for suitability as an output file. It does this by checking to see that the file does not exist.
perl
if (not -f $file) {
... | if (! -f $file || -w $file) {
if (not -f $file or -w $file) {
## Compliant Solution
This compliant solution uses the
!
operator in conjunction with the
||
operator. This code has the desired behavior of determining if a file either does not exist or does exist but is overwritable.
#ccccff
perl
if (! -f $file || -w $f... | ## Risk Assessment
Mixing early-precedence operators with late-precedence operators can produce code with unexpected behavior.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
EXP04-PL
Low
Unlikely
Low
P3
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP) |
perl | 88,890,557 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890557 | 3 | 3 | EXP06-PL | Do not use an array in an implicit scalar context | Perl has two contexts in which expressions can be evaluated: scalar and list. These contexts determine what the expression generates. It is recommended that the context be made explicit when an expression is evaluated in an unexpected context. Implicit context switching makes programs difficult to read and more error p... | sub print_array {
my $array = shift;
print "( ";
foreach $item (@{$array}) {
print "$item , ";
}
print ")\n";
}
my @array; # initialize
my $array_ref = @array;
print_array( $array_ref);
my @array; # initialize
my $cardinality = @array;
print "The array has $cardinality elements\n";
## Noncompliant Code... | my $array_ref = \@array;
print_array( $array_ref);
my $cardinality = scalar( @array);
print "The array has $cardinality elements\n";
my $cardinality = $#array + 1;
print "The array has $cardinality elements\n";
## Compliant Solution
## This compliant solution initializes$array_refcorrectly.
#ccccff
perl
my $array_re... | ## Risk Assessment
Evaluating an array or hash in improper contexts can lead to unexpected and surprising program behavior.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
EXP06-PL
low
unlikely
medium
P2
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP) |
perl | 88,890,539 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890539 | 3 | 3 | EXP07-PL | Do not modify $_ in list or sorting functions | 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 ad... | 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";
}
## Noncompliant Code Example (grep())
## This noncompliant code example reads the/etc/passwdfile and list... | 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";
}
open( PASSWD, "<", "/etc/passwd") or croak "error opening /etc/passwd: stopped"
my... | ## 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
EXP07-PL
Medium
Likely
Low
P18
L1 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP) |
perl | 88,890,520 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890520 | 3 | 3 | EXP08-PL | Do not use the one-argument form of select() | Perl has three
select()
functions with widely differing purposes. One form takes four arguments and is a wrapper around the POSIX
select(3)
call. A second form takes zero arguments and returns the currently selected file handle: the handle of the output stream used by
print
; it normally defaults to standard output. Th... | sub output_log {
my $action = shift;
open( my $log, ">>", "log.txt");
select( $log);
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$year += 1900;
$mon += 1;
print "$year-$mon-$mday $hour:$min:$sec: $action\n";
}
# ...
print "Hello!\n";
output_log("Greeted user");
print "How ar... | sub output_log {
my $action = shift;
open( my $log, ">>", "log.txt");
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$year += 1900;
$mon += 1;
print $log "$year-$mon-$mday $hour:$min:$sec: $action\n";
}
use IO::Handle;
# ...
$log->autoflush();
## Compliant Solution
## This compli... | ## 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
Detectable
Repairable
Priority
Level
EXP08-PL
Medium
Unlikely
Yes
No
P4
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP) |
perl | 88,890,531 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890531 | 2 | 3 | EXP30-PL | Do not use deprecated or obsolete functions or modules | Do not use deprecated or obsolescent functions when more secure equivalent functions are available.
Here is a list of deprecated functions along with their recommended alternatives if available:
Deprecated
Preferred
die()
Carp::croak()
warn()
Carp::carp()
-t
IO::Interactive
format()
Template
,
Perl6::Form
The following... | my $file;
open(FILE, "<", $file) or die "error opening $file: stopped";
# work with FILE
## Noncompliant Code Example (die())
## This noncompliant code example tries to open a file and invokes the obsoletedie()method if it fails.
#ffcccc
perl
my $file;
open(FILE, "<", $file) or die "error opening $file: stopped";
# wo... | use Carp;
my $file;
open(FILE, "<", $file) or croak "error opening $file: stopped";
# work with FILE
## Compliant Solution (croak())
## This compliant solution uses thecroak()function instead ofdie().
#ccccff
perl
use Carp;
my $file;
open(FILE, "<", $file) or croak "error opening $file: stopped";
# work with FILE
Unl... | ## Risk Assessment
Using deprecated or obsolete classes or methods in program code can lead to erroneous behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP30-PL
Medium
Probable
Yes
No
P8
L2 | SEI CERT Perl Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
perl | 88,890,500 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890500 | 2 | 3 | EXP31-PL | Do not suppress or ignore exceptions | The
perlfunc
manpage says, with regard to the built-in
eval forms
,
If there is a syntax error or runtime error, or a "die" statement is executed, "eval" returns an undefined value in scalar context or an empty list in list context, and $@ is set to the error message. If there was no error, $@ is guaranteed to be the e... | my ($a, $b) = # initialize
my $answer;
eval { $answer = $a / $b };
print "The quotient is $answer\n";
## Noncompliant Code Example
This noncompliant code example uses the
eval
built-in form to divide two numbers. Without using
eval
, the code would abort if
$b
happened to be 0, but thanks to
eval
, code processing can... | my ($a, $b) = # initialize
my $answer;
if (! eval { $answer = $a / $b }) {
carp($@) if $@;
$answer = 0;
}
print "The quotient is $answer\n";
## Compliant Solution
## This compliant solution checks to see ifevalfailed and, if so, emits a warning message and initializes$answer.
#ccccff
perl
my ($a, $b) = # initializ... | ## Risk Assessment
Suppressing exceptions can result in inconsistent program state and erroneous behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP31-PL
Low
Probable
Yes
No
P4
L3 | SEI CERT Perl Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
perl | 88,890,503 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890503 | 2 | 3 | EXP32-PL | Do not ignore function return values | Many functions return useful values whether or not the function has side effects. In most cases, this value signifies whether the function successfully completed its task or if some error occurred. Other times, the value is the result of some computation and is an integral part of the function's API.
Because a return v... | my $source;
open(my $SOURCE, "<", $source);
@lines = (<$SOURCE>);
close($SOURCE);
## Noncompliant Code Example
## This noncompliant code example opens a file, reads in its information, and closes it again.
#ffcccc
perl
my $source;
open(my $SOURCE, "<", $source);
@lines = (<$SOURCE>);
close($SOURCE);
It makes sure the ... | my $source;
open(my $SOURCE, "<", $source) or croak "error opening $source: $!";
@lines = (<$SOURCE>);
close($SOURCE) or croak "error closing $source: $!";
## Compliant Solution
## This compliant solution does the same thing but provides useful error messages if anything goes wrong.
#ccccff
perl
my $source;
open(my $S... | ## Risk Assessment
Failure to handle error codes or other values returned by functions can lead to incorrect program flow and violations of data integrity.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP32-PL
Medium
Probable
No
No
P4
L3 | SEI CERT Perl Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
perl | 88,890,544 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890544 | 2 | 3 | EXP33-PL | Do not invoke a function in a context for which it is not defined | Perl functions can be invoked in two contexts: list and scalar. These contexts indicate what is to be done with the return value. Functions can return different values in list context than in scalar context. For instance, the
grep()
function takes a list and a block or expression and filters out elements of the list fo... | sub ret {
my $list = shift;
my @list = @{$list};
# ...
return sort @list;
}
my @list = ( "foo", "bar", "baz");
my $result = ret @list;
## Noncompliant Code Example (sort())
## This noncompliant code example inadvertently assigns a scalar to the result of thesort()function.
#ffcccc
perl
sub ret {
my $list = sh... | sub ret {
my $list = shift;
my @list = @{$list};
# ...
return sort @list;
}
my @list = ( "foo", "bar", "baz");
my @result = ret @list;
## Compliant Solution (sort())
## This compliant solution guarantees that theret()function is called only in list context.
#ccccff
perl
sub ret {
my $list = shift;
my @list = ... | ## Risk Assessment
Using an unspecified value can lead to erratic program behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP33-PL
Medium
Unlikely
Yes
No
P4
L3 | SEI CERT Perl Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
perl | 88,890,572 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890572 | 2 | 3 | EXP35-PL | Use the correct operator type for comparing values | Perl provides two sets of comparison operators: one set for working with numbers and one set for working with strings.
Numbers
Strings
==
eq
!=
ne
<
lt
<=
le
>
gt
>=
ge
<=>
cmp
Do not use the number comparison operators on nonnumeric strings. Likewise, do not use the string comparison operators on numbers. | my $num = 2;
print "Enter a number\n";
my $user_num = <STDIN>;
chomp $user_num;
if ($num eq $user_num) {print "true\n"} else {print "false\n"};
sub check_password {
my $correct = shift;
my $password = shift;
# encrypt password
if ($password == $correct) {
return true;
} else {
return false;
}
}
##... | my $num = 2;
print "Enter a number\n";
my $user_num = <STDIN>;
chomp $user_num;
if ($num == $user_num) {print "true\n"} else {print "false\n"};
sub check_password {
my $correct = shift;
my $password = shift;
# encrypt password
if ($password eq $correct) {
return true;
} else {
return false;
}
}
##... | ## Risk Assessment
Confusing the string comparison operators with numeric comparison operators can lead to incorrect program behavior or incorrect program data.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP35-PL
Low
Likely
Yes
No
P6
L2 | SEI CERT Perl Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
perl | 88,890,535 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890535 | 3 | 7 | FIO00-PL | Do not use bareword file handles | File handles are traditionally package variables that represent file descriptors. Unlike other variables, file handles are typically not prefixed with punctuation. All barewords are subject to being interpreted by the parser differently than the developer intended, but bareword file handles are particularly fraught wit... | open( GOOD, "<", "good.txt");
my $good_data = <GOOD>;
print "GOOD: $good_data";
print "\n";
{
open( BAD, "<", "bad.txt");
my $bad_data = <BAD>;
print "BAD: $bad_data";
print "\n";
}
my $more_good_data = <GOOD>;
print "MORE GOOD: $more_good_data";
sub BAD {return GOOD;}
## Noncompliant Code Example
Suppose we ... | sub BAD {return GOOD;}
open( my $GOOD, "<", "good.txt");
my $good_data = <$GOOD>;
print "GOOD: $good_data";
print "\n";
{
open( my $BAD, "<", "bad.txt");
my $bad_data = <$BAD>;
print "BAD: $bad_data";
print "\n";
}
my $more_good_data = <$GOOD>;
print "MORE GOOD: $more_good_data";
## Compliant Solution
## This... | ## Risk Assessment
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
FIO00-PL
medium
probable
low
P12
L1 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 07. File Input and Output (FIO) |
perl | 88,890,565 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890565 | 3 | 7 | FIO01-PL | Do not operate on files that can be modified by untrusted users | Multiuser systems allow multiple users with different privileges to share a file system. Each user in such an environment must be able to determine which files are shared and which are private, and each user must be able to enforce these decisions.
Unfortunately, a wide variety of file system vulnerabilities can be exp... | use Carp;
my $file = # provided by user
open( my $in, "<", $file) or croak "error opening $file";
# ... work with FILE and close it
use Carp;
use Fcntl ':mode';
my $path = $ARGV[0]; # provided by user
# Check that file is regular
my $mode = (stat($path))[2] or croak "Can't run stat";
croak "Not a regular file" if (S... | use Carp;
use Fcntl ':mode';
# Fail if symlinks nest more than this many times
my $max_symlinks = 5;
# Indicates if a particular path is secure, including that parent directories
# are secure. If path contains symlinks, ensures symlink targets are also secure
# Path need not be absolute and can have trailing /.
sub i... | ## Risk Assessment
Performing operations on files in shared directories can result in DoS attacks. If the program has elevated privileges, privilege escalation exploits are possible.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
FIO01-PL
Medium
Unlikely
Medium
P4
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 07. File Input and Output (FIO) |
perl | 88,890,529 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890529 | 2 | 7 | FIO30-PL | Use compatible character encodings when performing network or file I/O | This rule is a stub. | ## Noncompliant Code Example
## This noncompliant code example shows an example where ...
#FFCCCC | ## Compliant Solution
## In this compliant solution, ...
#CCCCFF | ## Risk Assessment
Leaking sensitive information outside a trust boundary is not a good idea.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO30-PL
Low
Unlikely
No
No
P1
L3 | SEI CERT Perl Coding Standard > 2 Rules > Rule 07. File Input and Output (FIO) |
perl | 88,890,553 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890553 | 3 | 1 | IDS00-PL | Canonicalize path names before validating them | A file path is a string that indicates how to find a file, starting from a particular directory. If a path begins with the root directory or with a root volume (e.g.,
C:
in Windows), it is an
absolute
path; otherwise, it is a
relative
path.
Absolute or relative path names may contain file links such as symbolic (soft) ... | sub work_with_image {
my ($image_file) = @_; # untrusted
open( my $image, "<", "/img/$image_file") or croak "Can't open image file";
# ...
}
use File::PathConvert qw(realpath $resolved);
sub work_with_image {
my ($image_file) = @_; # untrusted
$image_file = realpath("/img/$image_file") || croak "Resolution ... | use Cwd 'abs_path';
sub work_with_image {
my ($image_file) = @_; # untrusted
$image_file = abs_path("/img/$image_file");
if ($image_file !~ m|/img/|) {
croak "Image file not in /img";
}
open( my $image, "<", $image_file) or croak "Can't open $image_file";
# ...
}
use Cwd 'abs_path';
my $DIR_SEP = "/"... | ## Risk Assessment
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
IDS00-PL
medium
unlikely
medium
P4
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 01. Input Validation and Data Sanitization (IDS) |
perl | 88,890,488 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890488 | 3 | 1 | IDS01-PL | Use taint mode while being aware of its limitations | Perl provides a feature called
taint mode
, which is a simple model for detecting data flow vulnerabilities such as SQL injection. When active, all scalar values are associated with a taint flag, and so they can be considered "tainted" or "untainted." Taint can propagate from variables to other variables in an expressi... | use CGI qw(:standard);
print header;
print start_html('A Simple Example'),
h1('A Simple Example'),
start_form, # Line A
"What's your name? ",textfield('name'), # Line B
submit,
end_form,
hr;
if (param()) {
print "Your name is: ",em(param('name')), # Line C
... | null | ## Risk Assessment
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
IDS01-PL
Medium
Probable
Medium
P8
L2 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 01. Input Validation and Data Sanitization (IDS) |
perl | 88,890,537 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890537 | 2 | 1 | IDS30-PL | Exclude user input from format strings | Never call any formatted I/O function with a format string containing user input.
An attacker who can fully or partially control the contents of a format string can crash the Perl interpreter or cause a denial of service. She can also modify values, perhaps by using the
%n||
conversion specifier, and use these values t... | my $host = `hostname`;
chop($host);
my $prompt = "$ENV{USER}\@$host";
sub validate_password {
my ($password) = @_;
my $is_ok = ($password eq "goodpass");
printf "$prompt: Password ok? %d\n", $is_ok;
return $is_ok;
};
if (validate_password( $ARGV[0])) {
print "$prompt: access granted\n";
} else {
print "$... | sub validate_password {
my ($password) = @_;
my $is_ok = ($password eq "goodpass");
print "$prompt: Password ok? $is_ok\n";
return $is_ok;
};
# ...
## Compliant Solution (print())
## This compliant solution avoids the use ofprintf(), sinceprint()provides sufficient functionality.
#ccccff
perl
sub validate_pas... | ## Risk Assessment
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS30-PL
high
probable
Yes
No
P12
L1 | SEI CERT Perl Coding Standard > 2 Rules > Rule 01. Input Validation and Data Sanitization (IDS) |
perl | 88,890,543 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890543 | 2 | 1 | IDS31-PL | Do not use the two-argument form of open() | The Perl
open()
function has several forms. The
perlfunc(1)
manpage lists the following:
open FILEHANDLE,EXPR
open FILEHANDLE,MODE,EXPR
open FILEHANDLE,MODE,EXPR,LIST
open FILEHANDLE,MODE,REFERENCE
open FILEHANDLE
Opens the file whose file name is given by EXPR and associates it with FILEHANDLE.
If the
MODE
argument is... | my $filename = # initialize
open(my $FILE, $filename) or croak("file not found");
while (<$FILE>) {
print "$filename: $_";
};
my $filename = # initialize
open(my $FILE, "<$filename") or croak("file not found");
while (<$FILE>) {
print "$filename: $_";
};
while (<ARGV>) {
print ":: $_";
};
while (<>) {
print ... | my $filename = # initialize
open(my $FILE, "<", $filename) or croak("file not found");
while (<$FILE>) {
print "$filename: $_";
};
while (<<>>) {
print ":: $_";
};
## Compliant Solution
## This compliant solution invokesopen()with three arguments rather than two.
#ccccff
perl
my $filename = # initialize
open(my $... | ## Risk Assessment
Failure to handle error codes or other values returned by functions can lead to incorrect program flow and violations of data integrity.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS31-PL
high
likely
Yes
No
P18
L1 | SEI CERT Perl Coding Standard > 2 Rules > Rule 01. Input Validation and Data Sanitization (IDS) |
perl | 88,890,574 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890574 | 2 | 1 | IDS32-PL | Validate any integer that is used as an array index | Perl, unlike most other languages, uses arrays that are not declared with a particular length and that may grow and shrink in size as is required by subsequent code. In fact, when assigning a value to an element within the array, if the index provided is beyond the end of the array, the array grows to make it valid. Co... | my @users;
while (<STDIN>) {
my ($username, $dummy, $uid) = split( /:/);
if (not (defined( $uid) and defined( $username))) {next;}
if (not $uid =~ /^\d*$/) {next;}
$users[$uid] = $username;
}
# ... Work with @users
## Noncompliant Code Example
This noncompliant code example takes a set of users via standard ... | my @users;
my $max_uid = 10000;
while (<STDIN>) {
my ($username, $dummy, $uid) = split( /:/);
if (not (defined( $uid) and defined( $username))) {next;}
if (not $uid =~ /^\d*$/) {next;}
if ($uid > $max_uid) {next;}
$users[$uid] = $username;
}
# ... Work with @users
## Compliant Solution
This compliant solut... | ## Risk Assessment
Using unsanitized array index values may exhaust memory and cause the program to terminate or hang.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS32-PL
low
likely
No
No
P3
L3 | SEI CERT Perl Coding Standard > 2 Rules > Rule 01. Input Validation and Data Sanitization (IDS) |
perl | 88,890,538 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890538 | 2 | 1 | IDS33-PL | Sanitize untrusted data passed across a trust boundary | Many programs accept untrusted data originating from arbitrary users, network connections, and other untrusted sources and then pass the (modified or unmodified) data across a trust boundary to a different trusted domain. Frequently the data is in the form of a string with some internal syntactic structure, which the s... | use CGI qw(:standard);
print header;
print start_html('A Simple Example'),
h1('A Simple Example'),
start_form,
"What's your name? ",textfield('name'),
submit,
end_form,
hr;
if (param()) {
print "Your name is: ",em(param('name')),
hr;
}
print end_html;
## Noncompliant Code Example (XSS)
This noncomp... | # rest of code unchanged
if (param()) {
print "Your name is: ", em(escapeHTML(param('name'))),
hr;
}
print end_html;
SELECT * FROM Users WHERE userid='<USERID>' AND
password='<PASSWORD>'
validuser' OR '1'='1
SELECT * FROM Users WHERE userid='validuser' OR '1'='1' AND password=<PAS... | ## Risk Assessment
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS33-PL
High
Likely
No
No
P9
L2 | SEI CERT Perl Coding Standard > 2 Rules > Rule 01. Input Validation and Data Sanitization (IDS) |
perl | 88,890,567 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890567 | 2 | 1 | IDS34-PL | Do not pass untrusted, unsanitized data to a command interpreter | External programs are commonly invoked to perform a function required by the overall system. This is a form of reuse and might even be considered a crude form of component-based software engineering. Command and argument injection vulnerabilities occur when an application fails to sanitize untrusted input and uses it i... | my $dir = $ARGV[0];
open( my $listing, "-|", "ls -F $dir") or croak "error executing command: stopped";
while (<$listing>) {
print "Result: $_";
}
close( $listing);
% ./sample.pl ~
Result: bin/
Result: Desktop/
Result: src/
Result: workspace/
%
% ./example.pl "dummy ; echo bad"
ls: cannot access dummy: No such file... | my $file;
my $dir = $ARGV[0];
croak "Argument contains unsanitary characters, stopped" if ($dir =~ m|[^-A-Za-z0-9_/.~]|);
open( my $listing, "-|", "ls -F $dir") or croak "error executing command: stopped";
while (<$listing>) {
print "Result: $_";
}
close( $listing);
% ./example.pl "dummy ; echo bad"
Argument contain... | ## Risk Assessment
Using deprecated or obsolete classes or methods in program code can lead to erroneous behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS34-PL
High
Probable
No
No
P6
L2 | SEI CERT Perl Coding Standard > 2 Rules > Rule 01. Input Validation and Data Sanitization (IDS) |
perl | 88,890,566 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890566 | 2 | 1 | IDS35-PL | Do not invoke the eval form with a string argument | Perl's
eval
built-in form provides programs with access to Perl's internal parser and evaluator. It may be called with a scalar argument (that is, a string) or with an expression that evaluates to a scalar argument, or it may be called with a block.
The
eval
built-in has one important role. It traps any errors that wou... | my $a = $ARGV[0];
my $b = $ARGV[1];
my $answer = 0;
eval qq{ \$answer = $a / $b };
carp $@ if $@;
print "The quotient is $answer\n";
% ./divide.pl 18 3
The quotient is 6
%
% ./divide.pl 18 0
Illegal division by zero at (eval 1) line 1.
The quotient is 0
%
% ./divide.pl 18 '6 ; print "Surprise!\n"'
Surprise!
The qu... | my $a = $ARGV[0];
my $b = $ARGV[1];
my $answer = 0;
eval { $answer = $a / $b; };
carp $@ if $@;
print "The quotient is $answer\n";
% ./divide.pl 18 3
The quotient is 6
% ./divide.pl 18 0
Illegal division by zero at ./divide.pl line 12.
The quotient is 0
% ./divide.pl 18 '6 ; print "Surprise!\n"'
Argument "6 ; print "S... | ## Risk Assessment
Using string-based
eval
can lead to arbitrary code execution.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
IDS35-PL
high
likely
Yes
No
P18
L1 | SEI CERT Perl Coding Standard > 2 Rules > Rule 01. Input Validation and Data Sanitization (IDS) |
perl | 88,890,484 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890484 | 3 | 4 | INT00-PL | Do not prepend leading zeroes to integer literals | When representing numeric literal values, Perl has a simple rule: integers that are prefixed with one or more leading zeroes are interpreted as octal, and integers with no leading zero are interpreted as decimal.
While simple, this rule is not known among many developers and is not obvious to those unaware of it. Conse... | null | null | ## Risk Assessment
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
INT00-PL
low
probable
medium
P4
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
perl | 88,890,486 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890486 | 3 | 4 | INT01-PL | Use small integers when precise computation is required | Perl does not distinguish between integer and floating-point numbers when doing arithmetic. Machine Arithmetic where the operands and the result are all integral is accurate as long as all values can be properly represented by the platform. Unfortunately, floating-point arithmetic is inherently imprecise, and can trip ... | my $x = 10000000000000000; # 1e+16
for (my $y = $x; $y <= $x + 5; $y += 1) {
print "$y\n";
}
## Noncompliant Code Example
## This noncompliant code example appears to print ten very large numbers, and on 64-bit machines, it indeed does so.
However, when run on a 32-bit machine, the loop will never terminate. This i... | my $x = 10000000000000000; # 1e+16
for (my $y = 0; $y <= 5; $y += 1) {
my $z = $x + $y;
print "$z\n";
}
use bignum;
my $x = 10000000000000000; # 1e+16
for (my $y = $x; $y <= $x + 5; $y += 1) {
print "$y\n";
}
## Compliant Solution
This compliant solution ensures that the loop counter computation involves numb... | ## Risk Assessment
Failing to understand the limitations of floating-point numbers can result in unexpected computational results and exceptional conditions, possibly resulting in a violation of data integrity.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
INT01-PL
medium
probable
high
P4
L3
Biblio... | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
perl | 88,890,576 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890576 | 3 | 50 | MSC00-PL | Detect and remove dead code | Code that is never executed is known as
dead code
. Typically, the presence of dead code indicates that a logic error has occurred as a result of changes to a program or the program's environment. To improve readability and ensure that logic errors are resolved, dead code should be identified, understood, and eliminate... | sub fix_name {
my $name = shift;
if ($name eq "") {
return $name;
}
$name =~ s/^([a-z])/\U$1\E/g;
$name =~ s/ ([a-z])/ \U$1\E/g;
if (length( $name) == 0) {
die "Invalid name"; # cannot happen
}
return $name;
}
## Noncompliant Code Example
## This noncompliant code example contains code that c... | sub fix_name {
my $name = shift;
$name =~ s/^([a-z])/\U$1\E/g;
$name =~ s/ ([a-z])/ \U$1\E/g;
if (length( $name) == 0) {
die "Invalid name"; # cannot happen
}
return $name;
}
## Compliant Solution
## This compliant solution makes the dead code reachable.
#ccccff
perl
sub fix_name {
my $name = shift;
... | ## Risk Assessment
The presence dead code may indicate logic errors that can lead to unintended program behavior. As a result, resolving dead code can be an in-depth process requiring significant analysis.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
MSC00-PL
low
unlikely
high
P1
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 50. Miscellaneous (MSC) |
perl | 88,890,483 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890483 | 3 | 50 | MSC01-PL | Detect and remove unused variables | The presence of unused variables may indicate significant logic errors. To prevent such errors, unused values should be identified and removed from code. | sub fix_name {
my $name = shift;
my $new_name = $name;
$name =~ s/^([a-z])/\U$1\E/g;
$name =~ s/ ([a-z])/ \U$1\E/g;
return $name;
}
## Noncompliant Code Example
## This noncompliant code example contains a variable$new_namethat is initialized but never subsequently read.
#ffcccc
perl
sub fix_name {
my $name... | sub fix_name {
my $name = shift;
$name =~ s/^([a-z])/\U$1\E/g;
$name =~ s/ ([a-z])/ \U$1\E/g;
return $name;
}
## Compliant Solution
## This compliant solution eliminates the unused variable
#ccccff
perl
sub fix_name {
my $name = shift;
$name =~ s/^([a-z])/\U$1\E/g;
$name =~ s/ ([a-z])/ \U$1\E/g;
return $name;... | ## Risk Assessment
The presence of unused variables may indicate logic errors that can lead to unintended program behavior. As a result, resolving unused variables can be an in-depth process requiring significant analysis.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
MSC01-PL
Low
Unlikely
High
P1
... | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 50. Miscellaneous (MSC) |
perl | 88,890,577 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890577 | 3 | 50 | MSC02-PL | Run programs with full warnings and strict checking | Perl provides several mechanisms for warning the user about potential problems with the program. The
use warnings
pragma turns on a default set of warnings for the Perl runtime to produce should it detect questionable code. The
-w
command-line argument serves the same purpose. It is considered so useful that the
perl(1... | use warnings;
use strict;
my %days = ("Sunday" => 'pray',
"Monday" => 'work',
"Tuesday" => 'work',
"Wednesday" => 'work',
"Thursday" => 'work',
"Friday" => 'work',
"Saturday" => 'rest');
sub what_to_do {
my $day = shift;
if ($day... | sub what_to_do {
my $day = shift;
no warnings 'uninitialized';
if ($days{$day} eq 'work') {
return 'work hard';
}
if (exists $days{$day}) {
return $days{$day};
} else {
return "do nothing";
}
}
sub what_to_do {
my $day = shift;
no warnings 'uninitialized';
no strict 'refs';
if ($$day ... | ## Risk Assessment
Suppressing warnings can mask problems that would otherwise be quickly recognized and fixed.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
MSC02-PL
Low
Unlikely
Medium
P2
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 50. Miscellaneous (MSC) |
perl | 88,890,498 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890498 | 3 | 50 | MSC03-PL | Do not use select() to sleep | This rule is a stub. | ## Noncompliant Code Example
## This noncompliant code example shows an example where ...
#FFCCCC | ## Compliant Solution
## In this compliant solution, ...
#CCCCFF | ## Risk Assessment
Leaking sensitive information outside a trust boundary is not a good idea.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
MSC03-PL
Low
Unlikely
Low
P3
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 50. Miscellaneous (MSC) |
perl | 88,890,487 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890487 | 3 | 50 | MSC04-PL | Do not use comma to separate statements | Perl's comma operator
,
performs several duties. The most widely known duty is to serve as a list separator:
my @list = (2, 3, 5, 7);
Outside of list context, the comma can also be used to combine multiple expressions into one statement. Each expression is evaluated, and its result is discarded. The last expression's r... | sub validate_file {
my $file = shift(@_);
if (-e $file) {
return 1; # file exists
}
die "$file does not exist";
}
my $file = $ARGV[0];
validate_file($file), print "hi!\n";
print validate_file($file), "hi!\n";
## Noncompliant Code Example
This code example validates a file and indicates if it exists.
#ffc... | validate_file($file);
print "hi!\n";
print do { validate_file($file); "hi!\n"};
## Compliant Solution (Segregation)
## This compliant solution segregates the call tovalidate_fileinto a separate statement.
#ccccff
perl
validate_file($file);
print "hi!\n";
## Compliant Solution (do)
If multiple functions must be invoke... | ## Risk Assessment
Using commas to separate statements can lead to unexpected program behavior and surprising results.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
MSC04-PL
Low
Probable
Medium
P4
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 50. Miscellaneous (MSC) |
perl | 88,890,528 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890528 | 2 | 50 | MSC31-PL | Do not embed global statements | This rule is a stub. | ## Noncompliant Code Example
## This noncompliant code example shows an example where ...
#FFCCCC | ## Compliant Solution
## In this compliant solution, ...
#CCCCFF | ## Risk Assessment
Leaking sensitive information outside a trust boundary is not a good idea.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
MSC31-PL
Low
Unlikely
Yes
Yes
P3
L3 | SEI CERT Perl Coding Standard > 2 Rules > Rule 50. Miscellaneous (MSC) |
perl | 88,890,534 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890534 | 2 | 50 | MSC32-PL | Do not provide a module's version value from outside the module | This rule is a stub. | ## Noncompliant Code Example
## This noncompliant code example shows an example where ...
#FFCCCC | ## Compliant Solution
## In this compliant solution, ...
#CCCCFF | ## Risk Assessment
Leaking sensitive information outside a trust boundary is not a good idea.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
MSC32-PL
Low
Unlikely
Yes
No
P2
L3 | SEI CERT Perl Coding Standard > 2 Rules > Rule 50. Miscellaneous (MSC) |
perl | 88,890,485 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890485 | 3 | 6 | OOP00-PL | Do not signify inheritence at runtime | The
@ISA
variable is a package variable that is used by all classes to indicate the class's parent (or parents). While this variable can be safely read to learn a class's inheritance hierarchy, it must not be modified at runtime [
Conway 2005
]. | {
package Base;
sub new {
my $class = shift;
my $self = {}; # no parent
bless $self, $class;
print "new Base\n";
return $self;
};
sub base_value {return 1;}
}
{
package Derived;
our @ISA = qw(Base); # establishes inheritance
sub new {
my $class = shift;
my $self = $class-... | # ... package Base is unchanged
{
package Derived;
use parent qw(Base);
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_); # relies on established inheritance
print "new Derived\n";
return $self;
};
sub derived_value {return 2;}
}
# ... The rest of the code is unchanged
new ... | ## Risk Assessment
Modifying class inheritance at runtime can introduce subtle bugs and is usually a sign of poor design.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
OOP00-PL
Low
Unlikely
Low
P3
L3 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 06. Object-Oriented Programming (OOP) |
perl | 88,890,493 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890493 | 3 | 6 | OOP01-PL | Do not access private variables or subroutines in other packages | Perl provides no mechanism to hide variables or functions. Although it provides mechanisms such as
my()
that limit the scope of variables, it does nothing to prevent code from accessing any variable or method that is available and dereferenceable from its current scope.
By convention, packages may indicate that a metho... | {
package Car;
my %_all_cars;
sub new {
my ($class, $type) = @_;
my $self = {type=>$type};
bless $self, $class;
$_all_cars{$self} = 1;
return $self;
};
sub DESTROY {
delete $_all_cars{shift()};
};
sub type {
my $self = shift;
return $$self{type};
}
sub _get_al... | {
package Car;
my %_all_cars;
sub count_cars {
my @all = keys( %_all_cars);
return 1 + $#all;
}
# ... other methods of Car
}
# ...
my $count = Car::count_cars();
print "There are $count cars on the road.\n";
## Compliant Solution
## This compliant solution adds a public method and invokes it inst... | ## Risk Assessment
Using deprecated or obsolete classes or methods in program code can lead to erroneous behavior.
Recommendation
Severity
Likelihood
Remediation Cost
Priority
Level
OOP01-PL
Medium
Probable
Medium
P8
L2 | SEI CERT Perl Coding Standard > 3 Recommendations > Rec. 06. Object-Oriented Programming (OOP) |
perl | 88,890,536 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890536 | 2 | 6 | OOP32-PL | Prohibit indirect object call syntax | The
indirect object call syntax
is a grammatical mechanism used by Perl to parse method calls. It is commonly used to emulate other language syntax. For instance, if a class
Class
has a constructor named
new
, then both of these statements invoke this constructor:
my $obj1 = Class->new; # 'object-oriented' syntax
my $o... | {
package Class;
sub new {
my $class = shift;
my $arg = shift;
my $self = bless( {Arg=>$arg}, $class);
print "Class::new called with $arg\n";
return $self;
}
}
sub new {
my $arg = shift;
print "::new called with $arg\n";
}
my $class_to_use = Class;
my $b1 = new Something; # Invok... | # ...
my $class_to_use = Class;
my $b1 = new( Something); # Invokes global new
my $b2 = Class->new( Something); # Invokes Class::new
my $b3 = $class_to_use->new( Something); # Invokes Class::new
## Compliant Solution
In this compliant solution, the final three statements all use
direct
object s... | ## Risk Assessment
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
OOP32-PL
Low
Probable
Yes
No
P4
L3 | SEI CERT Perl Coding Standard > 2 Rules > Rule 06. Object-Oriented Programming (OOP) |
perl | 88,890,494 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890494 | 2 | 5 | STR30-PL | Capture variables should be read only immediately after a successful regex match | Perl's capture variables (
$1
,
$2
, etc.) are assigned the values of capture expressions after a regular expression (regex) match has been found. If a regex fails to find a match, the contents of the capture variables can remain undefined. The
perlre
manpage [
Wall 2011
] contains this note:
NOTE: Failed matches in Pe... | my $data = "[ 4.693540] sr 1:0:0:0: Attached scsi CD-ROM sr0";
my $cd;
my $time;
$data =~ /Attached scsi CD-ROM (.*)/;
$cd = $1;
print "cd is $cd\n";
$data =~ /\[(\d*)\].*/; # this regex will fail
$time = $1;
print "time is $time\n";
cd is sr0
time is sr0
## Noncompliant Code Example
This noncompliant code exa... | my $data = "[ 4.693540] sr 1:0:0:0: Attached scsi CD-ROM sr0";
my $cd;
my $time;
if ($data =~ /Attached scsi CD-ROM (.*)/) {
$cd = $1;
print "cd is $cd\n";
}
if ($data =~ /\[(\d*)\].*/) { # this regex will fail
$time = $1;
print "time is $time\n";
}
cd is sr0
## Compliant Solution
## In this compliant ... | ## Risk Assessment
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
STR30-PL
Medium
Probable
Yes
No
P8
L2 | SEI CERT Perl Coding Standard > 2 Rules > Rule 05. Strings (STR) |
perl | 88,890,492 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890492 | 2 | 5 | STR31-PL | Do not pass string literals to functions expecting regexes | Many built-in functions accept a regex pattern as an argument. Furthermore, any subroutine can accept a string yet treat it as a regex pattern. This could be done, for example, by passing the string to the match operator (
m//
). Because regex patterns are encoded as regular strings, it is tempting to assume that a str... | my $data = 'Tom$Dick$Harry';
my @names = split( '$', $data);
## Noncompliant Code Example
This code example appears to split a list of names.
#ffcccc
perl
my $data = 'Tom$Dick$Harry';
my @names = split( '$', $data);
But the first argument to
split()
is treated as a regex pattern. Because
$
indicates the end of the str... | my $data = 'Tom$Dick$Harry';
my @names = split( m/\$/, $data);
## Compliant Solution
This compliant solution passes a regex pattern to
split()
as the first argument, properly specifying
$
as a raw character. Consequently,
@names
is assigned the three names
Tom
,
Dick
, and
Harry
.
#ccccff
perl
my $data = 'Tom$Dick$Har... | ## Risk Assessment
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
STR31-PL
Low
Likely
Yes
Yes
P9
L2 | SEI CERT Perl Coding Standard > 2 Rules > Rule 05. Strings (STR) |
Dataset Card for SEI CERT Perl Coding Standard (Wiki rules)
Structured export of the SEI CERT Perl Coding Standard from the SEI wiki.
Dataset Details
Dataset Description
Perl-focused secure coding guidance in tabular form: identifiers, narrative, and examples where available.
- Curated by: Derived from public SEI CERT wiki pages; packaged as CSV by the dataset maintainer.
- Funded by [optional]: [More Information Needed]
- Shared by [optional]: [More Information Needed]
- Language(s) (NLP): English (rule text and embedded code).
- License: Compilation distributed as
other; verify with CMU SEI for your use case.
Dataset Sources [optional]
- Repository: https://wiki.sei.cmu.edu/confluence/display/seccode/SEI+CERT+Coding+Standards
- Paper [optional]: SEI CERT Perl Coding Standard
- Demo [optional]: [More Information Needed]
Uses
Direct Use
Perl security tooling, training data, and documentation assistants.
Out-of-Scope Use
Not a substitute for the live wiki or official SEI publications.
Dataset Structure
All rows share the same columns (scraped from the SEI CERT Confluence wiki):
| Column | Description |
|---|---|
language |
Language identifier for the rule set |
page_id |
Confluence page id |
page_url |
Canonical wiki URL for the rule page |
chapter |
Chapter label when present |
section |
Section label when present |
rule_id |
Rule identifier (e.g. API00-C, CON50-J) |
title |
Short rule title |
intro |
Normative / explanatory text |
noncompliant_code |
Noncompliant example(s) when present |
compliant_solution |
Compliant example(s) when present |
risk_assessment |
Risk / severity notes when present |
breadcrumb |
Wiki breadcrumb trail when present |
Dataset Creation
Curation Rationale
Machine-readable Perl CERT rules for tooling pipelines.
Source Data
Data Collection and Processing
Wiki content normalized to the same schema as other SEI CERT language exports.
Who are the source data producers?
[More Information Needed]
Annotations [optional]
Annotation process
[More Information Needed]
Who are the annotators?
[More Information Needed]
Personal and Sensitive Information
[More Information Needed]
Bias, Risks, and Limitations
[More Information Needed]
Recommendations
Users should be made aware of the risks, biases and limitations of the dataset. More information needed for further recommendations.
Citation [optional]
BibTeX:
[More Information Needed]
APA:
[More Information Needed]
Glossary [optional]
[More Information Needed]
More Information [optional]
[More Information Needed]
Dataset Card Authors [optional]
[More Information Needed]
Dataset Card Contact
[More Information Needed]
- Downloads last month
- 39