From 70b0fc1f78d4b745769244c427b1365c5e75a2fb Mon Sep 17 00:00:00 2001
From: Timur Safin <tsafin@tarantool.org>
Date: Fri, 31 Mar 2023 13:27:13 +0300
Subject: [PATCH] datetime: fix buffer overflow in tnt_strptime

Fixes #8502
Needed for #8490

NO_DOC=bugfix
NO_TEST=covered by fuzzing test

(cherry picked from commit 783a70406f79b7cc59bfe65a21a11fa35206fb66)
---
 .../gh-8502-fix-buffer-overflow-in-tnt_strptime.md    |  3 +++
 src/lib/tzcode/strptime.c                             | 11 +++++++----
 2 files changed, 10 insertions(+), 4 deletions(-)
 create mode 100644 changelogs/unreleased/gh-8502-fix-buffer-overflow-in-tnt_strptime.md

diff --git a/changelogs/unreleased/gh-8502-fix-buffer-overflow-in-tnt_strptime.md b/changelogs/unreleased/gh-8502-fix-buffer-overflow-in-tnt_strptime.md
new file mode 100644
index 0000000000..104e22ca52
--- /dev/null
+++ b/changelogs/unreleased/gh-8502-fix-buffer-overflow-in-tnt_strptime.md
@@ -0,0 +1,3 @@
+## bugfix/datetime
+
+* Fixed a bug with buffer overflow in tnt_strptime (gh-8502).
diff --git a/src/lib/tzcode/strptime.c b/src/lib/tzcode/strptime.c
index b208e2b965..4cc4351fc9 100644
--- a/src/lib/tzcode/strptime.c
+++ b/src/lib/tzcode/strptime.c
@@ -125,9 +125,11 @@ tnt_strptime(const char *__restrict buf, const char *__restrict fmt,
 		c = *ptr++;
 
 		if (c != '%') {
-			if (isspace((u_char)c))
+			/* Eat up white-space in buffer and in format. */
+			if (isspace((u_char)c)) {
 				while (*buf != 0 && isspace((u_char)*buf))
 					buf++;
+			}
 			else if (c != *buf++)
 				return NULL;
 			continue;
@@ -661,9 +663,10 @@ tnt_strptime(const char *__restrict buf, const char *__restrict fmt,
 	if ((flags & (FLAG_YEAR | FLAG_YDAY)) == (FLAG_YEAR | FLAG_YDAY)) {
 		if (!(flags & FLAG_MONTH)) {
 			i = 0;
-			while (tm->tm_yday >=
-			       start_of_month[isleap(tm->tm_year +
-						     TM_YEAR_BASE)][i])
+			while (i <= 12 &&
+			       tm->tm_yday >=
+				       start_of_month[isleap(tm->tm_year +
+							     TM_YEAR_BASE)][i])
 				i++;
 			if (i > 12) {
 				i = 1;
-- 
GitLab