strncmp usage in ipfw

Brooks Davis brooks at one-eyed-alien.net
Mon Nov 29 14:16:20 PST 2004


On Mon, Nov 29, 2004 at 03:26:12PM -0500, Charles Swiger wrote:
> On Nov 29, 2004, at 2:25 PM, Brooks Davis wrote:
> >char *var;
> >if (!strncmp(var, "str", strlen(var)))
> >	...
> >[ ... ]
> >Was use of this idiom deliberate or accidental?
> 
> I can't speak for the author, but using the "n"-for-length variant of 
> the string and printf() family of functions is considered an important 
> saftey practice, especially for network/firewall/IDS software which may 
> be exposed to externally generated data which contains deliberately 
> malicious string lengths.

That's true for string creation functions, but not for strncmp

The only valid use of strncmp is to do comparisons between strings where
one string is known to not be NUL-terminated or to look for a
sub-string.  It is not a safety function.

> This brings me back to your point with regard to partial matches; it 
> might be the case that the IPFW code could use char arrays and 
> sizeof(var) rather than char *'s and strlen(var) for some cases?  The 
> former approach would not only address your concerns, Brooks, but also 
> be faster.  Otherwise, I suspect that:
> 
> 	char *var;
> 	if (!strncmp(var, "str", strlen(var)))
> 		...
> 
> ...should become:
> 
> 	#define STR "str"
> 	char *var;
> 	if (!strncmp(var, STR, sizeof(STR)))
> 		...

This is exactly equivalent in functionality to:

 	char *var;
 	if (!strcmp(var, "str"))
 		...

We know that "str" is NUL-terminated because the C standard says it
is so we will stop at or before the sizeof("str")th character.  In
either case we are not protected from the possibility that var contains
a bogus string if the bogosity occurs before we get to the end of "str".
In fact, there's no way to be sure of that except creating the string
correctly in the first place!

-- Brooks

-- 
Any statement of the form "X is the one, true Y" is FALSE.
PGP fingerprint 655D 519C 26A7 82E7 2529  9BF0 5D8E 8BE9 F238 1AD4
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://lists.freebsd.org/pipermail/freebsd-ipfw/attachments/20041129/1f6d5175/attachment.bin


More information about the freebsd-ipfw mailing list