Date: Mon, 29 Nov 2004 15:26:12 -0500 From: Charles Swiger <cswiger@mac.com> To: Brooks Davis <brooks@one-eyed-alien.net> Cc: ipfw@freebsd.org Subject: Re: strncmp usage in ipfw Message-ID: <E9480AE5-4244-11D9-9087-003065ABFD92@mac.com> In-Reply-To: <20041129192514.GA7331@odin.ac.hmc.edu> References: <20041129192514.GA7331@odin.ac.hmc.edu>
next in thread | previous in thread | raw e-mail | index | archive | help
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. Since the topic came up, it's also potentially dangerous to write code like: char errstr[1024]; /* ...intervening code... */ snprintf(errstr, 1024, "..."); ...because people making changes to the code may change the size of errstr without changing the 1024 in the snprintf(). Using a macro for the size is better practice: #define ERRLEN (1024) char errstr[ERRLEN]; /* ...intervening code... */ snprintf(errstr, ERRLEN, "..."); ...but the strong recommendation I've seen is to always use sizeof(): snprintf(errstr, sizeof(errstr), ...) 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))) ... -- -Chuck
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?E9480AE5-4244-11D9-9087-003065ABFD92>