PORTING.BYTEORDER.SIZE

Use of an incompatible type with a network conversion macro

The PORTING checkers identify code that might rely on specific implementation details in different compilers. The PORTING.BYTEORDER.SIZE checker detects situations in which an incompatible type is used with network byte-order macros ntoh*() and hton*().

Vulnerability and risk

Based on the underlying ANSI semantics for type promotion and demotion, the common data transformation functions can accept inappropriate types as arguments, resulting in potentially incorrect transformations. In the worst case, this could cause random data to be transformed as part of the byte-manipulation process.

Mitigation and prevention

Always use the appropriate ntoh*() or hton*() variant when code is transforming data to or from a network.

Vulnerable code example

Copy
   unsigned short foo(int socket)
   {
     int len;
     unsigned short val = 0;
       len = read(socket, &val, sizeof(unsigned short));
       if( len == sizeof(unsigned short) )
           val = ntohl(val);     // PORTING.BYTEORDER.SIZE
       return val;
   }

The checker produces a warning at the line 7 because the size of the type being passed (unsigned short) is different from that expected by the transformation function, ntohl().

Fixed code example

Copy
   unsigned short foo(int socket)
   {
     int len;
     unsigned short val = 0;
       len = read(socket, &val, sizeof(unsigned short));
       if( len == sizeof(unsigned short) )
           val = ntohs(val);
       return val;
   }

The fixed example uses a size-appropriate macro for the transformation, ensuring that the expected bytes are swapped.