Overlapping source and destination in sprintf/snprintf

ID

c.miscellaneous.incorrect_use_of_sprintf_snprintf

Severity

low

Resource

Miscellaneous

Language

C / C++

Description

C standards specify that the results are undefined if a call to sprintf(), snprintf(), vsprintf(), or vsnprintf() would cause copying to take place between objects that overlap (e.g., if the target string array and one of the supplied input arguments refer to the same buffer).

Rationale

C standards specify that the results are undefined if a call to sprintf(), snprintf(), vsprintf(), or vsnprintf() would cause copying to take place between objects that overlap (e.g., if the target string array and one of the supplied input arguments refer to the same buffer).

The following code illustrates a vulnerable pattern detected by this rule:

int test1()
{
	// ...
	for (oct_cnt = 1; oct_cnt < 7; oct_cnt++)
	{
		oct = (u_int8_t)retrieve_rand_int(0xFF);
		if (oct_cnt != 1)
			// VULNERABLE: Overlapping source and destination in sprintf/snprintf
			sprintf(eaddr, "%s:%0x", eaddr, oct);
		else
			sprintf(eaddr, "%0x", oct);
	}
	return eaddr;
}

Remediation

Follow secure coding practices and review the references below for detailed remediation guidance.

Configuration

This detector does not need any configuration.