From a9f9ff68320c7d2f7e97b22aa061d30be27b9b37 Mon Sep 17 00:00:00 2001
From: Moe Jette <jette1@llnl.gov>
Date: Sat, 1 Jan 2011 19:21:52 +0000
Subject: [PATCH] patch from Gerrit:
 07_hostlist__hostrange_pop__hostrange_shift.diff

hostrange_pop()/hostrange_shift(): test for overflow

hostrange_pop():
 * retrofitted out_of_memory() test after strdup;
 * tested for negative length/overflow before the while-loop,
   making sure that 'dims' characters also fit in;
 * second snprintf is not tested.

hostrange_shift():
 * analogous changes (second snprintf also not tested).
---
 src/common/hostlist.c | 18 ++++++++++--------
 1 file changed, 10 insertions(+), 8 deletions(-)

diff --git a/src/common/hostlist.c b/src/common/hostlist.c
index 78f5b80adeb..44b9c06f8b4 100644
--- a/src/common/hostlist.c
+++ b/src/common/hostlist.c
@@ -938,6 +938,8 @@ static char *hostrange_pop(hostrange_t hr)
 	if (hr->singlehost) {
 		hr->lo++;    /* effectively set count == 0 */
 		host = strdup(hr->prefix);
+		if (host == NULL)
+			out_of_memory("hostrange pop");
 	} else if (hostrange_count(hr) > 0) {
 		size = strlen(hr->prefix) + hr->width + 16;
 		if (!(host = (char *) malloc(size * sizeof(char))))
@@ -950,12 +952,12 @@ static char *hostrange_pop(hostrange_t hr)
 			hostlist_parse_int_to_array(hr->hi, coord, dims, 0);
 
 			len = snprintf(host, size, "%s", hr->prefix);
-			for (i2 = 0; i2 < dims; i2++) {
-				if (len <= size)
-					host[len++] = alpha_num[coord[i2]];
+			if (len >= 0 && len + dims < size) {
+				while (i2 < dims)
+					host[len++] = alpha_num[coord[i2++]];
+				host[len] = '\0';
 			}
 			hr->hi--;
-			host[len] = '\0';
 		} else {
 			snprintf(host, size, "%s%0*lu", hr->prefix,
 				 hr->width, hr->hi--);
@@ -990,12 +992,12 @@ static char *hostrange_shift(hostrange_t hr)
 			hostlist_parse_int_to_array(hr->lo, coord, dims, 0);
 
 			len = snprintf(host, size, "%s", hr->prefix);
-			for (i2 = 0; i2 < dims; i2++) {
-				if (len <= size)
-					host[len++] = alpha_num[coord[i2]];
+			if (len >= 0 && len + dims < size) {
+				while (i2 < dims)
+					host[len++] = alpha_num[coord[i2++]];
+				host[len] = '\0';
 			}
 			hr->lo++;
-			host[len] = '\0';
 		} else {
 			snprintf(host, size, "%s%0*lu", hr->prefix,
 				 hr->width, hr->lo++);
-- 
GitLab