Skip to contentSkip to conversation

stack smash?

PATCH Jim Meyering 3 participants 6 messages Aug 6, 2007 – Aug 8, 2007

lore
Share & tools
lore
#0 lore raw

In the vicinity of today's s/newname/new_name/ change, I spotted what looks like a potential stack smashing bug, though I confess I haven't tried to provoke it yet. It would require an abusively long name, where the original has length < PATH_MAX, but the new one's longer final component would make strcpy write beyond the end of new_name. Patch below.

Caveat: There may well be code somewhere that ensures ->path_live is so much shorter than PATH_MAX that this is a non-issue. But if that's the case, please let me know and instead, I'll add a comment or some sort of assertion here to that effect.

Assuming this patch is on the right track (yes, I'll test first), any preference on where to #define MIN? Or different spelling? Obviously, it doesn't belong in this file.

Jim

lib/format_text/format-text.c +15 -3
index 9085b2d..d1eb85f 100644
@@ -39,6 +39,9 @@
 #define FMT_TEXT_NAME "lvm2"
 #define FMT_TEXT_ALIAS "text"
 
+#undef MIN
+#define MIN(x,y) ((x) < (y) ? (x) : (y))
+
 static struct mda_header *_raw_read_mda_header(const struct format_type *fmt,
 					       struct device_area *dev_area);
 
@@ -939,8 +942,6 @@ static int _vg_commit_file(struct format_instance *fid, struct volume_group *vg,
 {
 	struct text_context *tc = (struct text_context *) mda->metadata_locn;
 	char *slash;
-	char new_name[PATH_MAX];
-	size_t len;
 
 	if (!_vg_commit_file_backup(fid, vg, mda))
 		return 0;
@@ -952,14 +953,25 @@ static int _vg_commit_file(struct format_instance *fid, struct volume_group *vg,
 		slash = tc->path_live;
 
 	if (strcmp(slash, vg->name)) {
-		len = slash - tc->path_live;
+		char new_name[PATH_MAX];
+		size_t len = slash - tc->path_live;
+		size_t rem = sizeof new_name - len;
 		strncpy(new_name, tc->path_live, len);
+		if (strlen(vg->name) >= rem) {
+			/* Append "...\0" (or whatever will fit) for diag.  */
+			size_t n_dots = MIN(3, rem-1);
+			memset(new_name + len, '.', n_dots);
+			new_name[len + n_dots] = '\0';
+			errno = ENAMETOOLONG;
+			goto rename_failed;
+		}
 		strcpy(new_name + len, vg->name);
 		log_debug("Renaming %s to %s", tc->path_live, new_name);
 		if (test_mode())
 			log_verbose("Test mode: Skipping rename");
 		else {
 			if (rename(tc->path_live, new_name)) {
+		      rename_failed:
 				log_error("%s: rename to %s failed: %s",
 					  tc->path_live, new_name,
 					  strerror(errno));
#1 lore raw
Quoted 4 lines · Jim Meyering

Caveat: There may well be code somewhere that ensures ->path_live is so much shorter than PATH_MAX that this is a non-issue. But if that's the case, please let me know and instead, I'll add a comment or some sort of assertion here to that effect.

Can you fix this at source? i.e. Add a path size restriction when the original string is read from the config file, after allowing for the maximum permitted vgname (NAME_LEN) and suffix.

Quoted 2 lines

Assuming this patch is on the right track (yes, I'll test first), any preference on where to #define MIN?

It's sad this has never made it into a standard include file, but there are numerous instances of it under /usr/include.

How about adopting the linux kernel version of this with its enforced type checking?

Quoted 1 line

Obviously, it doesn't belong in this file.

Could include in the new util.h?

lib/format_text/format-text.c static int _vg_commit_file(struct format_instance *fid, struct volume_group *vg, · line 956

Quoted 2 lines
lib/format_text/format-text.c +1 -0
 	if (strcmp(slash, vg->name)) {
+		char new_name[PATH_MAX];

We define all variables at the top of the function.
If there's a strong feeling a variable should be defined locally to a block, then instead we split the block out into a separate function.

Alasdair

Signature · 1 line
agk at redhat.com
#2 lore raw
Quoted 9 lines · Alasdair G Kergon
Quoted 4 lines · Jim Meyering

Caveat: There may well be code somewhere that ensures ->path_live is so much shorter than PATH_MAX that this is a non-issue. But if that's the case, please let me know and instead, I'll add a comment or some sort of assertion here to that effect.

Can you fix this at source? i.e. Add a path size restriction when the original string is read from the config file, after allowing for the maximum permitted vgname (NAME_LEN) and suffix.

I took a quick look and think I saw a command-line source, too. IMHO, even if you can guarantee something like this at the source, it's good to have a run-time check right before the strcpy, since it's so "distant". Besides, some systems (Hurd) don't even define PATH_MAX (or make it very large), so it's better to minimize use of that macro. Also, isn't it overkill to limit all names to a length of < PATH_MAX - NAME_LEN - suffix_len, just to avoid the length check when renaming?

Quoted 8 lines
Quoted 2 lines

Assuming this patch is on the right track (yes, I'll test first), any preference on where to #define MIN?

It's sad this has never made it into a standard include file, but there are numerous instances of it under /usr/include.

How about adopting the linux kernel version of this with its enforced type checking?

Sure.

Quoted 8 lines
Quoted 1 line

Obviously, it doesn't belong in this file.

Could include in the new util.h?

lib/format_text/format-text.c static int _vg_commit_file(struct format_instance *fid, struct volume_group *vg, · line 956

Quoted 2 lines
lib/format_text/format-text.c +1 -0
 	if (strcmp(slash, vg->name)) {
+		char new_name[PATH_MAX];

We define all variables at the top of the function.

I think you did mention that LVM and DM have this convention. I find the contrary (scope as tightly as possible) makes code more readable and more robust. If you would consider relaxing this restriction, let me know: I'll be happy to provide justification. [BTW, what's the motivation for it? ]

I believe strongly enough in the benefit of this approach that (in coreutils) I've begun using the c99 feature that allows declarations after statements, and maintaining a c99-to-c89 patch set for those who are unable to compile with a c99-compliant compiler. However, note that I wouldn't propose going that far here. Simply allowing c*8*9 scoped declarations provides most of the benefits without the portability/maintenance hassle.

Quoted 2 lines

If there's a strong feeling a variable should be defined locally to a block, then instead we split the block out into a separate function.

#3 lore raw
Quoted 3 lines · Jim Meyering

isn't it overkill to limit all names to a
length of < PATH_MAX - NAME_LEN - suffix_len, just to avoid the length check when renaming?

If you specify a configuration option that adds restrictions to some standard operations, you need to find out immediately - at the time you make the change - not months later when you're attempting an urgent rename and you don't want to lose time changing your metadata configuration too.

And as far as they can, the tools need to warn you your operation isn't going to work *before* they start making any changes because we've hardly any recovery logic in there: you'd be expected to clean up manually after a failure like that one.

Quoted 3 lines

I find the contrary (scope as tightly as possible) makes code more readable and more robust.
[BTW, what's the motivation for it? ]

Readability: While you can get away with it in tiny blocks for variables only used in one place, as soon as people extend the code, adding nesting or making blocks larger it takes more effort for someone to read the code. You see a variable and want to glance at its declaration. With nested blocks your eye has several places to search; with C99 declaration-after-statement you've to search backwards through the whole function.

Alasdair

Signature · 1 line
agk at redhat.com
#4 lore raw

permitting tightly scoped declarations

Quoted 1 line · Alasdair G Kergon

On Tue, Aug 07, 2007 at 11:51:18PM +0200, Jim Meyering wrote:

...

Quoted 11 lines
Quoted 3 lines

I find the contrary (scope as tightly as possible) makes code more readable and more robust.
[BTW, what's the motivation for it? ]

Readability: While you can get away with it in tiny blocks for variables only used in one place, as soon as people extend the code, adding nesting or making blocks larger it takes more effort for someone to read the code. You see a variable and want to glance at its declaration. With nested blocks your eye has several places to search; with C99 declaration-after-statement you've to search backwards through the whole function.

I tried to make it clear that I'm *not* advocating the use of C99's declaration-after-statement here (doing that presents a portability "challenge"), but merely the c89 feature of allowing declarations at the beginning of any {}-block.

More precisely, it'd be nice if the code were allowed to evolve in a way that permits moving declarations "down" into scopes where they're used.

One important goal is to improve locality. I.e., to keep each variable declaration as close to its first use as possible. Then, when searching backwards from a variable's use, you're more likely to find its declaration nearby, on the same screen/printed-page, or even the same line. Having to look in one or two more places (you don't have nesting much deeper, I hope) when visually searching for a declaration is a small price to pay. There are many good reasons to move declarations "down" into the scopes where they are used. IMHO, this is like const-correctness in that you should move declarations down as much as possible, even when it means converting a single function-scoped declaration into two or more tightly-scoped declarations. (example below)

Another goal of tightly scoped declarations is to ensure that a variable is rendered unusable as soon as possible beyond its final use. Then, any attempt at out-of-scope reuse provokes a *compile*-time failure.

Keeping declarations tightly scoped also improves maintainability. This is probably one of the bigger benefits. Consider the following function, with all variables declared at the top:

  foo ()
  {
    int ..., t1, t2;
    for (...) {
      t1 = ...
      use t1
    }

    if (...) {
      t2 = ...
      use t2
    }

}

Now, imagine you're modifying this function, and accidentally change things so that the first loop uses t2 or the second one uses t1. In the above example, the result would compile just fine, and would probably result in a run-time failure. Now, move each variable's declaration "down" into the scope where it's used, and you can see that neither of those errors would get past the compiler:

  foo ()
  {
    for (...) {
      int t1 = ...
      use t1
    }
    if (...) {
      int t2 = ...
      use t2
    }

}

Another non-negligible advantage is that sometimes you can combine the declaration and the initial definition (as above), saving a few lines. That's always a good thing since it helps fit more code into a limited vertical viewing window.

Just as with "const", this makes you think more about the code, as you read/change/write it. If you see a variable declared within an if-block, you know right away that it's going to be used only in that context. If you see another declared in the outermost scope of a function, you can assume that it's not just some banal index or temporary.

If you go one step further (the part I'm *not* advocating here) and allow the c99 feature of declarations-after-code, you get a few more advantages. Consider this function:

  foo ()
  {
          int n = init_n();
          if (...) {
                  ...
                  ...<long block>...
                  ...
          }

          while (n <= N_MAXIMUM) {
                  ...
                  if (...)
                          ++n;
          }
          ...

}

Imagine reading the code above.
You have to wonder if "n" is modified before the while loop. While, (assuming it's not), if the declaration is moved "down", then it's obvious that it cannot be.

  foo ()
  {
          if (...) {
                  ...
                  ...<long block>...
                  ...
          }
          int n = init_n();
          while (n <= N_MAXIMUM) {
                  ...
                  if (...)
                          ++n;
          }
          ...

}

Quoted 1 line

From both maintenance and readability standpoints, I prefer the

latter form, since there is no risk that someone will introduce code to accidentally change "n" in the preceding if-block, and 'n's declaration is that much nearer the majority of its uses.

Of course, still using c99, you can go one step further and use a for-loop to ensure that "n" is not accidentally used beyond the loop:

          for (int n = init_n(); n <= N_MAXIMUM; ) {
                  ...
                  if (...)
                          ++n;
          }
          ...

There.(!)
Now you know why I like tightly-scoped declarations.

#5 lore raw

permitting tightly scoped declarations

Well, i would probably vote for allowing C99-style declarations anywhere, but even declarations at the start of the block would be an improvement... IMHO / personal preference (ie. i find code easier to write, easier to read and getting better compile-time checks, too).

Yours (C++-spoilt) Peter.

Signature · 6 lines
Peter Rockai | me()mornfall!net | prockai()redhat!com
 http://blog.mornfall.net | http://web.mornfall.net

"In My Egotistical Opinion, most people's C programs should be
 indented six feet downward and covered with dirt."
     -- Blair P. Houghton on the subject of C program indentation