[Python-Dev] strncpy

Paul Prescod paul@prescod.net
Thu, 13 Jul 2000 01:07:30 -0500


Tim, Re: Patch #100874

Thanks for the quick disposition. I'll fix the style errors. It's just
so hard to concentrate on style when you're trying to fit code into the
5 character margin left by Guido's indentation style. Grrrr. ceval
reminds me of old BBS messages written on a Commodore-64, but read on a
17" monitor.

About this:

> char buf[500]; 
> ... followed by an unchecked sprintf into buf. 
> 
> This is a security hole: Python doesn't restrict identifiers to 
> being no longer than 500 chars, so a hacker can easily trick this 
> code into overwriting the buffer bounds.

I was prepared to be paranoid about this but then I saw this comment:

/* XXX There are several unchecked sprintf or strcat calls in this file.

   XXX The only way these can become a danger is if some C code in the

   XXX Python source (or in an extension) uses ridiculously long names

   XXX or riduculously deep nesting in format strings. */


I interpreted that as "Python enforces reasonable identifier lengths,
and only C code can violate it. I'm surprised to learn that Python
doesn't have a max identifier length #defined somewhere. Especially
since there is a defacto (probably undocumented) length limit for names
in C extensions (according to the comment above).


> Easy but tedious to
> fix (e.g., #define the buf length, and use runtime code in 
> conjunction with strncpy to guarantee buf's bounds are respected). 

Let me suggest two non-tedious solutions so you can shoot them down:

1. 

sprintf(buf, "Local variable referenced "
		"before assignment: %.128s",
		namestr);

Rationale: if you don't know what variable I'm talking about after 128
characters, you've got bigger problems than I can help with. I see this
solution elsewhere in the code.

2. 

Add an implementation of snprintf to our code and fix the other hundred
or so sprintf occurrences to use it. Most of them are safe but it
couldn't hurt to pass cleanly through those heuristic security checkers

Here's one:

http://www.ijs.si/software/snprintf/

And there is one in Apache.

-- 
 Paul Prescod - Not encumbered by corporate consensus
Simplicity does not precede complexity, but follows it. 
	- http://www.cs.yale.edu/~perlis-alan/quotes.html