Checkers:BYTEORDER.HTON.WRITE

From current

Reference > C/C++ checkers > BYTEORDER.HTON.WRITE

Byte order not converted before host-to-network write

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.HTON.WRITE checker reports cases in which a multibyte value that originates on the host side isn't converted from host to network byte order before it's written to the environment (for example, to file).

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 when writing data to the environment.

Code examples

Vulnerable code example

  1 #include <unistd.h>;
  2 #include <netinet/in.h>;
  3
  4
  5 void test_06_mywrite(int s, short *p) {
  6     write(s, p, sizeof *p);
  7 }
  8
  9 void test_06_mywrite_wrapper(int s, short *p) {
 10     test_06_mywrite(s, p);
 11 }
 12
 13
 14 void test_06_write(int s, short x) {
 15     short u = x + 12;
 16     test_06_mywrite_wrapper(s, &u); 
 17 }

Klocswork reports BYTEORDER.HTON.WRITE at line 16 to show that the value of 'u' is written, but not converted. In the host-to-network direction, 'u' should be converted to network values before it's written. If it's not fixed, this situation could result in unexpected program behavior.

Fixed code example

  1 #include <unistd.h>
  2 #include <netinet/in.h>
  3
  4
  5 void test_06_mywrite(int s, short *p) {
  6     write(s, p, sizeof *p);
  7 }
  8
  9 void test_06_mywrite_wrapper(int s, short *p) {
 10     test_06_mywrite(s, p);
 11 }
 12
 13
 14 void test_06_write(int s, short x) {
 15     short u = x + 12;
 16     u = htons(u);
 17     test_06_mywrite_wrapper(s, &u);
 18 }

In the fixed code, the value of type 'short int' is converted by a call to function 'htons' before being written. Writing the correct value type for the network 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.