shithub: riscv

Download patch

ref: c14ea9fdd1521ff9322f9af71b801e016622c0cd
parent: af6f03e52829a571f1fa3d61c0bfa09a1c89ea36
author: cinap_lenrek <cinap_lenrek@felloff.net>
date: Sat Mar 12 07:29:15 EST 2022

awk: fix off-by-one string buffer overflow from gsub

the bug happens when we did the fast exit thru "done" label,
where we would not make sure that theres space in the buffer
for the NUL terminator.

instead, avoid the fast exit and always do the final
adjbuf() that makes sure we have space for the NUL terminator.

remove the pointless pb checks, they'r wrong (should'v
been bp >= buf+bufsz) and adjbuf() already makes sure this
can never happen.

--- a/sys/src/cmd/awk/run.c
+++ b/sys/src/cmd/awk/run.c
@@ -1865,8 +1865,6 @@
 				*pb++ = *sptr++;
 		}
 		*pb = '\0';
-		if (pb > buf + bufsz)
-			FATAL("sub result1 %.30s too big; can't happen", buf);
 		sptr = patbeg + patlen;
 		if ((patlen == 0 && *patbeg) || (patlen && *(sptr-1))) {
 			adjbuf(&buf, &bufsz, 1+strlen(sptr)+pb-buf, 0, &pb, "sub");
@@ -1873,8 +1871,6 @@
 			while ((*pb++ = *sptr++) != 0)
 				;
 		}
-		if (pb > buf + bufsz)
-			FATAL("sub result2 %.30s too big; can't happen", buf);
 		setsval(x, buf);	/* BUG: should be able to avoid copy */
 		result = True;;
 	}
@@ -1934,11 +1930,9 @@
 					}
 				}
 				if (*c == 0)	/* at end */
-					goto done;
+					break;
 				adjbuf(&buf, &bufsz, 2+pb-buf, recsize, &pb, "gsub");
 				*pb++ = *c++;
-				if (pb > buf + bufsz)	/* BUG: not sure of this test */
-					FATAL("gsub result0 %.30s too big; can't happen", buf);
 				mflag = 0;
 			}
 			else {	/* matched nonempty string */
@@ -1962,10 +1956,12 @@
 						*pb++ = *sptr++;
 				}
 				c = patbeg + patlen;
-				if ((c[-1] == 0) || (*c == 0))
-					goto done;
-				if (pb > buf + bufsz)
-					FATAL("gsub result1 %.30s too big; can't happen", buf);
+				if (c[-1] == 0){
+					c--;
+					break;
+				}
+				if (*c == 0)
+					break;
 				mflag = 1;
 			}
 		} while (pmatch(p, t, c));
@@ -1973,9 +1969,6 @@
 		adjbuf(&buf, &bufsz, 1+strlen(sptr)+pb-buf, 0, &pb, "gsub");
 		while ((*pb++ = *sptr++) != 0)
 			;
-	done:	if (pb > buf + bufsz)
-			FATAL("gsub result2 %.30s too big; can't happen", buf);
-		*pb = '\0';
 		setsval(x, buf);	/* BUG: should be able to avoid copy + free */
 	}
 	if (istemp(x))