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.

Vulnerable code example

Copy
   #include <unistd.h>;
   #include <netinet/in.h>;
  
  
   void test_06_mywrite(int s, short *p) {
       write(s, p, sizeof *p);
   }
  
   void test_06_mywrite_wrapper(int s, short *p) {
      test_06_mywrite(s, p);
  }
 
 
  void test_06_write(int s, short x) {
      short u = x + 12;
      test_06_mywrite_wrapper(s, &u); 
  }

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

Copy
   #include <unistd.h>
   #include <netinet/in.h>
  
  
   void test_06_mywrite(int s, short *p) {
       write(s, p, sizeof *p);
   }
  
   void test_06_mywrite_wrapper(int s, short *p) {
      test_06_mywrite(s, p);
  }
 
 
  void test_06_write(int s, short x) {
      short u = x + 12;
      u = htons(u);
      test_06_mywrite_wrapper(s, &u);
  }

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.

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.