BYTEORDER.NTOH.RECV

Byte order not converted after network-to-host receive

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.RECV checker reports cases in which a multibyte value isn't converted from network to host byte order after it's received.

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

1   #include <sys/types.h>
2   #include <sys/socket.h>
3   #include <netinet/in.h>
4
5   int test_01_recv_A(int s) {
6         short u;
7         recv(s, &u, sizeof u, 0);
8         return u - 12; 
9   }

Klocwork reports BYTEORDER.NTOH.RECV at line 8 to show that 'u' is received and used, but is not converted. In the network-to-host direction, 'u' should be converted to host values after it's received. If it's not fixed, this situation could result in unexpected program behavior.

Fixed code example

1   #include <sys/types.h>
2   #include <sys/socket.h>
3   #include <netinet/in.h>
4
5   int test_01_recv_B(int s) {
6         short u;
7         short v;
8         recv(s, &u, sizeof u, 0);
9         v = ntohs(u);
10        return v - 12; 
11  }

In the fixed code example, the received value of type 'short int' is converted by a call to function 'ntohs'. Receiving the correct value type for the host 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.