From 71ee60208e7da700113aed24c8957fec0f0095f1 Mon Sep 17 00:00:00 2001
From: deraadt <>
Date: Sun, 26 Sep 2021 14:07:40 +0000
Subject: Avoid a potential overread in x509_constraints_parse_mailbox()

The length checks need to be >= rather than > in order to ensure the string
remains NUL terminated. While here consistently check wi before using it
so we have the same idiom throughout this function.

Issue reported by GoldBinocle on GitHub.

ok deraadt@ tb@

this is 6.9 errata 017
---
 src/lib/libcrypto/x509/x509_constraints.c | 14 +++++++++-----
 1 file changed, 9 insertions(+), 5 deletions(-)

diff --git a/src/lib/libcrypto/x509/x509_constraints.c b/src/lib/libcrypto/x509/x509_constraints.c
index 5fbcef304f..55a7eae28f 100644
--- a/src/lib/libcrypto/x509/x509_constraints.c
+++ b/src/lib/libcrypto/x509/x509_constraints.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: x509_constraints.c,v 1.15 2021/03/12 15:57:30 tb Exp $ */
+/* $OpenBSD: x509_constraints.c,v 1.15.2.1 2021/09/26 14:07:40 deraadt Exp $ */
 /*
  * Copyright (c) 2020 Bob Beck <beck@openbsd.org>
  *
@@ -334,16 +334,16 @@ x509_constraints_parse_mailbox(uint8_t *candidate, size_t len,
 			if (c == '.')
 				goto bad;
 		}
-		if (wi > DOMAIN_PART_MAX_LEN)
-			goto bad;
 		if (accept) {
+			if (wi >= DOMAIN_PART_MAX_LEN)
+				goto bad;
 			working[wi++] = c;
 			accept = 0;
 			continue;
 		}
 		if (candidate_local != NULL) {
 			/* We are looking for the domain part */
-			if (wi > DOMAIN_PART_MAX_LEN)
+			if (wi >= DOMAIN_PART_MAX_LEN)
 				goto bad;
 			working[wi++] = c;
 			if (i == len - 1) {
@@ -358,7 +358,7 @@ x509_constraints_parse_mailbox(uint8_t *candidate, size_t len,
 			continue;
 		}
 		/* We are looking for the local part */
-		if (wi > LOCAL_PART_MAX_LEN)
+		if (wi >= LOCAL_PART_MAX_LEN)
 			break;
 
 		if (quoted) {
@@ -378,6 +378,8 @@ x509_constraints_parse_mailbox(uint8_t *candidate, size_t len,
 			 */
 			if (c == 9)
 				goto bad;
+			if (wi >= LOCAL_PART_MAX_LEN)
+				goto bad;
 			working[wi++] = c;
 			continue; /* all's good inside our quoted string */
 		}
@@ -407,6 +409,8 @@ x509_constraints_parse_mailbox(uint8_t *candidate, size_t len,
 		}
 		if (!local_part_ok(c))
 			goto bad;
+		if (wi >= LOCAL_PART_MAX_LEN)
+			goto bad;
 		working[wi++] = c;
 	}
 	if (candidate_local == NULL || candidate_domain == NULL)
-- 
cgit v1.2.3-55-g6feb