Dataset Viewer
Auto-converted to Parquet Duplicate
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 function ($@) { # ... function body } However, prototypes are problematic in many ways. The biggest problem is that prototypes are not enforced by Perl's parser. That is, prototypes do not cause Perl to emit any warnings if a prototyped subroutine is invoked with arguments that violate the prototype.. Perl does not issue any warnings of prototype violations, even if the -w switch is used. Prototypes suffer from several other problems, too. They can change function behavior, by forcing scalar context when evaluating arguments that might not be scalars, or by forcing list context when evaluating arguments that might not be lists.  A function's prototype is ignored when that function is invoked with the & character. Finally, according to the perlfunc manpage [ Wall 2011 ]: Method calls are not influenced by prototypes either, because the function to be called is indeterminate at compile time, since the exact code called depends on inheritance. Because of these problems, subroutine prototypes must not be used when defining subroutines.
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 ## Noncompliant Code Example This noncompliant code example demonstrates a function with prototypes. The function takes a string and a list and simply prints out the string along with the list elements. #ffcccc perl 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); However, this program generates the following counterintuitive output: item is 3 List has 0 elements The problem arises from two issues. First, Perl constructs a single argument list from its arguments, and this process includes flattening any arguments that are themselves lists. For this reason, Perl allows function() to be invoked with one list argument rather than two. Second, the function prototype imposes contexts on the arguments it gets: a single scalar context for the first variable and a list context from the second variable. These contexts are invoked on the arguments actually provided rather than on the argument list. In this case, the scalar context is applied to the @elements list, which yields 3, the number of elements in the list. Then the list context is applied to no argument, since only one argument was specified, and it produces an empty list (with 0 elements).
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 Dick list contains Harry ## Compliant Solution ## This compliant solution omits the prototype: #ccccff perl 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); With no prototype, the first element in the list "Tom" is assigned to $item , and the $list gets the remaining elements: ("Dick", "Harry") . item is Tom List has 2 elements list contains Dick list contains Harry
## 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 declared in any block that contains it. Reusing variable names leads to programmer confusion about which variable is being modified. Additionally, if variable names are reused, generally one or both of the variable names are too generic.
$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 in the report_error() subroutine. Consequently, the program prints "The error is Local error" rather than "The error is Global error." #FFCCCC perl $errmsg = "Global error"; sub report_error { my $errmsg = shift(@_); # ... print "The error is $errmsg\n"; }; report_error("Local error");
$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"; sub report_error { my $local_error_msg = shift(@_); # ... print "The error is $local_error_msg\n"; }; report_error("Local error"); When the block is small, the danger of reusing variable names is mitigated by the visibility of the immediate declaration. Even in this case, however, variable name reuse is not desirable. In general, the larger the declarative region of an identifier, the more descriptive and verbose should be the name of the identifier. By using different variable names globally and locally, the compiler forces the developer to be more precise and descriptive with variable names.
## 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 obligated to reset the variable to its default value, lest it alter the behavior of subsequent unrelated code. The easiest way for a program to "clean up after itself" is to declare such variables local when modifying them.
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 subroutine that counts the number of virtual users on this platform. This value is deduced by the number of users in the /etc/passwd file that use the program /usr/bin/false as their shell. #ffcccc perl 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; } This program produces the correct result, but it leaves the $/ variable set to an unusual value ( : ). Subsequent reads of any file will use this character as the end-of-line delimiter rather than the typical newline, which is the default value.
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 same result but localizes the punctuation variable. Consequently, when the subroutine returns, the $/ variable is restored to its original value, and subsequent file reads behave as expected. #ccccff perl 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; }
## 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 iteration variable, which means the iteration variable does not preserve its value after the loop terminates. This can lead to surprising results if not accounted for. Consequently, it is recommended that the variable in a foreach loop be prefixed with my to make it explicit that the variable is private to the loop. And it is required that the variable not be read after the loop terminates.
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 (@list) { if ($value % 2 == 0) { last; } } print "$value is even\n"; However, the loop treats the iteration variable $value as local. So when it exits the list, $value regains the value it had before the loop. Because it was uninitialized before the loop, it remains undefined afterwards, and the final print statement prints: is even.
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++) { if ($value % 2 == 0) { last; } } print "$value is still even\n"; ## Compliant Solution (Expanded Loop) This compliant solution correctly prints 2 is even . It accomplishes this result by moving the print statement inside the loop and never refers to $value outside the loop. #ccccff perl my @list = (1, 2, 3); for my $value (@list) { if ($value % 2 == 0) { print "$value is even\n"; last; } } ## Compliant Solution (External Variable) This compliant solution preserves the value of $value by assigning it to a lexical variable defined outside the loop. It still declares $v to be private to the loop using my . #ccccff perl my @list = (1, 2, 3); my $value; for my $v (@list) { if ($v % 2 == 0) { $value = $v; last; } } print "$value is still even\n"; ## Compliant Solution (for) ## This compliant solution uses the noniterative form offor, which does no localization of its iteration variable. #ccccff perl my @list = (1, 2, 3); for ($value = 1; $value < 4; $value++) { if ($value % 2 == 0) { last; } } print "$value is still even\n";
## 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 initialized with the contents of the package variable. If they are meant to be uninitialized, they should be explicitly set to undef .
$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 example authenticates the user to enter a password, but only if the $passwd_required variable is defined. #ffcccc perl $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(); The call to local temporarily sets $passwd_required to the uninitialized value undef ; it does not maintain its previous value of 1 . Consequently, when the program executes, it incorrectly prints No password necessary .
$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 compliant solution initializes the localized variable to the old value, so it correctly prompts the user for a password. #ccccff perl $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();
## 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 confusing or arcane. #ffcccc perl require DBI'SQL'Nano;
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 be explicitly included to be used by a program, but modules that are part of the core language need not be. When a module has been assimilated into the core language, the original module is still available in CPAN. Modules that have become obsolete, superseded by newer modules, or integrated into the core language are considered deprecated. Do not import deprecated modules. If a module becomes deprecated because its features have been integrated into the core language, then their features may be used without importing the deprecated module. Here is a list of CPAN modules that should be considered deprecated, according to Perl::Critic . Deprecated Class::ISA Pod::Plainer Shell Switch Universal::isa Universal::can Universal::VERSION
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 was formerly an external CPAN module, but it is now part of Perl itself. #ffcccc perl use UNIVERSAL qw(can); # deprecated # ... sub doit { my ($func) = @_; if (can($self, $func)) { $self->$func(); } # ... } Although this code works correctly now, the use statement will be rejected by the Perl interpreter someday.
# 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) = @_; if ($self->can($func)) { $self->$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 keyword.
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 function. #ffcccc perl 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? Perl (v5.12.1) actually invokes the built-in open() rather than the newly crafted subroutine.
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 { my ($arg1, $arg2, $arg3) = @_; print "arg1 = $arg1\n"; print "arg2 = $arg2\n"; print "arg3 = $arg3\n"; } my_open( my $input, "<", "foo.txt");
## 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, false , or an empty string. Because Perl programs are typically not explicitly compiled before they are run, they can suffer from typographic errors in variable names. A variable whose name is typed incorrectly will appear as an undeclared variable to the Perl interpreter and consequently will contain the undef value instead of the value of the intended variable. Because of the hazard of mistyped variables, all variables should be declared before use.
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 following useless output: The result is and continue execution.
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 function may specify exactly what to return in each context. Returning the value undef is a common convention for a function to indicate it has no return value. It is often used to indicate that an error occurred or that a function could not successfully complete an operation. When used as the conditional in a conditional expression (such as in an if statement), undef evaluates to false. Therefore, a function that is evaluated only in scalar context may safely return undef to indicate failure. In list context, things are slightly more complicated. An empty list, when evaluated in a boolean condition, evaluates to false. But the value undef , when evaluated in list context, evaluates to true because it is converted to a list with the singleton value undef . Therefore, a function should not return undef if it might ever be invoked in list context.
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 ## Noncompliant Code Example This noncompliant code example opens the /etc/shadow file to process the users and encrypted passwords on a POSIX system. Because the /etc/shadow file is conventionally readable only by the root user, this program must gracefully abort if it is not allowed to read this file. #ffcccc perl 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"; } The read_users() subroutine returns undef if it cannot open /etc/shadow , but it returns a list of user data entries if it succeeds. Because its output is used in list context, a return value of undef is converted to a list of a single element: (undef) . Consequently, the if condition returns true, and the system incorrectly prints out the following: Your system has 0 users
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 properly complain if it cannot read the shadow file. #ccccff perl sub read_users { open( my $filehandle, "<", "/etc/shadow") or return; my @users = <$filehandle>; return @users; }
## 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 subroutine. This behavior is never intended by the developer (else she would have added a return statement) and may potentially be information that is private to the subroutine. Consequently, all subroutines must have an explicit return statement, even if it returns no useful value. Legacy code may, in lieu of an explicit return statement, use a trivial statement that at least computes an explicit value, such as the following: #ccccff perl sub subroutine { # ... do stuff 1; # always returns 1 }
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 noncompliant code example uses a hypothetical banking system to deposit some money. #ffcccc perl 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; } } The deposit() function does not explicitly return any value. Consequently, if any code invokes the deposit() routine and does something with the return value, what value does it actually receive? The answer is, the last value actually computed within the deposit() routine will be used as the return value. But to determine the last computed value, you have to do some control flow analysis. For this routine, if a valid $pin is supplied, then the last value computed is the return value of _set_balance() , so invoking deposit() with a valid PIN yields the result of the private _set_balance() routine, which may be sensitive. On the other hand, if an invalid $pin is supplied, the last value computed is $good_pin . So if deposit() is invoked with an invalid PIN, it actually returns the correct PIN!
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 trivial return statement to the function. Now the function always returns undef rather than any sensitive information. #ccccff perl 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; }
## 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 purpose of defining $BufferSize as a constant by assuming its value in the subsequent expression: #FFcccc perl our $BufferSize = 512; # ... my $nblocks = 1 + (($nbytes - 1) >> 9); # because $BufferSize = 512 = 2^9 The programmer might assume that everyone knows $BufferSize equals 512 and that right-shifting 9 bits is the same (for positive numbers) as dividing by 512. But if $BufferSize changes to 1024 on some systems, the subsequent expression must also be updated and can be overlooked easily. This makes modifications of constants difficult and error prone.
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 ]. They are called the late-precedence logical operators , whereas && , || , and ! are called the early-precedence logical operators . It is possible to mix the early-precedence logical operators with the late-precedence logical operators, but this mixture of precedence often leads to confusing, counterintuitive behavior. Therefore, every Perl expression should use either the early-precedence operators or the late-precedence ones, never both. Damian Conway recommends avoiding the use of not and and entirely and using or only in control-flow operations, as a failure mode [ Conway 2005 ]: perl print $filehandle $data or croak("Can't write to file: $!");
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) { This code is perfectly fine. However, it is later amended to also work if the file does exist but can be overwritten. #ffcccc perl if (not -f $file || -w $file) { This code will not behave as expected because the binding rules are lower for the not operator than for the ! operator. Instead, this code behaves as follows: perl if (not (-f $file || -w $file)) { when the maintainer really wanted: perl if ((not -f $file) || -w $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 $file) { ## Compliant Solution ## This compliant solution uses the early-precedence operators consistently. Again, the code works as expected. #ccccff perl if (not -f $file or -w $file) {
## 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 prone.
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 Example ## This noncompliant code example tries to print out the elements of an array. #ffcccc perl 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); The developer mistakenly left out the \ indicator when initializing $array_ref . Consequently, instead of a reference to the array, it contains the number of elements in the array. When passed to the print_array() subroutine, this program prints an empty array. ## Noncompliant Code Example ## This noncompliant code example prints the number of elements in an array. #ffcccc perl my @array; # initialize my $cardinality = @array; print "The array has $cardinality elements\n"; Although this program works correctly, the number of elements of an array can be obtained in less ambiguous ways.
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_ref = \@array; print_array( $array_ref); ## Compliant Solution (scalar()) ## This compliant solution uses thescalar()built-in subroutine to obtain the number of elements of an array. #ccccff perl my $cardinality = scalar( @array); print "The array has $cardinality elements\n"; This compliant solution evaluates @array in scalar context just as in the noncompliant code example. However, the scalar() makes this evaluation explicit, removing any doubt as to the programmer's intentions. ## Compliant Solution ($#) ## This compliant solution uses the$#operator to obtain the number of elements of an array. #ccccff perl my $cardinality = $#array + 1; print "The array has $cardinality elements\n";
## 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 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. Although it is supported, using map() to modify a list in place can lead to surprises in maintainability and is thus forbidden. Many other list functions provide similar functionality, using a block on various list elements. The grep() function is one such example, as are the first() and reduce() functions in List::Util and all of the functions in List::MoreUtils . Finally, the sort() function also provides aliases to its comparison blocks, so a comparison block for sort() must not modify its variables.
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 lists all users who use/bin/shas their login shell. #ffcccc perl 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 !
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 @users = <PASSWD>; my @shell_users = List::MoreUtils::apply { s|/bin/sh|| } @users; foreach my $user (@shell_users) { print "Shell User: $user"; } ## Compliant Solution (grep()) ## This compliant solution does the same thing but does not modify the@usersarray. #ccccff perl 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. #ccccff perl 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 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. The third form takes one argument, a file handle, and makes it the currently selected file handle. That is, this form of select() changes the file that is used by all print statements (unless they specify their own file handle). Modifying the file handle used by print is counterintuitive because subsequent print statements will no longer print to standard output. Furthermore, the globally selected file handle is not garbage-collected; it remains open even if the file handle goes out of scope. Therefore, do not modify the selected file handle with select() .
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 are you?\n"; select(( select($log), $| = 1)[0]); ## Noncompliant Code Example ## This noncompliant code example tries to log a message while interacting with the user. #ffcccc perl 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 are you?\n"; Unfortunately, the select() method causes the last print statement to print "How are you?" not to standard output but to the log file. ## Noncompliant Code Example (Autoflush) This noncompliant code example uses the one-argument select() function temporarily to modify the autoflush property associated with the file. The one-argument select() returns the old file handle (normally standard output). After the $log file handle is selected, the modification of $| instructs Perl to autoflush everything sent to the $log file handle. That is, every output to the $log file handle is flushed immediately. After the modification, select() is called again to restore the original selected file handle. #ffcccc perl select(( select($log), $| = 1)[0]);
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 compliant solution avoidsselect()and directs theprint()statement to use the log file handle for output. #ccccff perl 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"; } ## Compliant Solution This compliant solution causes output to $log to be autoflushed without using select() . It uses the autoflush() object method from the IO::Handle module. #ccccff perl use IO::Handle; # ... $log->autoflush();
## 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 modules are also deprecated: Deprecated Preferred base parent
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"; # work with FILE The die() method is considered deprecated because it prints the file name and line number in which it was invoked. This information might be sensitive.
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 Unlike die() , croak() provides the file name and line number of the function that invoked the function that invoked croak() . This solution is more useful for application code that invokes library code; in this case, croak() and carp() also will reveal the file name and line number of the application code rather than the library code.
## 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 empty string. Beware that using "eval" neither silences Perl from printing warnings to STDERR, nor does it stuff the text of warning messages into $@. ... It is also Perl's exception trapping mechanism, where the die operator is used to raise exceptions. Note that recommends using croak() rather than die() . Programmers may often suppress exceptions, which is easily accomplished by not examining the $@ variable (also known as $EVAL_ERROR ). Because eval makes ignoring exceptions the default, it is critically important that programmers inspect $@ after using eval . Exceptions are intended to disrupt the expected control flow of the application. Many exceptions are suppressed out of not knowing how to handle the exception or not even knowing that one may have been thrown. Consequently, exceptions must never be suppressed. If a call to eval fails, the calling code must at least inspect $@ . If the developer does not know how to handle the exception, he can always propagate it up the stack by issuing his own fatal error.
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 resume normally, with $answer being uninitialized. It produces a warning when the uninitialized value is embedded in the string passed to print() . So eval can be used to completely ignore an important error that may occur. #ffcccc perl my ($a, $b) = # initialize my $answer; eval { $answer = $a / $b }; print "The quotient is $answer\n";
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) = # initialize my $answer; if (! eval { $answer = $a / $b }) { carp($@) if $@; $answer = 0; } print "The quotient is $answer\n";
## 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 value often contains important information about possible errors, it should always be checked; otherwise, the cast should be made explicit to signify programmer intent.
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 variable containing the file name is properly defined, but it does nothing else to catch errors. Consequently, any error, such as the file not existing, being unreadable, or containing too much data to read into memory, will cause the program to abort.
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 $SOURCE, "<", $source) or croak "error opening $source: $!"; @lines = (<$SOURCE>); close($SOURCE) or croak "error closing $source: $!"; If any error occurs, the program calls the croak() function, passing it a string that includes both the source file being opened and the $! variable, which contains a system error string based on the value of errno , which is set to a useful value when the open(2) or close(2) functions fail.
## 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 for which the block or expression evaluates to false. The grep() function returns the filtered list when called in list context, but when called in scalar context, it merely returns the size of this list. That is, it returns the number of elements for which the block or expression evaluates to true. Some functions do not define what they return in list or scalar context. For instance, according to the perlfunc manpage, the sort() function "sorts the LIST and returns the sorted list value. In scalar context, the behavior of ' sort() ' is undefined."
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 = shift; my @list = @{$list}; # ... return sort @list; } my @list = ( "foo", "bar", "baz"); my $result = ret @list; The contents of $result are undefined because the sort() function's return value is not defined in a scalar context.
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 = @{$list}; # ... return sort @list; } my @list = ( "foo", "bar", "baz"); my @result = ret @list; In this case, the @result array will contain the list { "bar", "baz", "foo" }.
## 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; } } ## Noncompliant Code Example (Numbers) ## This noncompliant code example improperly useseqto test two numbers for equality. #ffcccc perl 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"}; This code will print true if the user enters 2 , but false if the user enters 02 , ## Noncompliant Code Example (Strings) ## This noncompliant code example improperly uses==to test two strings for equality. #ffcccc perl sub check_password { my $correct = shift; my $password = shift; # encrypt password if ($password == $correct) { return true; } else { return false; } } The == operator first converts its arguments into numbers by extracting digits from the front of each argument (along with a preceding + or - ). Nonnumeric data in an argument is ignored, and the number consists of whatever digits were extracted. A string such as "goodpass" has no leading digits, so it is converted to the numeral 0. Consequently, unless either $password or $correct contains leading digits, they will both be converted to 0 and will be considered equivalent.
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; } } ## Compliant Solution (Numbers) This compliant solution uses == , which interprets its arguments as numbers. This code therefore prints true even if the right argument to == is initialized to some different string like 02 . #ccccff perl 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"}; ## Compliant Solution (Strings) ## This compliant solution useseq, which interprets its arguments as strings. #ccccff perl 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 with peril. Consequently, file handles should never be stored as barewords.
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 maintain some simple code that makes the mistake of using bareword file handles. #ffcccc perl 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"; This code works as expected. It reads and prints a line of good text, followed by a line of bad text, followed by a second line of good text. But during maintenance, someone (undoubtedly with the best of intentions) adds this function: #ffcccc perl sub BAD {return GOOD;} This function completely changes the behavior of the subsequent code. The BAD bareword is now interpreted as a subroutine call, not a file handle. The program, as before, first opens good.txt , storing it in the GOOD file handle, which is a package variable. It next opens bad.txt , but instead of storing the descriptor in a BAD file handle, it stores the descriptor in the file handle returned by the BAD() subroutine, which returns GOOD . Consequently, the GOOD file handle now points to the descriptor for bad.txt , not good.txt . The program then tries to read from the BAD file handle, but this attempted read produces nothing because this file handle was never actually opened. Nonetheless, the program then reads a line from the GOOD file handle and echoes it—which turns out to be from bad.txt rather than good.txt .
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 compliant solution protects the file descriptors by using anonymous scalars rather than bareword file handles. #ccccff perl 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"; Consequently, the original behavior of this program is restored. Because the $BAD variable is declared with my , it is a lexical variable rather than a package variable and is unaffected by the BAD subroutine. So this program once again prints two lines from the good.txt file and one from the bad.txt file, and never confuses the two.
## 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 exploited by an attacker to gain access to files for which they lack sufficient privileges, particularly when operating on files that reside in shared directories in which multiple users may create, move, or delete files. Privilege escalation is also possible when programs that access these files run with elevated privileges. Many file system properties and capabilities can be exploited by an attacker, including file links, device files, and shared file access. To prevent vulnerabilities, a program must operate only on files in secure directories. The security of a directory depends on the security policy applied to a program. A program typically runs with the privileges of a particular user, and its policy will regard that user as trusted. Its policy may also regard some or all other users as untrusted. Any reasonable security policy must also regard the root user as trusted, as there is no protection from a malicious user with root privileges. For a particular security policy that may apply to a program, a directory is secure if only trusted users are allowed to create, move, or delete files inside that directory. Furthermore, each parent directory must itself be a secure directory up to and including the root directory. On most systems, home or user directories are secure by default and only explicitly shared directories, such as /tmp , are insecure. Programs with elevated privileges may need to write files to directories owned by unprivileged users. One example would be a mail daemon that reads a mail message from one user and places it in a directory owned by another user. Any such program should have a security policy dictating which users are trusted. For example, the mail daemon should trust only the user sending the message when gathering the mail to be sent and then trust only the user receiving the message when delivering it. ## File Links Many operating systems support file links, including symbolic (soft) links, hard links, shortcuts, shadows, aliases, and junctions. In POSIX, symbolic links can be created using the ln -s command and hard links using the ln command. Hard links are indistinguishable from normal files on POSIX systems. Three file link types are supported in Windows NTFS (New Technology File System): hard links, junctions, and symbolic links. Symbolic links are available in NTFS starting with Windows Vista. File links can create security issues for programs that fail to consider the possibility that a file being opened may actually be a link to a different file. This is especially dangerous when the vulnerable program is running with elevated privileges. When creating new files, an application running with elevated privileges may erroneously overwrite an existing file that resides outside the directory it expected. ## Device Files File names on many operating systems may be used to access device files. Device files are used to access hardware and peripherals. Reserved MS-DOS device names include AUX , CON , PRN , COM1 , and LPT1 . Character special files and block special files are POSIX device files that direct operations on the files to the appropriate device drivers. Performing operations on device files intended only for ordinary character or binary files can result in crashes and denial-of-service (DoS) attacks. For example, when Windows attempts to interpret a device name as a file resource, it performs an invalid resource access that usually results in a crash [ Howard 2002 ]. Device files in POSIX can be a security risk when an attacker can trick a program into accessing them in an unauthorized way. For instance, if malicious programs can read or write to the /dev/kmem device file, they may be able to alter their own priority, user ID, or other attributes of their process, or they may simply crash the system. Similarly, access to disk devices, tape devices, network devices, and terminals being used by other processes can also lead to problems [ Garfinkel 1996 ]. On Linux, it is possible to lock certain applications by attempting to read or write data on devices rather than files. Consider the following device path names: /dev/mouse /dev/console /dev/tty0 /dev/zero A web browser that failed to check for these devices would allow an attacker to create a website with image tags such as <IMG src="file:///dev/mouse"> that would lock the user's mouse. ## Shared File Access On many systems, files can be simultaneously accessed by concurrent processes. Exclusive access grants unrestricted file access to the locking process while denying access to all other processes, eliminating the potential for a race condition on the locked region. Some platforms provide various forms of file locking. Shared locks support concurrent read access from multiple processes; exclusive locks support exclusive write access. File locks provide protection across processes, but they do not provide protection from multiple threads within a single process. Both shared locks and exclusive locks eliminate the potential for a cross-process race condition on the locked region. Exclusive locks provide mutual exclusion; shared locks prevent alteration of the state of the locked file region (one of the required properties for a data race). Microsoft Windows uses a mandatory file-locking mechanism that prevents processes from accessing a locked file region. Linux implements both mandatory locks and advisory locks. Advisory locks are not enforced by the operating system, which diminishes their value from a security perspective. Unfortunately, the mandatory file lock in Linux is generally impractical because mandatory locking is supported only by certain network file systems. file systems must be mounted with support for mandatory locking, which is disabled by default. locking relies on the group ID bit, which can be turned off by another process (thereby defeating the lock). the lock is implicitly dropped if the holding process closes any descriptor of the file.
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_IFREG & $mode) == 0; open( my $in, "<", $path) or croak "Can't open 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 = (lstat($path))[2] or croak "Can't run lstat"; croak "Not a regular file" if (S_IFREG & $mode) == 0; open( my $in, "<", $path) or croak "Can't open file"; # ... work with FILE and close it use Carp; use Fcntl ':mode'; use POSIX; my $path = $ARGV[0]; # provided by user # Check that file is regular my ($device, $inode, $mode, @rest) = lstat($path) or croak "Can't run lstat"; croak "Not a regular file" if (S_IFREG & $mode) == 0; my $fd = POSIX::open($path, O_RDONLY) or croak "Can't open file"; # note: fd is a POSIX file descriptor, NOT a perl filehandle! my ($fdevice, $finode, $fmode, @frest) = POSIX::fstat($fd) or croak "Can't run fstat"; croak "File has been tampered with" if $fdevice ne $device or $finode ne $inode; open( my $in, "<&", $fd) or croak "Can't open file descriptor"; # ... work with FILE and close it ## Noncompliant Code Example This noncompliant code example opens a file whose name is provided by the user. It calls croak() if the open was unsuccessful, as required by . #ffcccc perl use Carp; my $file = # provided by user open( my $in, "<", $file) or croak "error opening $file"; # ... work with FILE and close it Unfortunately, an attacker could specify the name of a locked device or a first in, first out (FIFO) file, causing the program to hang when opening the file. ## Noncompliant Code Example (Regular File) ## This noncompliant code example first checks that the file is a regular file before opening it. #ffcccc perl 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_IFREG & $mode) == 0; open( my $in, "<", $path) or croak "Can't open file"; # ... work with FILE and close it This test can still be circumvented by a symbolic link. By default, the stat() built-in function follows symbolic links and reads the file attributes of the final target of the link. The result is that the program may reference a file other than the one intended. ## Noncompliant Code Example (lstat()) This noncompliant code example gets the file's information by calling lstat() rather than {[stat()}} . The lstat() system call does not follow symbolic links, and it provides information about the link itself rather than the file. Consequently, this code correctly identifies a symbolic link as not being a regular file. #ffcccc perl use Carp; use Fcntl ':mode'; my $path = $ARGV[0]; # provided by user # Check that file is regular my $mode = (lstat($path))[2] or croak "Can't run lstat"; croak "Not a regular file" if (S_IFREG & $mode) == 0; open( my $in, "<", $path) or croak "Can't open file"; # ... work with FILE and close it This code is still vulnerable to a time-of-check, time-of-use (TOCTOU) race condition. For example, an attacker can replace the regular file with a file link or device file after the code has completed its checks but before it opens the file. ## Noncompliant Code Example (Check-Use-Check) This noncompliant code example performs the necessary lstat() check and then opens the file using the POSIX::open() function to obtain a file descriptor. After opening the file, it performs a second check to make sure that the file has not been moved and that the file opened is the same file that was checked. This check is accomplished using POSIX::fstat() , which returns the same information as lstat() but operates on open file descriptors rather than file names. It does leave a race window open between the first check and the open but subsequently detects if an attacker has changed the file during the race window. In both checks, the file's device and i-node attributes are examined. On POSIX systems, the device and i-node serve as a unique key for identifying files, which is a more reliable indicator of the file's identity than its path name. #ffcccc perl use Carp; use Fcntl ':mode'; use POSIX; my $path = $ARGV[0]; # provided by user # Check that file is regular my ($device, $inode, $mode, @rest) = lstat($path) or croak "Can't run lstat"; croak "Not a regular file" if (S_IFREG & $mode) == 0; my $fd = POSIX::open($path, O_RDONLY) or croak "Can't open file"; # note: fd is a POSIX file descriptor, NOT a perl filehandle! my ($fdevice, $finode, $fmode, @frest) = POSIX::fstat($fd) or croak "Can't run fstat"; croak "File has been tampered with" if $fdevice ne $device or $finode ne $inode; open( my $in, "<&", $fd) or croak "Can't open file descriptor"; # ... work with FILE and close it Although this code goes to great lengths to prevent an attacker from successfully tricking it into opening the wrong file, it still has several vulnerabilities: The TOCTOU race condition still exists between the first check and open. During this race window, an attacker can replace the regular file with a symbolic link or other nonregular file. The second check detects this race condition but does not eliminate it. A system with hard links allows an attacker to construct a malicious file that is a hard link to a protected file. Hard links cannot be reliably detected by a program and can foil canonicalization attempts, which are prescribed by .
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 is_secure_path { my ($path) = @_; # trim trailing / chop $path if $path =~ m@/$@; # This could turn root dir into empty string. # make sure path is absolute $path = $ENV{"PWD"} . "/" . $path if $path !~ m@^/@; return is_secure_path_aux( $path, $max_symlinks); } # Helper to is_secure_path. Requires absolute path, w/o trailing / # Also accepts empty string, interpreted as root path. sub is_secure_path_aux { my ($path, $symlinks) = @_; # Fail if too many levels of symbolic links return 0 if $symlinks <= 0; # Fail if parent path not secure if ($path =~ m@(^.*)(/[^/]+)@) { my $parent = $1; return 0 if !is_secure_path_aux( $parent, $max_symlinks); } else { # No parent; path is root dir, proceed $path = "/"; } # If path is symlink, check that linked-to path is also secure if (-l $path) { my $target = readlink $path or croak "Can't read symlink, stopped"; return 0 if !is_secure_path_aux( $target, $max_symlinks-1); } return is_secure_dir( $path); } # Indicates if a particular path is secure. Does no checks on parent # directories or symlinks. sub is_secure_dir { my ($path) = @_; # We use owner uid and permissions mode, from path's i-node my ($dummy1, $dummy2, $mode, $dummy3, $uid, @dummy4) = lstat($path) or croak "Can't run lstat, stopped"; # Fail if file is owned by someone besides current user or root return 0 if $uid != $> && $uid != 0; # Fail if file has group or world write permissions return 0 if S_IWGRP & $mode || S_IWOTH & $mode; return 1; } use Carp; my $file = $ARGV[0]; # provided by user croak "Not a secure path" if !is_secure_path( $file); # Check that file is regular my $mode = (lstat($file))[2] or croak "Can't run lstat"; croak "Not a regular file" if (S_IFREG & $mode) == 0; open( my $in, "<", $file) or croak "Can't open file"; # ... work with FILE and close it ## Compliant Solution (Secure Path) Because of the potential for race conditions and the inherent accessibility of shared directories by untrusted users, files must be operated on only by secure paths. A secure path is a directory that cannot be moved or deleted by untrusted users. Furthermore, its parent path, grandparent path, and so on up to the root, must also be secure, and if the path includes any symbolic links, both the link's target path and the path containing the link must be secure paths. Because programs may run with reduced privileges and lack the facilities to construct a secure path, a program may need to abort if it determines that a given path is not secure. Following is a POSIX-specific implementation of an is_secure_path() subroutine. This function ensures that the file in the supplied path and all directories above it are secure paths. #ccccff perl 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 is_secure_path { my ($path) = @_; # trim trailing / chop $path if $path =~ m@/$@; # This could turn root dir into empty string. # make sure path is absolute $path = $ENV{"PWD"} . "/" . $path if $path !~ m@^/@; return is_secure_path_aux( $path, $max_symlinks); } # Helper to is_secure_path. Requires absolute path, w/o trailing / # Also accepts empty string, interpreted as root path. sub is_secure_path_aux { my ($path, $symlinks) = @_; # Fail if too many levels of symbolic links return 0 if $symlinks <= 0; # Fail if parent path not secure if ($path =~ m@(^.*)(/[^/]+)@) { my $parent = $1; return 0 if !is_secure_path_aux( $parent, $max_symlinks); } else { # No parent; path is root dir, proceed $path = "/"; } # If path is symlink, check that linked-to path is also secure if (-l $path) { my $target = readlink $path or croak "Can't read symlink, stopped"; return 0 if !is_secure_path_aux( $target, $max_symlinks-1); } return is_secure_dir( $path); } # Indicates if a particular path is secure. Does no checks on parent # directories or symlinks. sub is_secure_dir { my ($path) = @_; # We use owner uid and permissions mode, from path's i-node my ($dummy1, $dummy2, $mode, $dummy3, $uid, @dummy4) = lstat($path) or croak "Can't run lstat, stopped"; # Fail if file is owned by someone besides current user or root return 0 if $uid != $> && $uid != 0; # Fail if file has group or world write permissions return 0 if S_IWGRP & $mode || S_IWOTH & $mode; return 1; } When checking directories, it is important to traverse from the root directory to the leaf directory to avoid a dangerous race condition whereby an attacker who can write to at least one of the directories would rename and re-create a directory after the privilege verification of subdirectories but before the verification of the tampered directory. An attacker could use this race condition to fool the algorithm into falsely reporting that a path is secure. If the path contains any symbolic links, the code will recursively invoke itself on the linked-to directory and ensure it is also secure. A symlinked directory may be secure if and only if both its source and linked-to directory are secure. On POSIX systems, disabling group and world write access to a directory prevents modification by anyone other than the owner of the directory and the system administrator; consequently, this function checks that each path lacks group or world write permissions. It also checks that a file is owned by either the user running the program or the system administrator. This is a reasonable definition of a secure path, but it could do other checks as well, such as the following: checking group IDs checking the file's sticky bit checking that the file has only one hard link permitting a set of trusted users in addition to the current user This code is effective only on file systems that are fully compatible with POSIX file access permissions; it may behave incorrectly for file systems with other permission mechanisms such as AFS. It is designed to prevent untrusted users from creating race conditions based on the file system. It does not prevent race conditions in which both accesses to a file are performed by the user or the superuser. The following compliant solution uses the is_secure_path() method to ensure that an attacker cannot tamper with the file to be opened and subsequently removed. Note that once the path name of a directory has been checked using is_secure_path() , all further file operations on that file must be performed using the same path. No race conditions are possible involving untrusted users, and so there is no need to perform any check after the open; the only remaining check necessary is the check that the file is a regular file. #ccccff perl use Carp; my $file = $ARGV[0]; # provided by user croak "Not a secure path" if !is_secure_path( $file); # Check that file is regular my $mode = (lstat($file))[2] or croak "Can't run lstat"; croak "Not a regular file" if (S_IFREG & $mode) == 0; open( my $in, "<", $file) or croak "Can't open file"; # ... work with FILE and close it
## 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) links, hard links, shortcuts, shadows, aliases, and junctions. These file links must be fully resolved before any file validation operations are performed. For example, the final target of a symbolic link called trace might be the path name /home/system/trace . Path names may also contain special file names that make validation difficult: " . " refers to the directory itself. Inside a directory, the special file name " .. " refers to the directory's parent directory. In addition to these specific issues, a wide variety of operating system–specific and file system–specific naming conventions make validation difficult. The process of canonicalizing file names makes it easier to validate a path name. More than one path name can refer to a single directory or file. Furthermore, the textual representation of a path name may yield little or no information regarding the directory or file to which it refers. Consequently, all path names must be fully resolved or canonicalized before validation. Because the canonical form can vary among operating systems and file systems, it is best to use operating system–specific mechanisms for canonicalization; however, this option is often not available. For example, validation may be necessary when attempting to restrict user access to files within a particular directory or otherwise make security decisions based on a file name or path name. Frequently, an attacker can circumvent these restrictions by exploiting a directory traversal or path equivalence vulnerability. A directory traversal vulnerability allows an I/O operation to escape a specified operating directory. A path equivalence vulnerability occurs when an attacker provides a different but equivalent name for a resource to bypass security checks. Canonicalization contains an inherent race window between the time the program obtains the canonical path name and the time it opens the file. While the canonical path name is being validated, the file system may have been modified and the canonical path name may no longer reference the original valid file. Fortunately, this race condition can be easily mitigated. A path name that is a secure path is immune to race windows and other attempts by an untrusted user to confuse the program. See for more information on secure paths.
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 stopped at $resolved"; if ($image_file !~ m|/img/|) { croak "Image file not in /img"; } open( my $image, "<", $image_file) or croak "Can't open $image_file"; # ... } my $filename = $ENV{"HOME"} . $DIR_SEP . $ARGV[0]; # $DIR_SEP = / on POSIX or \ on Windows croak "Not a secure path" if !is_secure_path( $filename); croak "Invalid path" if !validate_path( $filename); ## Noncompliant Code Example (POSIX) This noncompliant code example allows the user to specify a file inside the /img directory for the program to work with. Because of its lack of checks, the user can specify files outside the intended directory by entering an argument that contains ../ sequences and consequently violates the intended security policies of the program. #ffcccc perl sub work_with_image { my ($image_file) = @_; # untrusted open( my $image, "<", "/img/$image_file") or croak "Can't open image file"; # ... } ## Noncompliant Code Example (POSIX,File::PathConvert) This noncompliant code example attempts to enforce that the file specified still lives within the /img directory. However, it is using the File::PathConvert module, which has been deprecated. #ffcccc perl use File::PathConvert qw(realpath $resolved); sub work_with_image { my ($image_file) = @_; # untrusted $image_file = realpath("/img/$image_file") || croak "Resolution stopped at $resolved"; if ($image_file !~ m|/img/|) { croak "Image file not in /img"; } open( my $image, "<", $image_file) or croak "Can't open $image_file"; # ... } According to the CPAN entry for File::PathConvert : There are several known bugs, and it is not being actively maintained since all functionality is now available in modules (Cwd.pm and File::Spec) bundled in every Perl distribution of recent vintage. This version is provided to fix a few bugs and to get the word out about the deprecation. ## Noncompliant Code Example This noncompliant code example accepts a file path as a command-line argument and uses the is_secure_path() subroutine defined in . This ensures that the file is in a secure directory. The validate_path() routine performs string-based validation on the path name. This could include checking for such things as that the file lives in the user's home directory. the file ends with the proper suffix, such as .html . the file does not contain "weird" characters such as spaces. #ffcccc perl my $filename = $ENV{"HOME"} . $DIR_SEP . $ARGV[0]; # $DIR_SEP = / on POSIX or \ on Windows croak "Not a secure path" if !is_secure_path( $filename); croak "Invalid path" if !validate_path( $filename); However, this code neither resolves file links nor eliminates equivalence errors. Consequently, the validation routine may pass on the path name given, whereas the path name might resolve to a file that the validation routine would fail on. For instance, a path name that starts with /home/person might resolve to a file that lives outside /home/person , foiling a validation routine that ensures that the file lives in the person's home directory.
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 = "/"; my $filename = $ENV{"HOME"} . $DIR_SEP . $ARGV[0]; croak "Not a secure path" if !is_secure_path( $filename); $filename = abs_path( $filename); croak "Invalid path" if !validate_path( $filename); ## Compliant Solution (POSIX,Cwd) This compliant solution obtains the file name from the untrusted user input and canonicalizes it using Perl's Cwd module, which is part of the standard Perl distribution. #ccccff perl 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"; # ... } ## Compliant Solution (POSIX) This compliant solution uses the Cwd module to obtain the file's canonical path before performing any validation. This guarantees that any string-based operations the validation may perform on the path are performed on the canonical path and therefore cannot be foiled by symbolic links or . or .. in the path. Furthermore, canonicalization is performed after the file has been verified to live in a secure path. This prevents attackers from conducting time-of-check, time-of-use (TOCTOU) attacks against the program during the abs_path() call, or the validation, or any subsequent operations on the path. #ccccff perl use Cwd 'abs_path'; my $DIR_SEP = "/"; my $filename = $ENV{"HOME"} . $DIR_SEP . $ARGV[0]; croak "Not a secure path" if !is_secure_path( $filename); $filename = abs_path( $filename); croak "Invalid path" if !validate_path( $filename); ## Compliant Solution (Windows) Producing canonical file names for Windows operating systems is extremely complex and beyond the scope of this standard. The best advice is to try to avoid making decisions on the basis of a path, directory, or file name [ Howard 2002 ]. Alternatively, use operating system–based mechanisms, such as access control lists (ACLs) or other authorization techniques.
## 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 expression—taint is associated with a value, not a particular variable. The Perl interpreter issues a fatal error if any tainted variable is used in certain operations, such as invoking the system() function. Finally, there are a few ways you can sanitize tainted data, thereby removing the taint. The details of how taint mode works are extensively documented in the perlsec manpage, which states: Taint checking is most useful when although you trust yourself not to have written a program to give away the farm, you don't necessarily trust those who end up using it not to try to trick it into doing something bad. If taint mode detects untainted data being used in a manner it deems insecure, it aborts the program. This is an improvement in security, as it is better for a program to crash than to reveal sensitive information or allow arbitrary code execution. However, many programs, such as web servers, may run in environments where a crash is unacceptable. The taint mode can be configured to emit a warning rather than a fatal error, but this practice is not recommended because it can permit behavior worse than a crash. Consequently, taint mode is best viewed as a testing tool for verifying code before putting it into production use. Taint mode is an example of a dynamic analysis tool, which provides useful information about a program while it runs. Taint mode has the usual advantages and disadvantages of dynamic analysis tools. It does not produce false positives; it emits errors only when tainted data is used in a manner it considers insecure, and therefore its messages warrant attention and demand a fix. It imposes a minor performance penalty from doing taint checks. Finally, it checks only code that actually runs. If a program is run in taint mode and happens to never execute one particular file, then that file may still contain dataflow vulnerabilities. Taint mode has a very simple model of what data is tainted, when tainted data becomes untainted, and what operations may not be performed on tainted data. This model is sufficient for some programs but not for others. Taint mode forbids tainted data from being passed to a command interpreter (such as system() ) or a file opened for writing (via open() or rename() ). However, taint mode does not prevent tainted data from being used in certain other contexts, some of which are forbidden by various CERT rules: Data Rule File names that are open only for reading Numbers that are used as an array index Strings printed to standard output Taint mode also provides a handful of mechanisms to produce untainted data from tainted data. The preferred means of sanitizing tainted data is to use a regex: perl my $tainted = # initialized my $regex = # data is sanitary if it satisfies this $tainted_data =~ m{($regex)}; my $sanitized_data = $1; In this case, the sanitized data may have the same value as the tainted data, but data harvested from a regex match is always considered to be untainted. It is up to the programmer to ensure that the regex will match only sanitary data. There are other ways to sanitize tainted data. For instance, hash keys cannot be tainted, so using tainted data as the key to a hash will sanitize it. Perl will also not stop tainted data from being sent to a subroutine or method referenced by a variable, as in: perl $obj->$method(@args); or perl $foo->(@args); The specific issue of what data is tainted depends on the execution environment. For example, data read from a database may or may not be considered tainted. Perl's DBI module provides an optional TaintOut attribute. If set, then any data retrieved from a database will be considered tainted. Likewise, the specific set of actions that should not be performed on tainted data depends on the execution environment. For instance, a CGI script will print out data to be displayed on a web page. Such data requires sanitization to prevent various web-based vulnerabilities, but taint mode does not prevent tainted data from being printed. Consequently, taint mode may be used for certain Perl scripts and is required for some. All scripts with the setuid or setgid bit set run with taint mode. It should be used during testing and quality assurance. It will not detect all potential dataflow vulnerabilities, and it is critical to know when taint mode can be relied on and when it cannot. The following is an example of a vulnerable program that cannot rely on taint mode.
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 hr; } print end_html; ## Noncompliant Code Example (CGI) Taint mode assumes a simple model: all data is either tainted or untainted. Although this assumption is useful for some applications, it is not sufficient for web-based security. Consider this noncompliant code example, from : #ffcccc perl 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 hr; } print end_html; This example contains a CGI form that prompts the user for a name and, when given, displays the name on the page. Like all web forms, it also takes a URL argument indicating what link to visit when the user clicks Submit . Lines A, B, and C all involve tainted data being printed to standard output, from which it is used to render a web page. Line A contains the URL to visit. This URL will include all arguments, including the name. The CGI::start_form sanitizes the URL in a suitable manner so that it may be visited and will appear in the Address bar of a web browser. Line B contains the user's name. The CGI::textfield() method escapes text in a manner suitable for displaying in a text field. Line C again contains the user's name but with no sanitization. This permits an XSS vulnerability, as described in IDS33-PL . It is recommended that this text be sanitized using the CGI::escapeHTML() method in order to be safely displayed in a web page. All three lines provide different contexts for their unsanitized data, so each line requires a different type of sanitization. Applying one sanitization method to the wrong line is likely to leave the data improperly sanitized and subject to a potential injection attack. Because taint mode does not distinguish between different contexts, it cannot discern that text sanitized for a URL should not be provided to a text field, and vice versa. Therefore, we do not recommend using taint mode for scripts that interact with the web.
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 to divert control flow. Their capabilities are not as strong as in C [ Seacord 2005 ]; nonetheless the danger is sufficiently great that the formatted output functions {{sprintf() and printf() should never be passed unsanitized format strings.
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 "$prompt: access denied\n"; }; user@host:~$ ./authenticate.pl goodpass user@host: Password ok? 1 user@host: access granted user@host:~$ ./authenticate.pl badpass user@host: Password ok? 0 user@host: access denied user@host:~$ user@host:~$ env USER=user%n ./authenticate.pl badpass user%n@host: Password ok? 0 user%n@host: access granted user@host:~$ ## Noncompliant Code Example This noncompliant code example tries to authenticate a user by having the user supply a password and granting access only if the password is correct. #ffcccc perl 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 "$prompt: access denied\n"; }; The program works as expected as long as the user name and host name are benign: user@host:~$ ./authenticate.pl goodpass user@host: Password ok? 1 user@host: access granted user@host:~$ ./authenticate.pl badpass user@host: Password ok? 0 user@host: access denied user@host:~$ However, the program can be foiled by a malicious user name: user@host:~$ env USER=user%n ./authenticate.pl badpass user%n@host: Password ok? 0 user%n@host: access granted user@host:~$ In this invocation, the malicious user name user%n was incorporated into the $prompt string. When fed to the printf() call inside validate_password() , the %n instructed Perl to fill the first format string argument with the number of characters printed, which caused Perl to set the $is_ok variable to 4. Since it is now nonzero, the program incorrectly grants access to the user.
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_password { my ($password) = @_; my $is_ok = ($password eq "goodpass"); print "$prompt: Password ok? $is_ok\n"; return $is_ok; }; # ...
## 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 provided (that is, if open() is given three or more arguments), the MODE argument indicates if the file is opened for input or output. It can also indicate that rather than opening a file, the system should execute a shell command and treat it as an input file or an output file. If the two-argument form is used, the EXPR should contain both the MODE argument and file name to be opened or shell command to be executed. If an attacker can provide a file name argument to be used in the two-argument form of open() , the attacker can instead provide a shell command, which gets executed by the program.
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 ":: $_"; }; perl -n 'print ":: $_\n";' * perl -p '$_ = ":: $_\n";' * ## Noncompliant Code Example ## This noncompliant code example uses the two-argument form ofopen(). #ffcccc perl my $filename = # initialize open(my $FILE, $filename) or croak("file not found"); while (<$FILE>) { print "$filename: $_"; }; Although this code clearly expects its file to be opened for reading, the file name might indicate a shell command. It might also indicate a file to be written rather than read. ## Noncompliant Code Example (<) ## This noncompliant code example attempts to mitigate the problem by prepending a #ffcccc perl my $filename = # initialize open(my $FILE, "<$filename") or croak("file not found"); while (<$FILE>) { print "$filename: $_"; }; If $filename begins or ends with | , the preceding < forces it to be treated as a file name rather than a shell command. This code will not execute a shell command. However, an attacker could cause a program to hang by supplying - as the file name, which is interpreted by open() as reading standard input. ## Noncompliant Code Example ( ) ## This noncompliant code example uses the operator. #ffcccc perl while (<ARGV>) { print ":: $_"; }; This code suffers from the same vulnerability as the first noncompliant code example. The <ARGV> operator opens every file provided in the @ARGV array and returns a line from each file. Unfortunately, it uses the two-argument form of open() to accomplish this task. If any element of @ARGV begins or ends with | , it is interpreted as a shell command and executed. ## Noncompliant Code Example (<>) ## This noncompliant code example uses the<>operator, known as the diamond operator. #ffcccc perl while (<>) { print ":: $_"; }; The <> operator is a synonym for <ARGV> and has the same behavior with the same vulnerability. ## Noncompliant Code Example (-n) ## This noncompliant code example uses the-nargument to Perl. #ffcccc perl -n 'print ":: $_\n";' * This code suffers from the same vulnerability as the previous noncompliant code example. The -n argument instructs Perl to open every file in the command line (in this case, every file in the current directory) and return a line from each file. If any argument in the command begins or ends with | , it is interpreted as a shell command and executed. In this manner, the -n operator acts exactly like the two-argument form of open() . ## Noncompliant Code Example (-p) ## This noncompliant code example uses the-pargument to Perl. #ffcccc perl -p '$_ = ":: $_\n";' * This code suffers from the same vulnerability as the previous noncompliant code example. The -p argument instructs Perl to open every file in the command line (in this case, every file in the current directory) and return a line from each file. Unlike -n , -p also instructs Perl to print the line read (stored in $_ ) at the end of each iteration of its implicit loop. If any argument in the command begins or ends with | , it is interpreted as a shell command and executed. In this manner, the -n operator acts exactly like the two-argument form of open() .
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 $FILE, "<", $filename) or croak("file not found"); while (<$FILE>) { print "$filename: $_"; }; The three-argument invocations of open() are not subject to the same vulnerabilities as the two-argument open() . In this code, $filename is treated as a file name even if it contains characters that are treated specially by the two-argument open() function. For example, if $filename is specified as - , then the three-argument open() attempts to open a file named - rather than opening standard input. ## Compliant Solution (<<>>) ## This compliant solution uses the<<>>operator, known as the double diamond operator. #ccccff perl while (<<>>) { print ":: $_"; }; The <<>> operator works like the <> operator except for using the three-argument form of open() (with "<" as the second argument) to accomplish this task.
## 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. Consider the following example: perl my @array = (1, 2, 3); # array initialized print "Array size is $#array\n"; # 2 (index of last element) $array[5] = 0; # array grows so that reference is valid print "Array size is $#array\n"; # 5 my $value = $array[7]; # array unchanged + uninitialized value warning $value = $array[-7]; # array unchanged + uninitialized value warning if (exists $array[9]) { # false, array unchanged print "That's a big array.\n"; } print "Array size is $#array\n"; # still 5 $value = $array[10][0]; # reading a value in list context grows array print "Array size is $#array\n"; # 10! This automatic growth occurs only if the index provided is positive and the array value is being written, not read, and not passed to a testing function like exists() or defined() . If an attacker is able to substitute a number to be used as an array index and provides the value 1000000000 (1 billion), then Perl will happily try to grow the array to 1 billion elements. Depending on the platform's capabilities, the attempt to grow the array might fail, or hang, or simply cause Perl to consume several gigabytes of memory for the lifetime of the array. Because a consequent denial of service could occur, attackers must not be permitted to control array indices.
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 input and adds them to an array, indexed by their UIDs. This program may, for instance, be fed the contents of the /etc/passwd file. #ffcccc perl 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 This code clearly skips input lines that do not contain a valid UID or user name. It also skips lines where the UID is not a positive number. However, a UID that is large might cause excessive growth of the @users array and provoke a denial of service.
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 solution enforces a limit on how large a UID may be. Consequently, the array may not contain more than $max_uid elements. #ccccff perl 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
## 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 subsystem must parse. Such data must be sanitized both because the subsystem may be unprepared to handle the malformed input and because unsanitized input may include an injection attack. In particular, programs must sanitize all string data that is passed to command interpreters or parsers so that the resulting string is innocuous in the context in which it is parsed or interpreted. Many command interpreters and parsers provide their own sanitization and validation methods. When available, their use is preferred over custom sanitization techniques because custom-developed sanitization can often neglect special cases or hidden complexities in the parser. Another problem with custom sanitization code is that it may not be adequately maintained when new capabilities are added to the command interpreter or parser software.
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 noncompliant code example demonstrates an XSS exploit. This code uses the CGI module to display a web form and is adopted from an example from the CGI.pm documentation . The form queries the user for a name and displays the resulting name on the page when the user clicks Submit . #ffcccc perl 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; When fed a benign name, such as Larry , this script works well enough: But this code will happily parse image tags, HTML markup, JavaScript, or any other commands an attacker may wish to send. The following picture demonstrates a remote image being loaded into the page on the request of the attacker: In this case. the trust boundary exists between the untrusted data and the CGI script, whereas the trusted domain is the web browser—or rather the HTML parsing and rendering engine within the web browser. More details about sanitization of this code example can be found in IDS01-PL. Use taint mode while being aware of its limitations . ## Noncompliant Code Example (Taint Mode) Using taint mode will not detect or prevent XSS. Taint mode does not prevent tainted data from being printed to standard output.
# 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=<PASSWORD> ' OR '1'='1 SELECT * FROM Users WHERE userid='' AND password='' OR '1'='1' use DBI; my $dbfile = "users.db"; my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","") or die "Couldn't connect to database: " . DBI->errstr; sub hash { # hash the password } print "Enter your id: "; my $userid = <STDIN>; chomp $userid; print "Enter your password: "; my $password = <STDIN>; chomp $password; my $hashed_password = hash( $password); my $sth = $dbh->prepare("SELECT * FROM Users WHERE userid = '$userid' AND password = '$hashed_password'") or die "Couldn't prepare statement: " . $dbh->errstr; $sth->execute() or die "Couldn't execute statement: " . $sth->errstr; if (my @data = $sth->fetchrow_array()) { my $username = $data[1]; my $id = $data[2]; print "Access granted to user: $username ($userid)\n"; } if ($sth->rows == 0) { print "Invalid username / password. Access denied\n"; } $sth->finish; $dbh->disconnect; # ... beginning of code my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","") or die "Couldn't connect to database: " . DBI->errstr; $dbh->{TaintIn} = 1; # ... rest of ocde # ... beginning of code my $sth = $dbh->prepare("SELECT * FROM Users WHERE userid = ? AND password = ?") or die "Couldn't prepare statement: " . $dbh->errstr; $sth->execute($userid, $hashed_password) or die "Couldn't execute statement: " . $sth->errstr; # ... rest of code ## Compliant Solution (XSS) To prevent injection of HTML, JavaScript, or malicious images, any untrusted input must be sanitized. This compliant solution sanitizes the input using the escapeHTML() subroutine from the CGI library. #ccccff perl # rest of code unchanged if (param()) { print "Your name is: ", em(escapeHTML(param('name'))), hr; } print end_html; When fed the malicious image tag demonstrated previously, the escapeHTML() subroutine sanitizes characters that might be misinterpreted by a web browser, causing the name to appear exactly as it was entered: SQL Injection A SQL injection vulnerability arises when the original SQL query can be altered to form an altogether different query. Execution of this altered query may result in information leaks or data modification. The primary means of preventing SQL injection are sanitizing and validating untrusted input and parameterizing queries. Suppose a database contains user names and passwords used to authenticate users of the system. A SQL command to authenticate a user might take the form: SELECT * FROM Users WHERE userid='<USERID>' AND password='<PASSWORD>' If it returns any records, the user ID and password are valid. However, if an attacker can substitute arbitrary strings for <USERID> and <PASSWORD> , he can perform a SQL injection by using the following string for <USERID> : validuser' OR '1'='1 When injected into the command, the command becomes SELECT * FROM Users WHERE userid='validuser' OR '1'='1' AND password=<PASSWORD> If validuser is a valid user name, this SELECT statement selects the validuser record in the table. The password is never checked because userid='validuser' is true; consequently, the items after the OR are not tested. As long as the components after the OR generate a syntactically correct SQL expression, the attacker is granted the access of validuser . Likewise, an attacker could supply a string for <PASSWORD> such as: ' OR '1'='1 This would yield the following command: SELECT * FROM Users WHERE userid='' AND password='' OR '1'='1' This time, the '1'='1' tautology disables both user ID and password validation, and the attacker is falsely logged in without a correct login ID or password. Noncompliant Code Example (SQL Injection) This noncompliant code example shows Perl DBI code to authenticate a user to a system. The program connects to a database, prompts the user for a user ID and password, and hashes the password. Unfortunately, this code example permits a SQL injection attack because the string passed to prepare accepts unsanitized input arguments. The attack scenario outlined previously would work as described. #ffcccc perl use DBI; my $dbfile = "users.db"; my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","") or die "Couldn't connect to database: " . DBI->errstr; sub hash { # hash the password } print "Enter your id: "; my $userid = <STDIN>; chomp $userid; print "Enter your password: "; my $password = <STDIN>; chomp $password; my $hashed_password = hash( $password); my $sth = $dbh->prepare("SELECT * FROM Users WHERE userid = '$userid' AND password = '$hashed_password'") or die "Couldn't prepare statement: " . $dbh->errstr; $sth->execute() or die "Couldn't execute statement: " . $sth->errstr; if (my @data = $sth->fetchrow_array()) { my $username = $data[1]; my $id = $data[2]; print "Access granted to user: $username ($userid)\n"; } if ($sth->rows == 0) { print "Invalid username / password. Access denied\n"; } $sth->finish; $dbh->disconnect; ## Compliant Solution (Taint Mode) One way to find potential injection points quickly is to use Perl's taint mode. #ccccff perl # ... beginning of code my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","") or die "Couldn't connect to database: " . DBI->errstr; $dbh->{TaintIn} = 1; # ... rest of ocde Perl will refuse to permit tainted data from entering the database via the prepare() method call. It will immediately exit with an error message: Note that not only must the program be run in taint mode, but the TaintIn attribute must be set on the connection handle, enabling taint checks to be run on the database. Compliant Solution (Prepared Statement) Fortunately, Perl's DBI library provides an API for building SQL commands that sanitize untrusted data. The prepare() method properly escapes input strings, preventing SQL injection when used properly. This is an example of component-based sanitization. #ccccff perl # ... beginning of code my $sth = $dbh->prepare("SELECT * FROM Users WHERE userid = ? AND password = ?") or die "Couldn't prepare statement: " . $dbh->errstr; $sth->execute($userid, $hashed_password) or die "Couldn't execute statement: " . $sth->errstr; # ... rest of code
## 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 in the execution of external programs. The exec() built-in function is the standard mechanism for executing system commands; it is a wrapper around the POSIX exec family of system calls. The system() built-in function is similar to exec , but it takes a single string, whereas exec() takes a list. The qx operator, often represented by encasing a command in backquotes ( `` ), can also be used to execute an arbitrary command. Finally, the open() function can also execute commands in a subprocess and either send data to them or fetch data from them (but not both). Command injection attacks cannot succeed unless a command interpreter is explicitly invoked. However, argument injection attacks can occur when arguments have spaces, double quotes, and so forth, or when they start with a - or / to indicate a switch. This rule is a specific instance of . Any string data that originates from outside the program's trust boundary must be sanitized before being executed as a command on the current platform.
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 or directory Result: bad % ./example.pl sub do { shift; $do_call = "xmms -" . shift; system $do_call; return $do_call; } ## Noncompliant Code Example (open()) This noncompliant code example tries to list a directory specified by the user. It safely uses the three-argument open() command, as required by . #ffcccc perl my $dir = $ARGV[0]; open( my $listing, "-|", "ls -F $dir") or croak "error executing command: stopped"; while (<$listing>) { print "Result: $_"; } close( $listing); The program also works properly when given a valid directory as an argument: % ./sample.pl ~ Result: bin/ Result: Desktop/ Result: src/ Result: workspace/ % But it can also have unintended consequences, as in this case, if an attacker injects an arbitrary command to be executed by the call to open() : % ./example.pl "dummy ; echo bad" ls: cannot access dummy: No such file or directory Result: bad % ./example.pl ## Noncompliant Code Example (VU#583020) US-CERT Vulnerability #583020 describes Perl code that invoked the system() built-ig function without sanitizing its argument: #ffcccc perl sub do { shift; $do_call = "xmms -" . shift; system $do_call; return $do_call; } An attacker who could control the arguments to the do() subroutine could cause the code to invoke arbitrary shell commands. This code also violates DCL31-PL. Do not overload reserved keywords or subroutines .
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 contains unsanitary characters, stopped at ./example.pl line 8 % 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); my %choices = (BIN => "~/bin", LIB => "~/lib", SRC => "~/src"); my $choice = $choices{$ARGV[0]}; croak "Invalid argument, stopped" if (!defined $choice); open( my $listing, "-|", "ls -F $choice") or croak "error executing command: stopped"; while (<$listing>) { print "Result: $_"; } close( $listing); my $dir = $ARGV[0]; opendir( my $listing, $dir) or croak "error executing command: stopped"; while (readdir($listing)) { print "Result: $_\n"; } closedir($listing); sub do { shift; $command = shift; $command =~ /([\w])/; $command = $1; $do_call = "xmms -" . $command; system $do_call; return $do_call; } ## Compliant Solution (Sanitization) This compliant solution sanitizes the untrusted user input by permitting only a small group of whitelisted characters in the argument that will be passed to open() ; all other characters are excluded. #ccccff perl 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); This code properly rejects shell commands: % ./example.pl "dummy ; echo bad" Argument contains unsanitary characters, stopped at ./example.pl line 8 % However, this code also rejects valid directories if they contain characters not in the whitelist regex. ## Compliant Solution (Shell Avoidance) ## This compliant solution again sanitizes the untrusted user input. However, it uses the multi-arg form ofopen(). #ccccff perl 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); The perlfunc manpages states, regarding all but the first two arguments to open() : If there is only one scalar argument, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing (this is "/bin/sh -c" on Unix platforms, but varies on other platforms). If there are no shell metacharacters in the argument, it is split into words and passed directly to "execvp," which is more efficient. So this form of open() is preferable if your platform's shell might be set up incorrectly or maliciously. ## Compliant Solution (Restricted Choice) This compliant solution prevents command injection by passing only trusted strings to open() . The user has control over which string is used but cannot provide string data directly to open() . #ccccff perl my %choices = (BIN => "~/bin", LIB => "~/lib", SRC => "~/src"); my $choice = $choices{$ARGV[0]}; croak "Invalid argument, stopped" if (!defined $choice); open( my $listing, "-|", "ls -F $choice") or croak "error executing command: stopped"; while (<$listing>) { print "Result: $_"; } close( $listing); ## This compliant solution hard codes the directories that may be listed. This solution can quickly become unmanageable if you have many available directories. A more scalable solution is to read all the permitted directories from an external file into a hash object, and the external file must be kept secure from untrusted users. ## Compliant Solution (Avoid Interpreters) When the task performed by executing a system command can be accomplished by some other means, it is almost always advisable to do so. This compliant solution uses the opendir() , readdir() , and closedir() subroutines to provide a directory listing, eliminating the possibility of command or argument injection attacks. #ccccff perl my $dir = $ARGV[0]; opendir( my $listing, $dir) or croak "error executing command: stopped"; while (readdir($listing)) { print "Result: $_\n"; } closedir($listing); ## Compliant Solution (VU#583020) This code was mitigated by adding a regex to make sure that only a single character supplied by the user could be added to the $do_call variable before passing it to system() . #ccccff perl sub do { shift; $command = shift; $command =~ /([\w])/; $command = $1; $do_call = "xmms -" . $command; system $do_call; return $do_call; } This code still violates DCL31-PL. Do not overload reserved keywords or subroutines ; it is shown here for historical accuracy.
## 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 would otherwise be fatal to the program and stores them in the $@ package variable. This role means that eval is critical to proper exception handling. If the code being evaluated is itself invalid (perhaps because it contains a syntax error), again, the error does not cause program termination, but is instead trapped by eval and saved in the $@ variable. When invoked with a block, the Perl parser compiles the block argument at the same time that it compiles the rest of the code, before it begins execution. Consequently, syntax errors or other compile-time errors are reported during compilation, before the program has begun executing. However, when eval invoked with a string argument, the argument is parsed and compiled only when the eval form actually executes, at run-time. Consequently, a syntax error is reported only when the eval form is actually executed. Furthermore, the argument gets compiled every time that eval is executed. Consequently, the block form of eval has better performance and reliability than the string form of eval . But, these issues aside, the string form of eval also allows it to execute any code. If an attacker can control the value of a scalar argument to eval , the attacker can cause any arbitrary code to be executed with the privileges of the running program. Therefore, the string form of eval must not be used.
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 quotient is 3 % my $module = "Foo::Bar"; # ... require $module; my $module = "Foo::Bar"; # ... eval "require $module"; % perl -e 'eval "use $ARGV[0]";' 'Foo::Bar' package Foo::Bar loaded % perl -e 'eval "use $ARGV[0]";' 'Foo::Bar ; print "Surprise!\n"' package Foo::Bar loaded Surprise! % ## Noncompliant Code Example Perl normally signals a fatal error if division by zero occurs. The eval built-in can be used to prevent such an error from terminating the program. This noncompliant code example uses the string-based eval to reduce the severity of a division-by-zero error to a mere warning. #ffcccc perl my $a = $ARGV[0]; my $b = $ARGV[1]; my $answer = 0; eval qq{ \$answer = $a / $b }; carp $@ if $@; print "The quotient is $answer\n"; As shown below, when given normal input, this program behaves as expected: % ./divide.pl 18 3 The quotient is 6 % It also gracefully handles division by zero: % ./divide.pl 18 0 Illegal division by zero at (eval 1) line 1. The quotient is 0 % But it also allows the caller to invoke arbitrary Perl code: % ./divide.pl 18 '6 ; print "Surprise!\n"' Surprise! The quotient is 3 % ## Noncompliant Code Example ## This noncompliant code example attempts to load a module that is specified by a variable. #ffcccc perl my $module = "Foo::Bar"; # ... require $module; This code does not behave properly, as require does no pathname interpolation when loading a module specified by a variable, and so it attempts to search the filesystem for a file named Foo::Bar . ## Noncompliant Code Example The perlfunc manpage recommends using the string-based form of eval when importing a module with require or use , where the name of the module may be stored in a variable. To wit: If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. ... In other words, if you try this: require Foo::Bar; # a splendid bareword the require function will actually look for the "Foo/Bar.pm" file in the directories specified in the @INC array. But if you try this: $class = 'Foo::Bar'; require $class; # $class is not a bareword # or require "Foo::Bar"; # not a bareword because of the "" the require function will look for the "Foo::Bar" file in the @INC array and will complain about not finding "Foo::Bar" there. In this case you can do: eval "require $class"; ## This noncompliant code example usesevalto load a module specified by a variable. #ffcccc perl my $module = "Foo::Bar"; # ... eval "require $module"; While this code properly searches the include paths for the file Foo/Bar.pm , it also suffers from command injection, as shown in the following transcript: % perl -e 'eval "use $ARGV[0]";' 'Foo::Bar' package Foo::Bar loaded % perl -e 'eval "use $ARGV[0]";' 'Foo::Bar ; print "Surprise!\n"' package Foo::Bar loaded Surprise! %
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 "Surprise!\\n"" isn't numeric in division (/) at ./divide.pl line 12. The quotient is 3 % use Module::Load;   my $module = "Foo::Bar"; # ... load $module; eval $x ; # string-based, noncompliant, evaluates value of $x eval "$x"; # string-based, noncompliant, evaluates value of $x eval '$x'; # string-based, noncompliant, returns value of $x (unevaluated) eval {$x}; # block-based, compliant, returns value of $x (unevaluated) ## Compliant Solution This compliant solution uses the block-based form of eval . In addition to foiling any attempts to evaluate untrusted code, this form of eval parses its argument at compile time rather than run-time. Performance is improved, and any syntax errors with the code are still caught and reported. #ccccff perl my $a = $ARGV[0]; my $b = $ARGV[1]; my $answer = 0; eval { $answer = $a / $b; }; carp $@ if $@; print "The quotient is $answer\n"; As shown below, this code behaves as in the previous example, but the division operation causes a warning when given non-numeric (malicious) input and ignores the malicious code. % ./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 "Surprise!\\n"" isn't numeric in division (/) at ./divide.pl line 12. The quotient is 3 % ## Compliant Solution This compliant solution uses the built-in Module::Load package which provides the ability to import modules specified by a variable. The load function prevents command injection. #ccccff perl use Module::Load; my $module = "Foo::Bar"; # ... load $module; Exceptions IDS35-PL-EX0 : This rule specifically forbids passing a scalar string or expression to eval . It does not forbid passing a block to eval . eval $x ; # string-based, noncompliant, evaluates value of $x eval "$x"; # string-based, noncompliant, evaluates value of $x eval '$x'; # string-based, noncompliant, returns value of $x (unevaluated) eval {$x}; # block-based, compliant, returns value of $x (unevaluated)
## 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. Consequently, do not prefix an integer with leading zeros. If it is to be interpreted as octal, use the oct() function, which clearly indicates the number to be treated as octal. perl my $perm1 = 0644; # noncompliant, octal my $perm2 = "0644"; # noncompliant, decimal my $perm3 = oct("644"); # compliant, octal my $perm4 = 644; # compliant, decimal
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 programmers who are not aware of its usage.
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 is because the numbers, while integral, are too large to be represented internally as integers, so they are represented as 32-bit floating-point numbers. Even with 24-bit mantissas, the numbers are too large for an increment of 1 to be noticed. Consequently, the program forever prints out the number 1e+16 . #ffcccc perl my $x = 10000000000000000; # 1e+16 for (my $y = $x; $y <= $x + 5; $y += 1) { print "$y\n"; }
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 numbers less than 2 48 (that is, 281,474,976,710,656). #ccccff perl my $x = 10000000000000000; # 1e+16 for (my $y = 0; $y <= 5; $y += 1) { my $z = $x + $y; print "$z\n"; } On a 32-bit machine, this program terminates normally after printing the following: 1e+16 1e+16 1e+16 1e+16 1e+16 1e+16 ## Compliant Solution This compliant solution uses the Bignum module to ensure precise computation. The Bignum module is available in CPAN, but became part of Perl's standard library for version 5.8. #ccccff perl use bignum; my $x = 10000000000000000; # 1e+16 for (my $y = $x; $y <= $x + 5; $y += 1) { print "$y\n"; } On a 32-bit machine, this program terminates normally after printing the following: 10000000000000000 10000000000000001 10000000000000002 10000000000000003 10000000000000004 10000000000000005
## 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 Bibliography [ Gough 2005 ] Section 8.6, "Floating-point issues" [ IEEE 754 2006 ] [ CPAN ] Florian Ragwitz, bignum [ Meta CPAN ] perlnumber
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 eliminated.
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 cannot possibly execute. #ffcccc perl 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; }
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; $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; }
## 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 = shift; my $new_name = $name; $name =~ s/^([a-z])/\U$1\E/g; $name =~ s/ ([a-z])/ \U$1\E/g; return $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 L3
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) manpage dryly notes the first bug in Perl is that "the -w switch is not mandatory" [ Wall 2011 ] . The use warnings pragma must be used in all Perl code. One of the modules that Perl provides for additional safety is the strict module. It identifies programming constructs that are likely to be errors, such as unqualified and undeclared variables (that might be typos), dangerous references, and unqualified subroutine names. The use strict pragma must also be used in all Perl code. However, occasionally there is a need to disable warnings or strictness for some code that may look strange but is actually correct. The -w switch cannot enable or disable particular warnings on particular ranges of code. When a particular warning or strict checking must be disabled, the no warnings or no strict pragmas should be used in as minimal a scope as possible. They should also disable the specific warning or strictness checker that would trigger a warning or fatal error rather than disable all checks.
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 ($days{$day} eq 'work') { return 'work hard'; } if (exists $days{$day}) { return $days{$day}; } else { return "do nothing"; } } my $task = what_to_do('tomorrow'); print "Prepare to $task\n"; Use of uninitialized value within %days in string eq at ./example.pl line 16. Prepare to do nothing use warnings; use strict; no warnings 'uninitialized'; my %days = ("Sunday" => 'pray', # ... use strict; use warnings; our $sunday = 'pray'; our $monday = 'work'; our $tuesday = 'work'; our $wednesday = 'work'; our $thursday = 'work'; our $friday = 'work'; our $saturday = 'rest'; sub what_to_do { my $day = shift; no warnings 'uninitialized'; if ($$day eq 'work') { return 'work hard'; } if (defined $$day) { return $$day; } else { return "do nothing"; } } my $task = what_to_do('tomorrow'); print "Prepare to $task\n"; Can't use string ("tomorrow") as a SCALAR ref while "strict refs" in use at ./example.pl line 19. use warnings; use strict; no strict 'refs'; our $sunday = 'pray'; # ... Prepare to do nothing ## Noncompliant Code Example (warnings) ## This noncompliant code example contains code that produces an unchecked warning. #ffcccc perl 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 ($days{$day} eq 'work') { return 'work hard'; } if (exists $days{$day}) { return $days{$day}; } else { return "do nothing"; } } my $task = what_to_do('tomorrow'); print "Prepare to $task\n"; This code produces the following output: Use of uninitialized value within %days in string eq at ./example.pl line 16. Prepare to do nothing ## Noncompliant Code Example (warnings) ## This noncompliant code example attempts to suppress the particular warning printed. #ffcccc perl use warnings; use strict; no warnings 'uninitialized'; my %days = ("Sunday" => 'pray', # ... Unfortunately, although this code correctly suppresses the warning message, it has the undesired effect of suppressing the warning message throughout the entire program and will likely suppress the warning in other lines of code that are not known to be correct. ## Noncompliant Code Example (strict) ## This noncompliant code example contains code that references a nonexistant variable. #ffcccc perl use strict; use warnings; our $sunday = 'pray'; our $monday = 'work'; our $tuesday = 'work'; our $wednesday = 'work'; our $thursday = 'work'; our $friday = 'work'; our $saturday = 'rest'; sub what_to_do { my $day = shift; no warnings 'uninitialized'; if ($$day eq 'work') { return 'work hard'; } if (defined $$day) { return $$day; } else { return "do nothing"; } } my $task = what_to_do('tomorrow'); print "Prepare to $task\n"; The strict pragma catches the improper reference and aborts the program, producing the following error message: Can't use string ("tomorrow") as a SCALAR ref while "strict refs" in use at ./example.pl line 19. ## Noncompliant Code Example (strict) This noncompliant code example disables the strict pragma, producing proper output. However, strictness is suppressed throughout the entire program. #ffcccc perl use warnings; use strict; no strict 'refs'; our $sunday = 'pray'; # ... This code produces the following output: Prepare to do nothing This example may be considered correct, but the code works by referencing a nonexistent variable $tomorrow .
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 eq 'work') { return 'work hard'; } if (defined $$day) { return $$day; } else { return "do nothing"; } } ## Compliant Solution (warnings) This compliant solution suppresses the warning in as minimal a scope as possible. Because the uninitialized warning is suppressed only inside the what_to_do subroutine, other regions of the code can still generate this warning. #ccccff perl 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"; } } ## Compliant Solution (strict) This compliant solution suppresses the strictness checking to as minimal a scope as possible. Because the strictness checking is suppressed only inside the what_to_do subroutine, other regions of the code can still be checked for strict compliance. #ccccff perl sub what_to_do { my $day = shift; no warnings 'uninitialized'; no strict 'refs'; if ($$day eq 'work') { return 'work hard'; } if (defined $$day) { return $$day; } else { return "do nothing"; } }
## 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 result is returned as the result of the comma operator. Comma operators are called thin commas [ Conway 2005 ]. This behavior was adopted from C. The potential for confusing thin commas with commas in list context is large enough to forbid use of thin commas. Commas must be used only to separate items in list context.
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. #ffcccc perl 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"; This code behaves as expected. The comma operator is used to separate the call to validate_file and subsequent call to print in the same statement. Consequently, the return value of validate_file is discarded before print is called. This line of code looks like it would behave the same but instead behaves quite differently: #ffcccc perl print validate_file($file), "hi!\n"; The print statement takes a list of items to print, and, in list context, the comma operator is assumed to separate list items. Consequently, if the file is valid, this program prints 1 before its friendly greeting.
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 invoked within one statement, a do block can be used to evaluate a list of expressions without using list context. #ccccff perl print do { validate_file($file); "hi!\n"};
## 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->SUPER::new(@_); # relies on established inheritance print "new Derived\n"; return $self; }; sub derived_value {return 2;} } BEGIN { my $derived = Derived->new(); my $b = $derived->base_value(); my $d = $derived->derived_value(); print "base_value = $b\n"; print "derived_value = $d\n"; } Can't locate object method "new" via package "Derived::SUPER" at ... ## Noncompliant Code Example (@ISA) ## This noncompliant code example defines a base class and an object class with simple methods: #ffcccc perl { 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->SUPER::new(@_); # relies on established inheritance print "new Derived\n"; return $self; }; sub derived_value {return 2;} } BEGIN { my $derived = Derived->new(); my $b = $derived->base_value(); my $d = $derived->derived_value(); print "base_value = $b\n"; print "derived_value = $d\n"; } When the code is run, we get a program error: Can't locate object method "new" via package "Derived::SUPER" at ... This error occurs because the BEGIN block is evaluated at the beginning of runtime, before the @ISA statement can be evaluated. Consequently, when the Derived::new() constructor is invoked, the Derived class has an empty parents list and therefore fails to invoke Base::new() .
# ... 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 Base new Derived base_value = 1 derived_value = 2 ## Compliant Solution (parent) ## This compliant solution uses theparentmodule rather than directly modifying the@ISAvariable. #ccccff perl # ... 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 The parent module establishes the inheritance hierarchy at parse time, before any runtime code, including the BEGIN block, is evaluated. When the Derived::new() constructor is invoked, Perl knows that Derived is an instance of Base , and the program produces the correct output: new Base new Derived base_value = 1 derived_value = 2
## 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 method or variable is not to be used outside the class by prefixing the method or variable name with an underscore ( _ ) [ Conway 2005 ]. Perl provides no inherent enforcement of this convention; however, it is followed by many modules in CPAN and other developers. This convention must not be violated.
{ 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_all_cars { return %_all_cars; } } my $mine = Car->new("Transam"); my $type = $mine->type(); print "I drive a $type.\n"; my $yours = Car->new("Corvette"); $type = $yours->type(); print "You drive a $type.\n"; my %cars = Car::_get_all_cars(); my @all = keys( %cars); my $count = $#all + 1; print "There are $count cars on the road.\n"; ## Noncompliant Code Example ## This noncompliant code example provides aCarpackage that registers cars and keeps track of all cars that it creates. #ffcccc perl { 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_all_cars { return %_all_cars; } } my $mine = Car->new("Transam"); my $type = $mine->type(); print "I drive a $type.\n"; my $yours = Car->new("Corvette"); $type = $yours->type(); print "You drive a $type.\n"; my %cars = Car::_get_all_cars(); my @all = keys( %cars); my $count = $#all + 1; print "There are $count cars on the road.\n"; This program behaves as expected, correctly reporting 2 cars on the road. However, it clearly violates encapsulation, because the _get_all_cars() method is considered private within the Car class.
{ 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 instead of any private method. #ccccff perl { 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";
## 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 $obj = new Class; # 'indirect object' syntax The perlobj manpage [ Wall 2011 ] states the following: The -> notation suffers from neither of these disturbing ambiguities, so we recommend you use it exclusively. However, you may still end up having to read code using the indirect object notation, so it's important to be familiar with it. Consequently, indirect object syntax shall not be used.
{ 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; # Invokes global new my $b2 = new Class Something; # Invokes Class::new my $b3 = new $class_to_use; # Surprise! invokes global new! ## Noncompliant Code Example ## This noncompliant code example demonstrates some of the hazards of using indirect call syntax. #ffcccc perl { 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; # Invokes global new my $b2 = new Class Something; # Invokes Class::new my $b3 = new $class_to_use; # Surprise! invokes global new! In this code, the last three statements use indirect object syntax to invoke a new subroutine. However, the Perl interpreter can easily misinterpret which subroutine is actually meant to be invoked. This behavior can be especially dangerous if the methods to be invoked live in different packages.
# ... 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 syntax, explicitly making their intent clear to both the developer and the Perl interpreter. #ccccff perl # ... 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
## 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 Perl do not reset the match variables, which makes it easier to write code that tests for a series of more specific cases and remembers the best match. Consequently, the value of a capture variable can be indeterminate if a previous regex failed. The value can also be overwritten on subsequent regex matches. Always ensure that a regex was successful before reading its capture variables.
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 example demonstrates the hazards of relying on capture variables without testing the success of a regex. #ffcccc perl 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"; This code produces the following output: cd is sr0 time is sr0 The surprising value for the $time variable arises because the regex fails, leaving the capture variable $1 still holding its previously assigned value sr0 .
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 solution, both regular expressions are checked for success before the capture variables are accessed. #ccccff perl 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"; } This code produces the following output: cd is sr0 This output might not be what the developer expected, but it clearly reveals that the latter regex failed to find a match.
## 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 string literal will be treated as if a regex that matched only that string literal were supplied. Unexpected function behavior can result if the string contains characters that have special meanings when the string is treated as a regex pattern. Therefore, do not pass strings that are not clearly regex patterns to a function that takes a regex.
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 string, no splitting occurs.
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$Harry'; my @names = split( m/\$/, $data);
## 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]

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
-