Main Content

CWE Rule 187

Partial String Comparison

Since R2026a

Description

The product performs a comparison that only examines a portion of a factor before determining whether there is a match, such as a substring, leading to resultant weaknesses

Polyspace Implementation

Polyspace® checks for the issue Partial String Comparison

Examples

expand all

Issue

This issue occurs when you compare two strings by calling string comparison functions such as strncmp with a length parameter that is not greater than or equal to the size of each string. For example:

const char* inUser = "u";
const char* username = "actualuser";
strncmp(username,inUser, strlen(inuser));
This code compares only the first byte of username and inUser because the length parameter is the size of inuser. Polyspace reports a violation.

Polyspace does not report violations of this rule on user inputs or arguments of main() function.

Risk

Relying on partial string matches reduces effectiveness of security measures. For example, if the length parameter is not greater than or equal to each argument string, attackers can gain access by supplying a partial guess. partial string comparison reduces the search space for secrets and makes your systems more vulnerable to attacks.

Fix

If you use strncmp for string comparison, set the length parameter to the be greater than or equal to each string. For prefix checking in C++, use std::starts_with.

Example

This example shows code where the comparison length comes from an untrusted input, causing only a prefix to be checked.

#include <stdio.h>
#include <string.h>
#define MAXLEN(a, b) (strlen(a) > strlen(b) ? strlen(a) : strlen(b))

int authenticate(const char *stored, const char *provided) {
	if(strncmp(stored, provided, strlen(provided)) == 0) {  //Noncompliant
		return 1; /* authenticated */
	}
	return 0;
}

int main(void) {
	const char *secret = "S3cretKey";
	printf("%d\n", authenticate(secret, "S"));
	return 0;
}
Correction

The corrected code shows the entire stored secret is compared against the provided value.

#include <stdio.h>
#include <string.h>
#define MAXLEN(a, b) (strlen(a) > strlen(b) ? strlen(a) : strlen(b))

int authenticate(const char *stored, const char *provided) {
    if (strncmp(stored, provided, MAXLEN(stored,provided)) == 0) { //Compliant
        return 1; /* authenticated */
    }
}

int main(void) {
    const char *secret = "S3cretKey";
    printf("%d\n", authenticate(secret, "S"));  
    return 0;
}

Check Information

Category: Others
PQL Name: std.cwe_native.R187

Version History

Introduced in R2026a