Safeguard
Application Security•

CWE-198 Use of Incorrect Byte Ordering: Endianness Bugs

Reading a multi byte value in the wrong byte order gives the wrong number. How CWE-198 hides in rare code paths and how to read data safely.

Safeguard Security Team
2 min read

CWE-198, Use of Incorrect Byte Ordering, describes a product that receives input from an upstream component but does not account for byte ordering, big-endian or little-endian, so it uses an incorrect number or value.

It affects network protocol parsers, file format readers, and code that moves data between machines with different architectures.

How it happens

A 16 bit value of 258 is sent as the bytes 01 02 in big-endian order and 02 01 in little-endian order. Read it with the wrong assumption and you get 513 instead of 258. When that number is a length, a count or an offset, the program then behaves in ways the author never planned.

// Fragile: depends on the host's byte order
uint16_t len = *(uint16_t *)(packet + 2);

// Portable: build the value from bytes in the documented order
uint16_t len = (uint16_t)((packet[2] << 8) | packet[3]);   // big-endian field

MITRE's listed consequence is integrity: the product ends up in an unexpected state. The record lists no observed CVE examples.

How to find it

MITRE makes an interesting point. Byte ordering bugs are usually very noticeable even with normal inputs, so the ones that survive are more likely in rarely triggered error conditions, which makes black box testing a poor fit. Code review and tests that run on both byte orders are better. If you cannot run a big-endian machine, an emulator will do.

How to fix it

The record gives no mitigations, so these are general steps.

  1. Document the byte order of every field in a protocol or file format.
  2. Convert explicitly on read and write, using standard conversion functions such as ntohs and ntohl, or by assembling values from bytes.
  3. Avoid casting raw buffers to integer pointers.
  4. Add tests with known byte patterns, including error paths.

Quick check

Why do these bugs hide in error paths? The main path gets exercised constantly and breaks visibly. Rarely used paths can carry the wrong assumption for years.

Sources

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.

Self-healing security runs on Safeguard.

Your first fix PR is minutes away.

No sales call required, even your agent can complete the purchase over MCP.