sha1-name: check for overflow of N in "foo^N" and "foo~N"

Reject values that don't fit into an int, as get_parent() and get_nth_ancestor() cannot handle them. That's better than potentially returning a random object. If this restriction turns out to be too tight then we can switch to a wider data type, but we'd still have to check for overflow. Signed-off-by: René Scharfe <l.s.r@web.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>

René Scharfe committed Sep 15, 2019 at 14:10 UTC 59fa5f5a25d9ccc57558ac44cce83d37ac1cec58
2 files changed +14 -5
sha1-name.c
+12 -3
@@ -1163,13 +1163,22 @@ static enum get_oid_result get_oid_1(struct repository *r,
1163 }
1164
1165 if (has_suffix) {
1166 - int num = 0;
1166 + unsigned int num = 0;
1167 int len1 = cp - name;
1168 cp++;
1169 - while (cp < name + len)
1170 - num = num * 10 + *cp++ - '0';
1169 + while (cp < name + len) {
1170 + unsigned int digit = *cp++ - '0';
1171 + if (unsigned_mult_overflows(num, 10))
1172 + return MISSING_OBJECT;
1173 + num *= 10;
1174 + if (unsigned_add_overflows(num, digit))
1175 + return MISSING_OBJECT;
1176 + num += digit;
1177 + }
1178 if (!num && len1 == len - 1)
1179 num = 1;
1180 + else if (num > INT_MAX)
1181 + return MISSING_OBJECT;
1182 if (has_suffix == '^')
1183 return get_parent(r, name, len1, oid, num);
1184 /* else if (has_suffix == '~') -- goes without saying */
t/t1506-rev-parse-diagnosis.sh
+2 -2
@@ -215,11 +215,11 @@ test_expect_success 'arg before dashdash must be a revision (ambiguous)' '
215 test_cmp expect actual
216 '
217
218 -test_expect_failure 'reject Nth parent if N is too high' '
218 +test_expect_success 'reject Nth parent if N is too high' '
219 test_must_fail git rev-parse HEAD^100000000000000000000000000000000
220 '
221
222 -test_expect_failure 'reject Nth ancestor if N is too high' '
222 +test_expect_success 'reject Nth ancestor if N is too high' '
223 test_must_fail git rev-parse HEAD~100000000000000000000000000000000
224 '
225