BYTEORDER.NTOH.READ
Byte order not converted after network-to-host read
There are two main approaches to storing multibyte values: big-endian and little-endian. When data is being transferred between systems that use different methods, multibyte values should be converted from the host byte order to the network byte order, or the reverse. The BYTEORDER checkers look for multibyte values that aren't converted correctly in these situations.
The BYTEORDER.NTOH.READ checker reports cases in which a multibyte value isn't converted from network to host byte order after it's read from the environment.
Vulnerability and risk
When programs that run under systems with different byte-order methods need to communicate with each other, the failure to convert byte order may lead to unexpected behavior. Network-to-host and host-to-network conversion should be performed not only with network operations, but with file read/write operations, to ensure that the data is portable. An appropriate conversion function can be used to avoid this problem before the data is used.
Vulnerable code example
#include <unistd.h>
#include <netinet/in.h>
void test_06_myread(int d, short *p) {
read(d, p, sizeof *p);
}
void test_06_myread_wrapper(int d, short *p) {
test_06_myread(d, p);
}
int test_06_read(int d) {
short u;
test_06_myread_wrapper(d, &u);
return u - 12;
}
In this example, Klockwork reports BYTEORDER.NTOH.READ at line 17 to mark that 'u' is read from the file and used, but is not converted. In the network-to-host direction, 'u' should be converted to host values after it's read. If it's not fixed, this situation could result in unexpected program behavior.
Fixed code example
#include <unistd.h>
#include <netinet/in.h>
void test_06_myread(int d, short *p) {
read(d, p, sizeof *p);
}
void test_06_myread_wrapper(int d, short *p) {
test_06_myread(d, p);
}
int test_06_read(int d) {
short u;
test_06_myread_wrapper(d, &u);
return ntohs(u) - 12;
}
In the fixed code example, the read value of type 'short int' is converted by a call to function 'ntohs'. Reading the correct value type for the host means that the program will operate as intended.
Related checkers
External guidance
Extension
This checker can be extended. Platform-specific and application-specific information can be added through the Klocwork knowledge base. Configuration is used to describe properties of system functions that perform buffer manipulation. Several platform-specific configurations are provided as part of the standard distribution.
The related C/C++ knowledge base record kinds are:
See Tuning C/C++ analysis for more information.