284
Fully specify which encodings are required by components that will be communicating with each
other.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same
character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set
the encoding you are using whenever the protocol allows you to do so.
Demonstrative Examples
Example 1:
This code displays an email address that was submitted as part of a form.
Example Language: JSP (Bad)
<% String email = request.getParameter("email"); %>
...
Email Address: <%= email %>
The value read from the form parameter is reflected back to the client browser without having been
encoded prior to output, allowing various XSS attacks (CWE-79).
Example 2:
Consider a chat application in which a front-end web application communicates with a back-end
server. The back-end is legacy code that does not perform authentication or authorization, so the
front-end must implement it. The chat protocol supports two commands, SAY and BAN, although
only administrators can use the BAN command. Each argument must be separated by a single
space. The raw inputs are URL-encoded. The messaging protocol allows multiple commands to be
specified on the same line if they are separated by a "|" character.
First let's look at the back end command processor code
Example Language: Perl (Bad)
$inputString = readLineFromFileHandle($serverFH);
# generate an array of strings separated by the "|" character.
@commands = split(/\|/, $inputString);
foreach $cmd (@commands) {
# separate the operator from its arguments based on a single whitespace
($operator, $args) = split(/ /, $cmd, 2);
$args = UrlDecode($args);
if ($operator eq "BAN") {
ExecuteBan($args);
}
elsif ($operator eq "SAY") {
ExecuteSay($args);
}
}
The front end web application receives a command, encodes it for sending to the server, performs
the authorization check, and sends the command to the server.
Example Language: Perl (Bad)
$inputString = GetUntrustedArgument("command");
($cmd, $argstr) = split(/\s+/, $inputString, 2);
# removes extra whitespace and also changes CRLF's to spaces
$argstr =~ s/\s+/ /gs;
$argstr = UrlEncode($argstr);
if (($cmd eq "BAN") && (! IsAdministrator($username))) {
die "Error: you are not the admin.\n";
}
# communicate with file server using a file handle
CWE Version 4.14
CWE-116: Improper Encoding or Escaping of Output
CWE-116: Improper Encoding or Escaping of Output