PORTING.UNSIGNEDCHAR.OVERFLOW.FALSE

Relational expression may be always false

The PORTING checkers identify code that might rely on specific implementation details in different compilers. The PORTING.UNSIGNEDCHAR.OVERFLOW.FALSE checker detects situations in which a relational expression may be always false, depending on 'char' type signedness.

Vulnerability and risk

The 'char' data type isn't precisely defined in the C standard, so an instance may or may not be considered to be signed. Some compilers allow the sign of 'char' to be switched using compiler options, but best practice is for developers to write unambiguous code at all times to avoid problems in porting code.

Mitigation and prevention

Always specify whether or not the 'char' type is signed. This is best done by a using a typedef or #define definition that is then rigorously used everywhere.

Vulnerable code example

Copy
   int has_utf8_byte_order_mark(char *s) {
     return s[0] == 0xEF && s[1] == 0xBB && s[2] == 0xBF;  /* PORTING.UNSIGNEDCHAR.OVERFLOW.FALSE */
   }
   int main() {
     char *s = "\xEF\xBB\xBFHello, World!\n";
     if (has_utf8_byte_order_mark(s)) {
       printf("unicode\n");
     } else {
       printf("not unicode\n");
    }
    return 0;
  }

In this example, the code would detect a UTF-8 byte-order mark only when char is unsigned.

Fixed code example 1

Copy
   int has_utf8_byte_order_mark(char *s) {
     return s[0] == '\xEF' && s[1] == '\xBB' && s[2] == '\xBF';
   }
   int main() {
     char *s = "\xEF\xBB\xBFHello, World!\n";
     if (has_utf8_byte_order_mark(s)) {
       printf("unicode\n");
     } else {
       printf("not unicode\n");
    }
    return 0;
  }

In this example, the fixed code uses char literals in the comparison, rather than integer literals.

Fixed code example 2

Copy
   int has_utf8_byte_order_mark(unsigned char *s) {
     return s[0] == 0xEF && s[1] == 0xBB && s[2] == 0xBF;  
   }
   int main() {
     char *s = "\xEF\xBB\xBFHello, World!\n";
     if (has_utf8_byte_order_mark(s)) {
       printf("unicode\n");
     } else {
       printf("not unicode\n");
    }
    return 0;
  }

In this approach, unsigned char is used instead of char.

External guidance

Security training

Application security training materials provided by Secure Code Warrior.